两柴时,下列程式码行会发生错误:
int StartKmReading = Convert.ToInt32(txtDTStartKmReading);
这是错误
System.InvalidCastException:无法将类型为“System.Windows.Forms.TextBox”得对象强制转换为类型“System.IConvertible”
数据库的数据类型和名称也正确。
请帮我拿这个。谢谢
private void btnAddDT_Click(object sender, EventArgs e)
{
try
{
String InvoiceNo = txtDTInvoice.Text;
String VehicleNo = txtDTVehicleNo.Text;
String PackageType = txtDTPackageType.Text;
DateTime StartTime = dtpStartTimeDT.Value;
DateTime EndTime = dtpEndtimeDT.Value;
int StartKmReading = Convert.ToInt32(txtDTStartKmReading);
int EndKmReading = Convert.ToInt32(txtDTEndKmReading.Text);
double BaseHire = Convert.ToDouble(txtBaseHireChargeDT.Text);
double WaitingFee = Convert.ToDouble(txtWaitingFeeDT.Text);
double ExtraKmCharge = Convert.ToDouble(txtExtraKmChargeDT.Text);
double TotalAmount = Convert.ToDouble(txtDTTotalAmountCal.Text);
conn.Open();
String addQ = "insert into DayTourHires Values ('" + InvoiceNo + "', '" + VehicleNo + "', '" + PackageType + "', '" + StartTime+ "', '" + EndTime + "', '" + StartKmReading + "', '" + EndKmReading + "', '" + BaseHire + "', '" + WaitingFee + "', '" + ExtraKmCharge + "', '" + TotalAmount + "')";
SqlCommand comm = new SqlCommand(addQ, conn);
comm.ExecuteNonQuery();
MessageBox.Show("Record inserted");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
数据应成功存储在数据库中,且无错误。
1条答案
按热度按时间rpppsulh1#
问题在此行代码中
它应该是:
但是要小心。如果用户在文本框中输入了一个无效值,你的代码将抛出一个异常。你应该使用
int.TryParse
方法来增强你的代码