在我的 datagridview 中,我在 winforms 中有一个文本框列和一个可编辑的组合框列。但是在组合框文本中键入新值并按回车键时,我没有将键入的值作为相应的单元格值。有人可以吗帮助解决这个问题。
private void dgv_customAttributes_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow row = dgv_customAttributes.CurrentRow;
if (row.Cells[1].Value.ToString() != null)
{
//Here the selectedVal is giving the old value instead of the new typed text
string SelectedVal = row.Cells[1].Value.ToString();
foreach (CustomAttribute attribute in customAttributes)
{
if (row.Cells[0].Value.ToString() == attribute.AttributeName)
{
attribute.AttributeValue = SelectedVal;
break;
}
}
}
}
最佳答案
您需要在显示时找出组合框,并在所选索引更改时为它们附加一个事件处理程序(因为无法从列或单元格本身获取该信息)。
这意味着,不幸的是,捕获事件 CellEndEdit 是无用的。
在下面的示例中,文本框填充了所选选项,但您可以执行任何其他操作,例如在枚举变量中选择特定值或其他任何操作。
void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
{
if ( e.Control is ComboBox comboEdited ) {
// Can also be set in the column, globally for all combo boxes
comboEdited.DataSource = ListBoxItems;
comboEdited.AutoCompleteMode = AutoCompleteMode.Append;
comboEdited.AutoCompleteSource = AutoCompleteSource.ListItems;
// Attach event handler
comboEdited.SelectedValueChanged +=
(sender, evt) => this.OnComboSelectedValueChanged( sender );
}
return;
}
void OnComboSelectedValueChanged(object sender)
{
string selectedValue;
ComboBox comboBox = (ComboBox) sender;
int selectedIndex = comboBox.SelectedIndex;
if ( selectedIndex >= 0 ) {
selectedValue = ListBoxItems[ selectedIndex ];
} else {
selectedValue = comboBox.Text;
}
this.Form.EdSelected.Text = selectedValue;
}
找到 complete source code for the table in which a column is a combobox in GitHub .
希望这对您有所帮助。
关于c# - 未在可编辑组合框中获取键入的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52257984/