我在Visual Studio 2010中使用C#。我有一个绑定到DataSource的DataGridViewComboBoxColumn。我想从组合框中选择时,整行改变颜色。我不知道怎么做,因为组合框没有自己独立的名字,它们都属于cbColumn1。我在这里使用这篇文章,但不知道如何使代码工作。 How do I immediately change the row color when the selected index of a DataGridViewComboBox changes?
非常感谢任何帮助
答案 0 :(得分:0)
这样的东西应该有用......你可能需要调整一下,因为我在我自己的程序上测试它可能会设置得相当不同。
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
column.Items.Add("0");
column.Items.Add("1");
column.Items.Add("2");
dataGridView1.Columns.Add(column);
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
ComboBox comboBox = e.Control as ComboBox;
comboBox.DropDownStyle = ComboBoxStyle.DropDown;
comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;
}
}
void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedIndex = ((ComboBox)sender).SelectedIndex;
DataGridViewCellStyle style = new DataGridViewCellStyle();
if (selectedIndex == 0)
{
style.BackColor = Color.AliceBlue;
}
if (selectedIndex == 1)
{
style.BackColor = Color.Beige;
}
if (selectedIndex == 2)
{
style.BackColor = Color.Crimson;
}
dataGridView1.CurrentCell.OwningRow.DefaultCellStyle = style;
dataGridView1.Refresh();
}