An exception throws when DataGridView column header clicked to sort after the filtering applied to DataGridView

  • Thread starter Thread starter AndieDu
  • Start date Start date
A

AndieDu

Guest
Hi team,

I am facing an issue whereby when I click the DataGridView column header to sort, the application throws this exception: HResult=0x80070057 Message=Object must be of type String, plz be aware that there are blank or null values in the corresponding cells. However, there are blank or null values in the corresponding cells before filtering and there was no issues to sort by click the column header.

I have a DataGridView and ComboBox controls on my form, and once the data loaded into the DataGridView (plz be aware that the data is loaded from database hence all the columns are auto binding to the DataGridView), the ComboBox control is epopulated and enabled and once a value selected in the ComboBox control, the DataGridView will be filtered based on the selected value in ComboBox.

This is the code to filter the DataGridView based on the selected value in ComboBox:

public static void FilerDataGridView(DataTable dt, string filterColumnName, string selectedItem, DataGridView dgv, int numberOfCells)
{
try
{
dgv.DataSource = null;
dgv.Rows.Clear();

DataView dv = dt.DefaultView;
if (dgv.Columns.Count == 0)
{
foreach (DataColumn dc in dt.Columns)
{
dgv.Columns.Add(dc.ColumnName, dc.ColumnName);
}
}

if (selectedItem.ToLower() != "all")
{
dv.RowFilter = string.Format("" + filterColumnName + " = '{0}'", selectedItem);
if (dv.Count > 0)
{
dgv.Rows.Add(dv.Count);
for (int j = 0; j < numberOfCells; j++)
{
for (int i = 0; i < dv.Count; i++)
{
dgv.Rows.Cells[j].Value = dv.Row.ItemArray[j];
}
}
}
}
else
{
dgv.Rows.Add(dt.Rows.Count);
for (int j = 0; j < numberOfCells; j++)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
dgv.Rows.Cells[j].Value = dt.Rows[j];
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

The funny thing was i dont have any event handler of the DataGridView ColumnHeader click and i cant debug the code and the exception was directly thrown at the enter point of the application:

Application.Run(new frmMain());

Could someone plz in here shed me a light on this.

Many thanks.

Andie.

Continue reading...
 
Back
Top