Load Data of DataGridView's Selected Row to TextBox Control in C#/CSharp

The following example loads the data of the Selected Row in a DataGridView control into a TextBox control in CSharp. As shown on the previous example Populate Data Into DataGridView using For-Loop in C#/CSharp, we'll use that method to fill our DataGridView with data.
To begin with:
1.) Start start a new C# project.
2.) Add the following controls onto Form1.
  • (1) DataGridView Control
  • (2) TextBoxes
  • (2) Labels
3.) Open the Windows Form Designer and Update the DataGridView's generated code with the following.
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(12, 12);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(240, 221);
this.dataGridView1.TabIndex = 0;
this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
4.) Add the following codes into the Form1_Load() Event to fill the dataGridView control with data.

 Random rand = new Random();
 DataGridView dgv = this.dataGridView1;
           
 //DATAGRIDVIEW SETTING
 dgv.AllowUserToAddRows = false;
 dgv.AllowUserToResizeRows = false;
 dgv.RowHeadersVisible = false;
 dgv.ReadOnly = true;
 dgv.MultiSelect = false;
 dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

 //ADD COLUMN HEADERS
 dgv.Columns.Add("Product", "Product");
 dgv.Columns.Add("Price", "Price");

 //ADD 10 ROWS
 dgv.Rows.Add(10);

 //NOW, POPULATE THE DATA INTO THE CELLS
 for (int i = 0; i < 10; i++)
 {
     double price = rand.Next(1, 30) * rand.NextDouble();

     dgv.Rows[i].Cells[0].Value = "Product " + i;
     dgv.Rows[i].Cells[1].Value = "$ " + price;
 }

 //CLEARS THE DEFAULT SELECTION WHICH IS THE FIRST ROW
 dgv.ClearSelection();

5.) Add the following code to handle on CellClick() Event of the dataGridView Control.

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dgv = this.dataGridView1;
    txtProduct.Text = dgv.SelectedRows[0].Cells[0].Value.ToString();
    txtPrice.Text = dgv.SelectedRows[0].Cells[1].Value.ToString();
}

6.) Build and Compile the Project. The project can also be downloaded here.

OUTPUT:


Comments

Popular posts from this blog

How to Create a Configuration.INI Files in VB6

How to Set Windows Form Always on Top of Other Applications in VB6

Populate Data Into DataGridView using For-Loop in C#/CSharp