通过使用箭头键导航 DataGridView 来更新文本框

Update textbox by navigating DataGridView with arrow keys

public delegate void MyEventHandler(object sender, DataGridViewCellEventArgs e);
public event MyEventHandler SomethingHappened;    

private void dataGridViewCargo_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DataGridViewRow rowID = this.dataGridViewCargo.Rows[e.RowIndex];
        cargoDisplayMessageIdTextBox.Text = rowID.Cells["iDDataGridViewTextBoxColumn"].Value.ToString();

        DataGridViewRow rowSender = this.dataGridViewCargo.Rows[e.RowIndex];
        cargoDisplaySubjectTextBox.Text = rowSender.Cells["subjectDataGridViewTextBoxColumn"].Value.ToString();

    }
}



protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    Invoke(new MyEventHandler(SomethingHappened));
    return base.ProcessCmdKey(ref msg, keyData);
}

第一部分在我 select 行时更新我的​​文本框。第二部分是对事件处理程序的尝试。我想通过使用键盘在网格中导航来更新文本框。因此,以蓝色突出显示的任何行都会自动填充文本框。

我试图通过将事件处理程序包含在 dataGridViewCargo_CellContentClick 中来调用它,但是 sender 和 e 没有通过,我收到参数计数不匹配错误或委托给实例方法不能有 null 'this'.这个想法是通过按下按钮来调用 CellContentClick 事件。

如有帮助将不胜感激。

当您使用鼠标或箭头键在您的行之间移动时 DataGridView 是数据绑定的,其数据源的位置会发生变化,并且绑定到同一数据源的所有控件将显示来自新职位。

此外,如果您不使用数据绑定,DataGridViewSelectionChanged 事件将被引发并可用于更新控件。

因此您可以使用以下任一选项来解决问题:

  • 将那些 TextBox 控件绑定到 DataGridView 使用的同一数据源。

  • 使用 DataGridViewSelectionChanged 事件。

如果您将 DataGridView 绑定到 DataSource,那么您也可以简单地为 TextBox 控件使用数据绑定。通过单击每一行将那些 TextBox 控件绑定到要显示的数据源字段就足够了。您可以使用设计器或使用代码执行数据绑定:

var data = GetDataFromSomeShere();
dataGridViewCargo.DataSource = data;
cargoDisplayMessageIdTextBox.DataBindings.Add("Text", data, "ID");
cargoDisplaySubjectTextBox.DataBindings.Add("Text", data, "Subject");

如果你不使用数据绑定,你可以简单地使用DataGridViewSelectionChanged事件和DataGridViewCurrentRow 属性来找到这些字段并更新您的 TextBox 控件:

private void dataGridViewCargo_SelectionChanged(object sender, EventArgs e)
{
    var row = dataGridViewCargo.CurrentRow;
    cargoDisplayMessageIdTextBox.Text = 
        row.Cells["iDDataGridViewTextBoxColumn"].Value.ToString();
    cargoDisplaySubjectTextBox.Text =
        row .Cells["subjectDataGridViewTextBoxColumn"].Value.ToString();
}

首选使用数据绑定(第一个选项)。