DataGridView is used very often especially in database application. In most cases this control is very easy to use. Unfortunately it isn't free of bugs so it can cause us a lot of problems. For your convenience I will present most of the potential problems.
First problem occurs when we try to select programmatically any row. This is very easy to do:
dgvMain.Rows.Selected = true;
Unfortunatelly when we did it before the form is displayed e.g in the constructor then row will be selected but not highligtted.
The second problem is more subtle. The DataGridView control has a property named AutoGenerateColumns. If this property is set to true then DataGridView will generate columns for all public properties of datasource. In the other case we need to create columns manually. Visual studio provides us the following GUI for this purpose:
For each column we can assign descriptable name. Unfortunatelly this don't have any sense because each time we will assign null to the datasource then columns will be recreated and our names disapear. The main conclusion from this is that you should never use the names of the columns to manipulate a collection of columns. Instead, you should use the index of columns. Please look at the following example:
dgvMain.DataSource = GetData(10); dgvMain.DataSource = null; dgvMain.DataSource = GetData(6);
After the first line collection of columns in dgvMain DataGridView contains columns with names:
This is obvious. Those name has been assign in designer. The magic thing occurs after line number three. at this point the column names will be as follows: