简体   繁体   中英

C#,Input string was not in a correct format.

What is wrong with my code? there is an error "Input string was not in a correct format." , i cant seem to get that p

protected void bearer_TextChanged(object sender, EventArgs e)
{
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["main"].ConnectionString);
    connection.Open();

    string insertquery = @"insert into verlog(bearerid,txndate,sendep,recdep,status) 
                                values(@bearer,@txndate,@depsend,@deprec,@status)";
    SqlCommand query = new SqlCommand(insertquery, connection);
    string query2 = "select @@Identity";

    query.Parameters.AddWithValue("@bearer", bearer.Text);
    query.Parameters.AddWithValue("@depsend", drpSender.Text);
    query.Parameters.AddWithValue("@deprec", drpRec.Text);
    query.Parameters.AddWithValue("@status", "Pending");
    query.Parameters.AddWithValue("@txndate", Label1.Text);
    query.ExecuteNonQuery();
    query.CommandText = query2;

    object sample = query.ExecuteScalar();
    //Label2.Text = txnid.ToString();
    connection.Close();
   // Label2.Text = myCounter.ToString();
   // bearer.Text = bearer.Text.Trim();
}

Is the txtDate field in the DB a DateTime field? If so, you are trying to pass a String to this field instead of a DateTime object.

 query.Parameters.AddWithValue("@txndate", Label1.Text);

You should convert the contents of the Label1 textbox to a DateTime object and then try and insert it.

DateTime dt = Convert.ToDateTime(Label1.Text);  

Here is a link to the MSDN page on how to convert a String to a DateTime. This page shows how you can specify the expected input format of the string you are trying to parse using the CultureInfo object.

How to: Convert a String to a DateTime

You should also check the other DB field types as well to ensure they are all String types - if not, you may need to convert some of the other fields before trying to save data to DB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM