【问题标题】:Update textbox by navigating DataGridView with arrow keys通过使用箭头键导航 DataGridView 来更新文本框
【发布时间】:2016-09-20 21:16:08
【问题描述】:
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);
}

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

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

任何帮助都会非常友好。

【问题讨论】:

  • CellContentClick 是一个糟糕的选择,因为您必须点击实际内容。为什么你必须 ProcessCmdKey? dgv 应该自己做所有的事情,除非它被禁用。只需编写 CurrentCellChanged 事件!

标签: c# winforms datagridview textbox keydown


【解决方案1】:

当您使用鼠标或箭头键在 DataGridView 的行之间移动时,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();
}

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

【讨论】:

  • 谢谢。我使用了建议的数据绑定方法,但是我确实尝试使用 SelectionChanged 替代方法,但是当我编写 private void dataGridViewCargo_SelectionChanged(object sender, EventArgs e) 时,我似乎没有对我的 dataGridViewCargo 的引用。你知道为什么会这样吗?
  • 不客气。对于第二个选项,您不应忘记使用代码或设计器将事件处理程序附加到事件。还要确保在网格对方法可见的范围内编写事件处理程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
相关资源
最近更新 更多