Search code examples
c#databasems-accessdatagridviewtextbox

Bind a textbox to a datagridview row


I want to bind DataGridView Rows all from the same Column to a textbox, to make the text of that cell appear in that textbox when I click on cells from that Column. The problem is I can't use e.RowIndex. Is there any way to do this with properties or code?


Solution

  • You can use the TextBoxes DataBindings property. Something like...

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

    If the grid does not have a data source, then you can wire up the grids SelectionChanged event and reference the grids CurrentRow property. Something like...

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