Home > Mobile >  Error when inserting records into database in windows forms app
Error when inserting records into database in windows forms app

Time:11-29

When debugging, an error happens on this line of code:

int StartKmReading = Convert.ToInt32(txtDTStartKmReading);

This is the errpr

System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.TextBox' to type 'System.IConvertible'

Data types and names of the database are correct as well.

Please help me with this. Thanks

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

The data should be successfully stored in the database without errors.

CodePudding user response:

This issue is in this line code

int StartKmReading = Convert.ToInt32(txtDTStartKmReading);

It should be:

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