C#Datagridview ComboBox选择值棒

时间:2010-02-15 23:51:55

标签: c#

我希望能够在datagridview中的组合框中显示所选的intem。我已经填充了组合框,我已经知道如何从数据库中获取所选值。我想要完成的是,无论何时加载表单,组合框中的任何预先选择的值都会自动预选,以向用户显示他们最后选择的内容。我有一个存储选择的数据库,可以轻松访问它们。同样,我如何使选择坚持用户选择的任何内容,以便每次打开表单时都会记住它们,除非有人更改其选择并保存。我没有像往常那样在datagridview组合框中看到一个value.selected。有没有人得到这个工作?

以下是一个例子:

我在一个名为test的datagridiew中嵌入了一个组合框作为列名

有4个字段可供选择:

  
      
  1. TEST1
  2.   
  3. TEST2
  4.   
  5. TEST3
  6.   
  7. TEST4
  8.   

让我们说这次我选择test3作为我的选择。我关闭表单,选择保存到数据库。现在我知道如何从数据库中检索该值,但是当表单作为显示成员加载时如何使测试3显示,如果我选择,仍然可以选择另一个?

2 个答案:

答案 0 :(得分:1)

处理Cell Validating事件,如下所示......

void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (cell is DataGridViewComboBoxCell)
    {        
        DataGridViewComboBoxCell cell = DataGridViewComboBoxCell)dataGridView1.CurrentCell;
        cell.Items.Clear();
        cell.Items.Add(e.FormattedValue);
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        cell.Value = e.FormattedValue;
    }
}

基本上你必须将选定的值添加到单元格的items集合中,然后将value =设置为添加的值。如果值不在items集合中,您将在单元格上获得DataError事件。

单元格项集合与ComboBox项目集合不同。

这是如何处理根据选择设置单元格的值。

如果您处理datagridview的EditingControlShowing事件,您可以在单击时访问组合框控件,并在为用户绘制之前将所选项目设置为单元格的当前值。

void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (dataGridView1.CurrentCell is DataGridViewComboBoxCell
            && e.Control is DataGridViewComboBoxEditingControl)
        {
            DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1.CurrentCell;
            ComboBox ctrl = (ComboBox)e.Control;
            // Get Currently selected value...
            string curValue = String.Empty;
            if (cell.Value != null)
                curValue = cell.Value.ToString();

            //bind data
            ctrl.DataSource = dataBaseData;
            //set selected value
            ctrl.SelectedItem = curValue;
        }

    }

答案 1 :(得分:0)

我相信您需要做的就是在单元格上设置.Value,它会自动设置所选项目。您可以遍历所有单元格并将它们设置为先前选择的值。