1
votes

I want to sort a DataGridView by a column when the form loading, but I got an exception.

    private void frm_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'dataSetExclusion.Exclude' table. You can move, or remove it, as needed.
        this.excludeTableAdapter.Fill(this.dataSetExclusion.Exclude);
        this.dgv.Sort(this.dgv.Columns["ID"], ListSortDirection.Ascending); 
    }

The column's headtext in the DataGridView dgv is "ID". Its DataPropertyName is "ExcludeID". I tried both "ID" and "ExcludeID" for the column name, but still got the exception.

Value cannot be null.Parameter name: dataGridViewColumn
3
If you set a breakpoint at the Sort line and examine this.dgv.Columns, do you see "ID" or "ExcludeID" in the list? Where have you set the dgv.DataSource? - Kelly Cline

3 Answers

2
votes

Try to check the name property of that column like shown below

enter image description here

0
votes

The column's name may be different than it's textual representation. According to the documentation, that indexer is looking at the Name property and not the HeaderText property. The column designer should let you change the name or see what it currently is.

0
votes

There are two possible causes of this issue, either you have not bound your DataGridView or you are using an incorrect column name.

In your form load your don't appear to ever bind the datasource of the grid. You need to change your code to something like this (guessing that dataSetExclusion.Exclude is what you want in the grid?):

private void frm_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'dataSetExclusion.Exclude' table. You can move, or remove it, as needed.
    this.excludeTableAdapter.Fill(this.dataSetExclusion.Exclude);
    this.dgv.DataSource = this.dataSetExclusion.Exclude;
    this.dgv.Sort(this.dgv.Columns["ID"], ListSortDirection.Ascending); 
}

There are various ways to check the column name - you could always place a break point method here and look in the debugger, or you could look in the DataSet Designer. The column name in the grid will match the column name in the designer (if you are using form designer columns and dataproperty names then look in the form designer for the name instead).

Note that the Name and the HeaderText do not have to match so using the HeaderText will often not work.