Sam Teng Wong
Sam Teng Wong

Reputation: 2439

DataGridView get row values

I am trying to get the cell values of the row that I clicked.

here's my code..

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        txtFullName.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
        txtUsername.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
        txtPassword.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
    }

works fine.. but it doesn't work when I click on the row(left side of the UserID) and on user id column... it also gives me an error when I click on the column header. how can I fix that error and I want it to also click on row and userid column.

enter image description here

Upvotes: 6

Views: 28440

Answers (3)

Gregg
Gregg

Reputation: 625

You are using the wrong event: Try this

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex > -1)
        {
            var val = this.dataGridView1[e.ColumnIndex,  e.RowIndex].Value.ToString();
        }
    }

Upvotes: 10

Fabio
Fabio

Reputation: 32445

Use SelectionChanged eventhandler and CurrentRow property of the DataGridView, which were designed exactly for your purposes

void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
    DataGridView temp = (DataGridView)sender;
    if (temp.CurrentRow == null)
        return; //Or clear your TextBoxes
    txtFullName.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
    txtUsername.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
    txtPassword.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
}

And set SelectionMode to the FullRowSelection

this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;    

Upvotes: 5

jhmt
jhmt

Reputation: 1421

To avoid the error caused on clicking column headers, you have to check if e.RowIndex is 0 or more:

void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex == -1) { return; }
    txtFullName.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
    txtUsername.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
    txtPassword.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}

To set an event on clicking row headers, you have to register an event handler to RowHeaderMouseClick event.

dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;

Upvotes: 0

Related Questions