Casting Problem On DatagridViewtextBoxColumn
I have noticed that DatagridviewtextBoxColumn is not casting to Decimal. I have demonstrate it by two ways which are as follows.
DataTable :-
DataTable dt = new DataTable(); dt.Columns.Add("carats"); d开发者_运维百科t.Columns.Add("rate"); dt.Columns.Add("amount"); dataGridView1.DataSource = dt;
It works fine with Following casting code
private void dataGridView1_CellEndEdit(object sender,DataGridViewCellEventArgs e)
{
int b = dataGridView1.CurrentCell.RowIndex;
if (
dataGridView1[0, b].Value != DBNull.Value &&
dataGridView1[1, b].Value != DBNull.Value
)
{
dataGridView1[2, b].Value = Convert.ToDecimal(dataGridView1[0, b].Value.ToString())
* Convert.ToDecimal(dataGridView1[1, b].Value.ToString());
}
}
But my main observation on DatagridviewtextBoxColumn it’s notcasting it Why?.
2.DatagridviewtextboxColumn:-
DataGridViewTextBoxColumn cts = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Insert(0, cts);
DataGridViewTextBoxColumn rt = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Insert(1, rt);
DataGridViewTextBoxColumn amt = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Insert(2, amt);
It’s Throw Error Like “NullReference Exception was Unhandle”, “Object reference not set an instance on an Object “ with Following Code:
private void dataGridView1_CellEndEdit(object sender,DataGridViewCellEventArgs e)
{
int b = dataGridView1.CurrentCell.RowIndex;
if (
dataGridView1[0, b].Value != DBNull.Value &&
dataGridView1[1, b].Value != DBNull.Value
)
{
dataGridView1[2, b].Value = Convert.ToDecimal(dataGridView1[0, b].Value.ToString())
* Convert.ToDecimal(dataGridView1[1, b].Value.ToString());
}
}
I just wants to know the reason behind it. And Solve the Casting Problem with DatagridviewtextBoxColumn
I have used only 'null' to check datagridView cells, not DBNull. Have you tried with that?
Edit: after reading a bit I found this (VB.NET) which says that
If the grid is bound to a DataTable then "empty" cells will contain DBNull.Value. If the grid is bound to something else or not bound at all then "empty" cells will contain Nothing
so you should probably check for null.
精彩评论