0

I am inserting data in the textbox1 and dropdown1 but the data is only saved in the query which is written at the second position"i.e in this case c_name". C_name is either empty or inserts null values.

protected void Button1_Click(object sender, EventArgs e)
{
    con.Open();
    MySqlCommand cmd = con.CreateCommand();

    cmd.CommandType = CommandType.Text;

    cmd.CommandText = "insert into market (m_name) values ('" + TextBox1.Text + "')";
    cmd.CommandText = "insert into city (c_name) values('" + DropDownList1.SelectedValue + "')";

    if (DropDownList1.SelectedValue == "-1")
    {
        Response.Write("Please select a city");
    }


    cmd.ExecuteNonQuery();
    con.Close();
}
taimoor
  • 11
  • 4

1 Answers1

0

You should cmd.ExecuteNonQuery() after the first cmd.CommandText and then you have to do the same for your second cmd.CommandText, and both query will perform their actions.

protected void Button1_Click(object sender, EventArgs e)
{
   if (DropDownList1.SelectedValue == "-1")
   {
       Response.Write("Please select a city");
       return; // Must return don't execute after 'if' part or use 'else' there
   }

   con.Open();
   MySqlCommand cmd = con.CreateCommand();

   cmd.CommandType = CommandType.Text;

   cmd.CommandText = "insert into market (m_name) values ('" + TextBox1.Text + "')";

   cmd.ExecuteNonQuery(); // First insert executed here

   cmd.CommandText = "insert into city (c_name) values('" + DropDownList1.SelectedValue + "')";

   cmd.ExecuteNonQuery(); // Second insert executed here
   con.Close();
}
Hammad Sajid
  • 312
  • 1
  • 3
  • 14
Jawad Anwar
  • 485
  • 4
  • 15