Marci Marci - 1 year ago 195
C# Question

How to Copy values from a Datagridview selected row to textboxes

I am trying to select a datagridview row and copy values to 3 textbox.

I tried this code (it works in another my project), but I got an error. This is the code:

private void DataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
if (e.RowIndex >= 0)
DataGridViewRow row = this.DataGridView2.Rows[e.RowIndex];

textBox1.Text = row.Cells["HomeNM"].Value.ToString();
textBox3.Text = row.Cells["HostNM"].Value.ToString();
fromTxt.Text = row.Cells["odd1NM"].Value.ToString();


This is my error:

Error 1 ' bexscraping.Form1 ' does not contain a definition of ' DataGridView2 ' and has not been found no extension method ' DataGridView2 ' accepting a first argument of type ' bexscraping.Form1 ' . Probably missing a using directive or a reference to an assembly.

I don't know where is the error- Any idea?

EDIT: I forgot to initialize my datagridview;M now my code is working! Anyway thanks!

Answer Source

Make sure that the gridView is initialzed. Then try this

private void dataGridView1_Click(object sender, EventArgs e)
           textBox1.Text = dataGridView1.SelectedRows[0].Cells["HomeNM"].Value.ToString();
           textBox2.Text = dataGridView1.SelectedRows[0].Cells["HostNM"].Value.ToString();
            textBox3.Text = dataGridView1.SelectedRows[0].Cells["odd1NM"].Value.ToString();
   } // haha
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download