Search code examples
c#mysql.netajaxwebgrid

{"Input string was not in a correct format."}


protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
    string CustomerID = ((Label)GridView1.Rows[e.RowIndex]
                        .FindControl("lblCustomerID")).Text;
    string Name = ((TextBox)GridView1.Rows[e.RowIndex]
                        .FindControl("txtContactName")).Text;
    string Company = ((TextBox)GridView1.Rows[e.RowIndex]
                        .FindControl("txtCompany")).Text;
    MySqlConnection con = new MySqlConnection();
    string Connection = "Server=localhost;" +
    "DATABASE=northwind2007;" + "username=;" +
    "PASSWORD=;";
    con.ConnectionString = Connection;
    MySqlCommand cmd = new MySqlCommand();
    cmd = new MySqlCommand(cmd.CommandText, con);
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "update Customers set FirstName=@ContactName," +
     "Company=@CompanyName where ID=@CustomerID;" + "select ID,FirstName,Company from Customers";
    cmd.Parameters.AddWithValue("@CustomerID", MySqlDbType.VarChar).Value = CustomerID;
    cmd.Parameters.AddWithValue("@ContactName", MySqlDbType.VarChar).Value = Name;
    cmd.Parameters.AddWithValue("@CompanyName", MySqlDbType.VarChar).Value = Company;
    GridView1.EditIndex = -1;
    MySqlDataAdapter da = new MySqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

i have tried everything but its now working out , everytime i try to update a record from my grid it throws this error.


Solution

  • Don't use AddWithValue but Add:

    cmd.Parameters.Add("@CustomerID", MySqlDbType.VarChar).Value = CustomerID;
    

    otherwise MySqlDbType.VarChar is treated as the value.

    You should also execute the update-command and you need to Open the connection:

    con.Open();
    int updatedRecords = cmd.ExecuteNonQuery();
    

    If you want to fill the table afterwards you could use the DataAdapter:

    using(var da = new MySqlDataAdapter("select ID,FirstName,Company from Customers", con))
        da.Fill(dt);
    

    Note that you should always use the using-statement to ensure that any unmanaged resource will be disposed and the connection gets closed (even on error). For example:

    using(var con = new MySqlConnection())
    using(var cmd =  new MySqlCommand("UPDATE ...", con))
    {
        con.Open();
        cmd.ExecuteNonQuery();
    }