0
votes

I have a DataGridView with its DataSource set to a DataTable. So use this code as an example:

DataTable table;
table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Last_Name", typeof(string));
table.Columns.Add("Male", typeof(Boolean));

DataRow row;

for (int i = 1; i < 10; i++)
{
    row = table.NewRow();
    row["Name"] = String.Format("Person {0}", i + 1);
    row["Last_Name"] = String.Format("Person Last Name {0}", i + 1);

    if (i % 2 == 0)
    {
        row["Male"] = true;
    }
    else
    {
        row["Male"] = false;
    }

    table.Rows.Add(row);
}

dataGridView1.DataSource = table;

I have also subscribed to the SelectionChanged event which just shows the contents on the first cell in a textbox. See below:

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    if (dataGridView1.CurrentRow != null)
    {
        DataRowView row = dataGridView1.CurrentRow.DataBoundItem as DataRowView;
        if (row != null)
        {
            textBox1.Text = row.Row[0].ToString();
        }
    }
}

As I change rows the SelectionChanged event fires and the contents are shown correctly in the textbox.

Now I have a button which adds a new row to the grid:

private void buttonAdd_Click(object sender, EventArgs e)
{
    DataRow row= table.NewRow();
    row["Name"] = "Bob";
    row["Last_Name"] = "Smith";
    row["Male"] = true;
    table.Rows.Add(row);
}

The new row is now added to the grid fine but it isn't selected.

So I try to select it by subscribing to the RowsAdded Event:

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{            
    dataGridView1.Rows[e.RowIndex].Selected = true;
    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[0];
}

So this now selects the row correctly but the SelectionChanged event doesn't fire and the textbox is still showing the result of the previously selected row.

What can I do to get round this or what am I doing wrong?

Strangely if I click the add button again the row that I added on the first click is then selected!?

I'm using C#4.0 & Visual Studio 2012.

Thanks

1

1 Answers

0
votes

Well first of all why not select row after adding and changing label there?

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{            
    dataGridView1.Rows[e.RowIndex].Selected = true;
    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[0];

    textBox1.Text =  dataGridView1.Rows[e.RowIndex].ToString();
}

if you want to change label only by firing event you can try deselecting cell first:

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    dataGridView1.CurrentCell = null;

    dataGridView1.Rows[e.RowIndex].Selected = true;
    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[0];

    textBox1.Text =  dataGridView1.Rows[e.RowIndex].ToString();
}