We help IT Professionals succeed at work.

Copying the content of a cell in a dataGridView into a textbox

adamtrask
adamtrask asked
on
Hello,

I am playing with code in an attempt to copy the value of a cell on a dataGridView into a TextBox:

I used the code below to identify the selected row in the dataGridView before trying to copy the content of the desired cell

Obviously there is some thing wrong in this code since the closing bracket which follows the word "Value" get a red line indicating a syntax error...
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            Int32 rowToUpdate = this.dataGridView1.Rows.GetFirstRow(
     DataGridViewElementStates.Selected);
            if (rowToUpdate > -1)
            {
                this.txtDate.Text = this.dataGridView1.Rows[rowToUpdate].Cells[0].Value[];
                
            }

Open in new window

Comment
Watch Question

Commented:
this.txtDate.Text = this.dataGridView1.Rows[rowToUpdate].Cells[0].Value;

Open in new window

Author

Commented:
Actually I ended up using the code below but nothing is copied to the textBox when I click the button
private void button1_Click(object sender, EventArgs e)
        {
            Int32 rowToUpdate = this.dataGridView1.Rows.GetFirstRow(
     DataGridViewElementStates.Selected);
            if (rowToUpdate > -1)
            {
                this.txtName.Text = this.dataGridView1.Rows[rowToUpdate].Cells[2].Value.ToString();
                //this.dataGridView1.Rows.RemoveAt(rowToDelete);
            }

Open in new window

Commented:
Line three in your code
Int32 rowToUpdate = e.RowIndex;

Open in new window

Author

Commented:
@nepaluz:

I am afraid I don't follow...

do you want me to replace the following line of code:

Int32 rowToUpdate = this.dataGridView1.Rows.GetFirstRow(DataGridViewElementStates.Selected);

with:
Int32 rowToUpdate = e.RowIndex;


Commented:
Yes, as in your original code inside
dataGridView1_CellContentClick

Open in new window

and not the updated code of
button1_Click

Open in new window

Author

Commented:
Ok..... It's working. Thanks a lot
}

Open in new window

Author

Commented:
Thank you