Note that there are some explanatory texts on larger screens.

plurals
  1. PODataGridView SelectionChanged Event not firing when a new row is selected via code
    primarykey
    data
    text
    <p>I have a DataGridView with its DataSource set to a DataTable. So use this code as an example:</p> <pre><code>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 &lt; 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; </code></pre> <p>I have also subscribed to the SelectionChanged event which just shows the contents on the first cell in a textbox. See below:</p> <pre><code>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(); } } } </code></pre> <p>As I change rows the SelectionChanged event fires and the contents are shown correctly in the textbox.</p> <p>Now I have a button which adds a new row to the grid:</p> <pre><code>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); } </code></pre> <p>The new row is now added to the grid fine but it isn't selected.</p> <p>So I try to select it by subscribing to the RowsAdded Event:</p> <pre><code>private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) { dataGridView1.Rows[e.RowIndex].Selected = true; dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[0]; } </code></pre> <p>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.</p> <p>What can I do to get round this or what am I doing wrong?</p> <p>Strangely if I click the add button again the row that I added on the first click is then selected!?</p> <p>I'm using C#4.0 &amp; Visual Studio 2012.</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload