Search in This Blog

Object must be of type String while sorting datagridview

Object must be of type String

You are working with DataGridView with  several columns. You want to make sort of one column name "marks". then you will simply use below one line of code:

dataGridView1.Sort(dataGridView1.Columns["marks"], ListSortDirection.Ascending); 


But you may get error message as below:

System.ArgumentException was unhandled
  Message="Object must be of type String."
  Source="mscorlib"
  StackTrace:
       at System.String.CompareTo(Object value)
       at System.Collections.Comparer.Compare(Object a, Object b)
       at 
       .......................................
       .......................................
       at System.Threading.ThreadHelper.ThreadStart()

  InnerException: 

Let me try to understand you why the error message "Object must be of type String." You are getting when sorting "marks".

Very first time You are getting data from database and storing in the your datagridview something like this, note that string marks:

string marks = ds.Tables[0].Rows[grid_sr_no]["marks"].ToString();
dataGridView1.Rows[i].Cells["marks"].Value = mark;


after some processing in the seconds time you are string marks as intereger like this:

int marks = Convert.ToInt32(ds1.Tables[0].Rows[0]["marks"].ToString());
dataGridView1.Rows[i].Cells["marks"].Value = marks;


Then after if you use sorting code as below:
dataGridView1.Sort(dataGridView1.Columns["marks"], ListSortDirection.Ascending); 

You will get error message:
System.ArgumentException was unhandled
 Message="Object must be of type String."


so, to overcome this problem only use similar datatype while storing in datagridview.
alternatively you can use below code:
dataGridView1.Rows[i].Cells["marks"].Value = marks.ToString();






Previous
Next Post »