代码摘要来自最小的问题示例:
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.DataGridViewTextBoxColumn colButtonEditedText;
private System.Windows.Forms.DataGridViewButtonColumn ColBrowse;
private System.Windows.Forms.DataGridViewTextBoxColumn colOtherText;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colButtonEditedText,
this.ColBrowse,
this.colOtherText});
this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= 0 && e.ColumnIndex >= 0
&& dataGridView1.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewButtonColumn))
{
dataGridView1.NotifyCurrentCellDirty(true); // needed to make new row appear
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Value
= "some value"; // button helps user edit row
}
}
观察到的行为:
如何使步骤4之后的行为与步骤2之后的行为相同? 6?
我尝试的事情:
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Selected = true;
dataGridView1.BeginEdit(true);
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.LeaveControl);
dataGridView1.EndEdit();
答案 0 :(得分:1)
您看到此行为的原因与Control关注的重点有关。单击Button
单元格会从DataGridView
中删除此焦点,从而阻止CancelEdit
按预期触发。在if-statement
内,请尝试以下操作:
dataGridView1.NotifyCurrentCellDirty(true);
dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex - 1];
dataGridView1.BeginEdit(false);
dataGridView1.EditingControl.Text = "some value";
由于您正在将焦点从Button
单元格更改为已编辑的单元格,因此看起来有点hacky,但是当您点击 Esc 时,您将看到所需的行为。
旁注:我会处理DataGridView.CellContentClick
事件 - 仅在Button
本身被点击而不是整个单元格时触发。