user6807975 user6807975 - 18 days ago 15
C# Question

which DataGridView event to call after a row is selected

My

DataGridView
contains ~200 rows, each of them containing some user info (such as Last name). When an user selects any of these rows, I need to retrieve the ID of selected row in order to query my database for more info. As such, when the user selects a row, I iterate through the whole list untill I find matching ID. Here's the code to visualize what I'm talking about:

if (e.RowIndex > -1)
{
int selectedId = Convert.ToInt32(dataGridView.Rows[e.RowIndex].Cells["IdColumn"].Value);
foreach (var user in Users)
if (user.Id == selectedId)
{
SelectedUser = GetUserById(user.Id);
break;
}
}


Now, the event I'm using here is
DataGridView.RowEnter
and it's a problem because this event fires even when the list is loaded for the first time, thus executing
foreach
loop at the very least a hundred times.

So the question is: which event should I use so that the code above is executed only once, after a row is selected?

Answer

The most viable option was proposed by @LarsTech in a comment: connecting the event only after all data is loaded. And since my data is sorted after being loaded, I executed it like this:

private void dataGridView_Sorted(object sender, EventArgs e)
    {
        this.dataGridView.SelectionChanged -= new System.EventHandler(this.dataGridView_SelectionChanged);
        this.dataGridView.SelectionChanged += new System.EventHandler(this.dataGridView_SelectionChanged);
    }

(I also used the code provided by @Karthik to make the event SelectionChanged-based instead of RowEnter-based)