我有两列的DataGridView
。第一列是TextBoxCol(DataGridViewTextBoxColumn)
,第二列是ComboBoxCol(DataGridViewComboBoxColumn)
。
当ComboBoxCol
更改其选定的索引值时,如何更改TextBoxCol
的值?(当所选索引在ComboBoxCol
中更改时,应该会发生这种情况。不是在离开专栏之后,就像dataGridView_CellValueChanged
一样)
我读了一个主题,几乎有相同的问题,但我不明白答案(根据复选标记应该是正确的)。这是链接。-Almost same topic
发布于 2012-06-22 02:17:47
尝试这两个简单的方法( top方法中的'1‘是combobox列的索引)
您要修改的行将是setter行cel.Value =
,因为您可以将其更改为您喜欢的任何行。
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1 && e.Control is ComboBox)
{
ComboBox comboBox = e.Control as ComboBox;
comboBox.SelectedIndexChanged -= LastColumnComboSelectionChanged;
comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged;
}
}
private void LastColumnComboSelectionChanged(object sender, EventArgs e)
{
var currentcell = dataGridView1.CurrentCellAddress;
var sendingCB = sender as DataGridViewComboBoxEditingControl;
DataGridViewTextBoxCell cel = (DataGridViewTextBoxCell)dataGridView1.Rows[currentcell.Y].Cells[0];
cel.Value = sendingCB.EditingControlFormattedValue.ToString();
}
发布于 2014-01-24 07:52:58
这个答案在几个地方流传开来。
使用DataGridViewEditingControlShowingEventHandler将触发比预期更多的事件。在我的测试中,它多次触发事件。
另外,使用combo.SelectedIndexChanged -=事件并不会真正删除事件,它们只是继续堆叠。
不管怎样,我找到了一个似乎可行的解决方案。我包含了下面的代码示例:
// Add the events to listen for
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
// This event handler manually raises the CellValueChanged event
// by calling the CommitEdit method.
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
// This fires the cell value changed handler below
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// My combobox column is the second one so I hard coded a 1, flavor to taste
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[1];
if (cb.Value != null)
{
// do stuff
dataGridView1.Invalidate();
}
}
https://stackoverflow.com/questions/11141872
复制相似问题