【问题标题】:Error when inserting records into database in windows forms app在 Windows 窗体应用程序中将记录插入数据库时​​出错
【发布时间】:2022-11-27 09:06:26
【问题描述】:

调试时,出现“int StartKmReading = Convert.ToInt32(txtDTStartKmReading);” 然后它显示如下 errpr

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

`

数据应该成功地存储在数据库中而没有错误。

【问题讨论】:

  • Convert.ToInt32(txtDTStartKmReading); - 您需要像所有其他文本框一样从txtDTStartKmReading 获取Text 属性。这段代码也开放了SQL注入

标签: c# sql winforms


【解决方案1】:

这个问题在这一行代码中

int StartKmReading = Convert.ToInt32(txtDTStartKmReading);

它应该是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多