本文介绍了如何处理无效的强制转换操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有bankname combobox,accountno文本框和Accounttype combobox。如果我从组合框中选择bankname。它在datagridview中显示数据库表中的相关数据。如果选择 从bankcombobox选择文本。它没有在datagridview中显示任何数据。我想在我点击addbutton时添加datagridview的新行顶部。新行正在成功添加。在datagridview中我有像slno,startno,noofcheques和endingno以及status.after进入的文本框startno和noofcheques都将添加填充数据结束没有文本我正在使用单元格离开事件。当我加载表单第一次添加新行和值计算正常。当我第一次选择bankname然后选择选择文本单击addnew行按钮行正在添加,但是当我尝试在startno文本框中输入值时。它会抛出错误。在mscorlib.dll.Object中发生的'System.InvalidCastException'无法从DBNull强制转换为其他类型。 我很新鲜,请帮助我。 我尝试了什么:I have bankname combobox,accountno textbox and Accounttype combobox.If i select bankname from the combobox.It shows the related data in datagridview from database table.If select"Select " text from the bankcombobox.It doesn't show any data in datagridview.I want to add new row top of the datagridview when i click addbutton.new row is adding succesfully.In datagridview i have textboxes like slno,startno,noofcheques and endingno and status.after entering startno and noofcheques both will add populate data in ending no text for that i am using cell leave event.when i load the form firsttime new row is adding and values are calculating fine.when i first select bankname and then select "select" text click addnew row button row is adding but when i try to enter values into the startno textbox.It throws error.'System.InvalidCastException' occurred in mscorlib.dll.Object cannot be cast from DBNull to other types.I'm fresher please help me on this.What I have tried: private void dgvwChqs_CellLeave(object sender, DataGridViewCellEventArgs e) { if (dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value != null) { dgvwChqs.Rows[e.RowIndex].Cells["endingno"].Value = Convert.ToInt32(dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value) + Convert.ToInt32(dgvwChqs.Rows[e.RowIndex].Cells["noofcheques"].Value); } }private void btnadd_Click(object sender, EventArgs e) { dts.Rows.InsertAt(dts.NewRow(), 0); }推荐答案//first methodint startno = 0;int noofcheques = 0;if(!Convert.IsDbNull(dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value)) startno = dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value; //assuming that startno field stores integer valuesif(!Convert.IsDbNull(dgvwChqs.Rows[e.RowIndex].Cells["noofcheques"].Value)) noofcheques = dgvwChqs.Rows[e.RowIndex].Cells["noofcheques"].Value;//second methodint startno = Convert.IsDbNull(dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value)==true ? dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value : 0;int noofcheques = Convert.IsDbNull(dgvwChqs.Rows[e.RowIndex].Cells["noofcheques"].Value)==true ? dgvwChqs.Rows[e.RowIndex].Cells["noofcheques"].Value : 0;//finally:dgvwChqs.Rows[e.RowIndex].Cells["endingno"].Value = startno + noofcheques; 另一种方法是使用可空数据类型。有关详细信息,请参阅:使用可空类型(C#编程指南)| Microsoft Docs [ ^ ] 这篇关于如何处理无效的强制转换操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-09 09:02