我正在尝试在我的DataGridView中获取ComboBoxes,以便在更改所选索引后更改颜色。当单元格的选定索引发生变化时,我可以让它们成功地将颜色从白色变为黄色,但是当我离开单元格时再次变为白色。我不知道为什么会这样做。
下面提供的代码来自我的继承自DataGridView的类。
我在构造函数中添加了EditingControlShowing侦听器:
this.columnCardName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.columnCardNumber = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.extraColumns = new List<DataGridViewColumn>();
this.blocks = blocks;
this.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.Location = new System.Drawing.Point(81, 54);
this.Name = "dataGridView1";
this.RowTemplate.Height = 24;
this.Size = new System.Drawing.Size(1589, 934);
this.TabIndex = 0;
this.EditingControlShowing += dataGridView_EditingControlShowing; // This is where I add the event handler
这是我用来生成ComboBoxes列的代码:
DataGridViewComboBoxColumn column = new System.Windows.Forms.DataGridViewComboBoxColumn();
column.DropDownWidth = SMALL_COLUMN_WIDTH;
column.HeaderText = columnHeader;
column.Name = columnName;
column.DropDownWidth = 160;
column.Width = SMALL_COLUMN_WIDTH;
DataTable data = new DataTable();
data.Columns.Add(new DataColumn("Value", typeof(string)));
data.Rows.Add("N");
data.Rows.Add("M");
data.Rows.Add("Q");
column.DataSource = data;
column.ValueMember = "Value";
this.Columns.Add(column);
最后,这些是我对EditingControlShowing和SelectedIndexChanged的处理程序:
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
if (e.Control is ComboBox) {
((ComboBox)e.Control).SelectedIndexChanged -= new EventHandler(comboBoxEventHandler);
((ComboBox)e.Control).SelectedIndexChanged += new EventHandler(comboBoxEventHandler);
}
}
private void comboBoxEventHandler(object sender, EventArgs e) {
Console.WriteLine("Event firing "+e.GetType());
((ComboBox)sender).BackColor = System.Drawing.Color.Yellow;
}
答案 0 :(得分:1)
尝试使用以下代码:
DataGridViewComboBoxColumn myCombo = new DataGridViewComboBoxColumn();
dataGridView1.DataSource = dataSetFromDatabaseCall.Tables[0];
myCombo.HeaderText = "My Combo";
myCombo.Name = "myCombo";
this.dataGridView1.Columns.Insert(1, myCombo);
myCombo.Items.Add("test1");
myCombo.Items.Add("test2");
myCombo.Items.Add("test3");
//event to check the cell value changed
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == myCombo.Index && e.RowIndex >= 0) //check if it is the combobox column
{
dataGridView1.CurrentCell.Style.BackColor = System.Drawing.Color.Yellow;
}
}
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}