Reputation: 53
This is a really weird error I've never had before. I have added a checkbox to my datagridview like this:
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
datagrid.Columns.Insert(0, checkBoxColumn);
I get the error
Specified cast is not valid
And it highlights this in cell formating of the datagrid:
for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
{
if ((int)datagrid.Rows[e.RowIndex].Cells[7].Value <= 5)
{
this.datagrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}
This checks if a value in cell 7 is below the value or equal to 5 and if it is changes it to red. I have tried changing the cell to 8 because I thought it had moved since I've added a new column at 0 however it didn't work.
Upvotes: 0
Views: 2750
Reputation: 4819
Try using int.TryParse
which will only parse the cell's value if it can be successfully parsed to an int
. Like this:
int temp;
for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
{
if (int.TryParse(datagrid.Rows[e.RowIndex].Cells[7].Value.ToString(), out temp) == true)
{
if (temp <= 5)
{
this.datagrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}
}
At the very least this will stop throwing an exception and you can determine if your cell formatting is working correctly or not. I'm guessing you have a row in your data set that has a bad or null value in column 7 and/or 8. If you added this new checkbox column at position zero then you will need to now reference .Cells[8]
.
A better way to reference columns is by their name. Then if you add or delete columns in the future you don't mess up the rest of your column index references throughout your code. Try this if you get the above working:
if (int.TryParse(datagrid.Rows[e.RowIndex].Cells["yourColumnName"].Value, out temp) == true)
In order to use this method, you must specify the .Name
column when you create and add the columns.
Upvotes: 1
Reputation: 2688
Try this
for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
{
if (Convert.ToInt32(datagrid.Rows[e.RowIndex].Cells[7].Value) <= 5)
{
}
Upvotes: 3