将文本框绑定到 datagridview 行

Bind a textbox to a datagridview row

我想将同一列中的所有 DataGridView 行绑定到一个文本框,以便在我单击该列中的单元格时使该单元格的文本显示在该文本框中。问题是我不能使用 e.RowIndex。有什么方法可以用属性或代码做到这一点吗?

可以使用TextBoxesDataBindings属性。像...

textBox1.DataBindings.Add(new Binding("Text", GridDataSource, "ColumnOrPropertyName"));

如果网格没有数据源,那么您可以连接网格 SelectionChanged 事件并引用网格 CurrentRow 属性。像...

private void dataGridView1_SelectionChanged(object sender, EventArgs e) {
  if (dataGridView1.CurrentRow != null) {
    textBox1.Text = dataGridView1.CurrentRow.Cells["ColumnName"].Value.ToString();
  }
}