0

我在datagridview中有一个DataGridViewComboBoxCell。我在form_load中加载值。它最初在DataGridViewComboBoxCell中显示为空白,当添加新行时。但我的问题是我如何设置默认值,说“其他” DataGridViewComboBoxCell.So 每当我尝试添加新行时,它都会在其中显示默认项。

我想向您展示我的代码。

DataGridViewComboBoxCell comboItem_current = dataGridView1.CurrentRow.Cells[2] as DataGridViewComboBoxCell;

                comboItem_current.Items.Clear();
                comboItem_current.Items.Add("Other");

                foreach (DataRow dr in ds_Item.Tables[0].Rows)
                {
                    DataGridViewComboBoxCell comboItem1 = dataGridView1.CurrentRow.Cells[2] as DataGridViewComboBoxCell;  
                    comboItem1.Items.Add(dr[1].ToString());

                }

请帮忙....谢谢

4

3 回答 3

3

我知道这是一篇古老的帖子,但希望我能帮助一些人避免我的困惑。

使用 CellFormatting 是一个失败者,因为它每次接触到单元格时都会调用它。结果是该值不断地设置回默认值。

对我有用的是像这样处理 DefaultValuesNeeded 事件:

private void OnGridDefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
    e.Row.Cells["Position"].Value = PositionEnum.Any;
}

这允许我设置默认值,并让用户更改值。

于 2013-07-30T00:17:31.897 回答
0

您可以这样做:设置 DatagridviewComboBoxColumn 默认值

或者这样:

只需CellFormatting为 datagridview 添加事件

void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 0) //Index of your DataGridViewComboBoxColumn 
    {
        e.Value = "Default Value";
    }
}
于 2012-08-21T13:23:43.743 回答
-1

为什么不保持简单,只使用类似的东西

<DataGridComboBoxColumn SelectedItemBinding="{Binding MyProp}" Width="*" Header="MyHeader" ></DataGridComboBoxColumn>

当然,您的 DataGrid 需要使用 IEnumerable 设置 DataContext 属性,其中 MyObj 具有 MyProp

于 2012-08-21T13:40:13.423 回答