DataGridViewComboBoxCell 默认显示行值

DataGridViewComboBoxCell show row value as default

我想在 DataGridView 中的任何行的特定列中放置一个 DataGridViewComboBoxCell。 现在我遇到了问题...我想在我放置 DataGridViewComboBoxCell 的特定列中显示默认值,但没有显示任何内容..

String[] options = new String[] {"On", "Off" };

for(int i = 0; i< rows.Count; i++)
{
     // lets say one row looks like this {"1","On"}, {"2", "Off"}
     MydataGridView.Rows.Add(rows[i]);

     DataGridViewComboBoxCell MyComboBox= new DataGridViewComboBoxCell();
     MyComboBox.Items.AddRange(options);

     MydataGridView.Rows[i].Cells[1] = MyComboBox;

}

我想默认显示我添加的行,然后才能通过 DataGridViewComboBoxCell.

select {"On","Off"} 状态

我希望已经足够清楚了。 :)

这个呢(DataGridView.CellFormatting Event):

public Form1()
{
    InitializeComponent();
    MydataGridView.CellFormatting += MydataGridView_CellFormatting;
}

private void MydataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 1) //Index of your DataGridViewComboBoxCell 
    {
        e.Value = "yourDefaultValue";
    }
}

我也看到了以下事件,它也用于设置默认值 (DataGridView.DefaultValuesNeeded Event):

public Form1()
{
    InitializeComponent();
    MydataGridView.DefaultValuesNeeded += MydataGridView_DefaultValuesNeeded;
}

private void MydataGridView_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
    e.Row.Cells[1].Value = "yourDefaultValue";
}