Best way to handle errors caused by trying to order rows in a DataGridView with null values
If you add some null
values on some cells in a DataGridView
and then try to order by the column where the null
values were added by clicking on the header, you will get a "Object must be of type String" exception, and the program will crash. How should I handle this? I want the user to be able to order by clicking on the header. Does this mean my only choice is to replace all null
or DBNull
values to something like ""
? Or can I 开发者_Go百科somehow catch the exception?
How is the data on the grid? If it is data-bound to a collection, you can implement IBindingList
and provide your own ApplySort
method that accounts for null
however you choose. You also need to provide suitable implementations of SupportsSorting
, SortDirection
and SortProperty
.
But personally, I would just remove the null
s for now; so yes, a ""
is a reasonable alternative to null
in a string column; trickier for some other cases.
精彩评论