[英]How to resolve 'System.InvalidCastException' when calculating in DataGridView C#
我試圖在C#中的DataGridView中橫向添加行,垂直向下添加一列,但是每次嘗試輸入數據時都會收到此錯誤消息:
“ mscorlib.dll中發生了'System.InvalidCastException類型的未處理的異常。附加信息:無法將對象從DBNull強制轉換為其他類型”。
這些是我的代碼:
private void tbl_valuesDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//totalling horizontally across rows
int val1 = Convert.ToInt32(tbl_valuesDataGridView.Rows[e.RowIndex].Cells[1].Value);
int val2 = Convert.ToInt32(tbl_valuesDataGridView.Rows[e.RowIndex].Cells[2].Value);
tbl_valuesDataGridView.Rows[e.RowIndex].Cells[3].Value = val1 + val2;
//adding vertically down the total column to get Grand Total
double sum = 0;
for (int i = 0; i < tbl_valuesDataGridView.Rows.Count; ++i)
{
sum += Convert.ToDouble(tbl_valuesDataGridView.Rows[i].Cells[2].Value);
}
textBox1.Text = sum.ToString();
}
注意事項:
我是編程新手,所以我不知道該錯誤是由於我設置數據庫表的方式導致的,還是由C#代碼引起的。
有人可以幫幫我嗎?
對於水平附加代碼,將Cells [3] .Value設置為等於Cells [1] .Value + Cells [2] .Value。 很好,但是您似乎只執行了一行。
然后,在垂直相加中,您將所有行的Cells [2] .Value相加。
如果我正確理解代碼,則應該在此處總計Cells [3] .Value(因為這是存儲每一行總計的位置)。
無論如何,您都需要轉到引發異常的行,並在調試器的“監視”窗口中檢查每個變量。 這應該告訴您哪個對象處於錯誤狀態。
借助Anik的幫助和一些調試,我終於能夠找到問題的答案。 對於我們中剛接觸編程的人,如果打算使用DataGridView,那么您會發現此代碼非常有用。 始終確保為該代碼使用CellEndEdit事件處理程序。
private void tbl_valuesDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//totalling horizontally across rows
int val1 = 0, val2 = 0, demo1;
if (int.TryParse(tbl_valuesDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString().Trim(), out demo1))
val1 = Convert.ToInt32(tbl_valuesDataGridView.Rows[e.RowIndex].Cells[1].Value);
if (int.TryParse(tbl_valuesDataGridView.Rows[e.RowIndex].Cells[2].Value.ToString().Trim(), out demo1))
val2 = Convert.ToInt32(tbl_valuesDataGridView.Rows[e.RowIndex].Cells[2].Value);
tbl_valuesDataGridView.Rows[e.RowIndex].Cells[3].Value = val1 + val2;
//Adding vertically down the total column
double sum = 0;
for (int i = 0; i < tbl_valuesDataGridView.Rows.Count; ++i)
{
sum += Convert.ToDouble(tbl_valuesDataGridView.Rows[i].Cells[3].Value); //where 1 represents the index of the column you are adding
}
textBox1.Text = sum.ToString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.