简体   繁体   中英

how do I get the data from selected row by its column name from datagridview in c#

Hello I have a table that contains 5 column. One of the column name is "mail". I want to get the data from selected row by its column name.

for example: when I click a row, I want to show the data of the mail column in a textbox

how do I achieve that?

You bind the datagridview and the textbox to the same bindingsource

Follow these steps in a new form (so it doesn't disturb what you have)

  • Add a new file of type DataSet to your project
  • Open it, right click the surface, choose add DataTable. Call it Person
  • Right click the table and add a column, call it Name
  • Right click again, add column, Age - make it type int
  • Again, Birthday, make it datetime (just to add some different datatypes)
  • Save and close the designer
  • Open the Form1 designer. Show the DataSources window (view menu>>other windows)
  • Drag the Person node onto the form. A DataGridView appears, along with a BindingSource, DataSet and some other stuff in the tray at the bottom. You can remove the navigator if you want. The DGV is bound to the bindingsource. The bindingsource is bound to the dataset
  • Expand the Person node in DataSources, see the textbox for Name underneath it? Drag that to the form too. A textbox appears. Its Text proeprty is also bound to the bindingsource

That's it; the designer has set up everything necessary for your desired behavior to work. You can see the code it has written in Form1.Designer.cs if you want

Run the program, add some data to the grid and then click up and down the rows. The data in the textbox changes.. If you change the textbox, the grid is updated

The process embodies MVC - you keep your data in a model (the datatable), you view it via the grid or textbox and you control (change) it again via the grid/textbox (though perhaps you'd make the grid readonly so it just was more a Viewer role, and devolve the Control role to the textbox

Just handle CellClick event of DataGridView and like below -

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
      txtMail.Text = dataGridView1.Rows[e.RowIndex].Cells["mail"].Value.ToString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM