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
  • You could drag some other controls too if you like, and you can change what kind they are before you drag. The birthday should come as a datetimepicker etc

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