winforms 在Windows窗体应用程序中将记录插入数据库时出错

mqxuamgl  于 2022-11-30  发布在  Windows
关注(0)|答案(1)|浏览(127)

两柴时,下列程式码行会发生错误:

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();
    }
}

数据应成功存储在数据库中,且无错误。

rpppsulh

rpppsulh1#

问题在此行代码中

int StartKmReading = Convert.ToInt32(txtDTStartKmReading);

它应该是:

int StartKmReading = Convert.ToInt32(txtDTStartKmReading.Text);

但是要小心。如果用户在文本框中输入了一个无效值,你的代码将抛出一个异常。你应该使用int.TryParse方法来增强你的代码

相关问题