Pregunta

I am having some trouble with a sorting an unbound DataGridView. I am filling a DataTable from a StreamReader, and then manually transferring the items from the DataTable to the DataGridView. The AllowUserToAddRows property is set to true on the DataGridView.

This populates the DataGridView, without any trouble. I can sort the columns by clicking on the column headers without any issue. If I add a value to the first column in a new row, and then try to sort the column, I get an error message that shows: "Object must be of type String."

I have tried different ways of converting all of the cells in the column to the same datatype, but I cannot get around this issue. Am I missing something here?

In the form load event, I have the following code:

dgvStartingGrid.Columns(0).ValueType = GetType(Integer)

I also am making sure that the values from the StreamReader are Integer types before entering them in the DataGridView:

If IsNumeric(strColumnValue) Then
    dtbFillGrid.Rows(intCurrentRow).Item("Starting Position") = strColumnValue
End If

I have also tried:

dtbFillGrid.Rows(intCurrentRow).Item("Starting Position") = CInt(strColumnValue)

What could cause this issue? I have verified that all of the cells in the column are of the same datatype, but it still gives me an error, and I am sure that it is this column that is the problem.

The other columns are of string type, and I do not have any issue sorting them by their column headers, unless I click the first column, and then the exception is thrown.

¿Fue útil?

Solución

Right, after some testing I found this out.

Even though you have set your DataGridView column to be Integer it doesn't mean that it will be filled with Integers. Unless you alter the datatype of the DataTable the DataGridView is actually filled with strings. The sorting function on a DataGridView is not based on column type, it is based on the first value it finds. And since you that value is a string, you get an error when it reaches your typed value (which is an Integer).

So here is what you have to do.

dtbFillGrid.Columns.Item(0).DataType = GetType(Integer)

Where 0 is the column containing Integer.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top