hi,

I'm trying to get daya into a new table via form. two fields in new table will pick up data based on look up tables.
pls guide as to how do i proceed . The code is flashing conversion of Data type error.
To avoid the datatype error, i 've already taken category_id and city_id fields in DB as varchar.


Thanks

protected void btnWinesAvailable_Click(object sender, EventArgs e)
    {   
        conn.Open();
        SqlCommand cmd1 = new SqlCommand("Insert into wines_available(name, address, city_id, category_id) values (@name, @address, @cityid, @categoryid)", conn);
        
       string a =("select city_id from city_master where city_name= '" + ddlCityname.SelectedItem + "'");
       string b= ("select category_id from category_master where category = '"+ ddlCategoryname.SelectedItem+ "'");
        
        cmd1.Parameters.Add(new SqlParameter("@name", txtOrgName.Text));
        cmd1.Parameters.Add(new SqlParameter("@address", txtAddress.Text));
        cmd1.Parameters.Add(new SqlParameter("@cityid", SqlDbType.Char,10)).Value = a;
        cmd1.Parameters.Add(new SqlParameter("@categoryid", SqlDbType.Char, 10)).Value = b;
        
      
        cmd1.ExecuteNonQuery();
        txtOrgName.Text = "";
        txtAddress.Text = "";
        //txtCityID1.Text = "";
        //txtCategoryID1.Text = "";
        conn.Close();
        conn.Dispose();
    }

Dani AI

Generated

Short summary and a few practical fixes.

The conversion error happened because the code was passing SQL text or the wrong parameter types into the INSERT rather than the actual ID values. Turning the ID columns into varchar “fixed” the symptom, but it hides the real problems: incorrect parameter usage, string concatenation (SQL injection risk), and unnecessary round trips to the database.

What to do next (practical, safe options)

  • Bind the dropdowns so the ID is the value (set the control’s DataValueField to the ID column and DataTextField to the name). Then use SelectedValue to pass the ID directly. This removes the need to run lookup SELECTs before the insert.
  • If you must lookup by name, do it inside the database in one call: either a stored procedure (as suggested) or an INSERT that resolves the IDs with subqueries/JOINs in the same statement (this avoids multiple DB calls).
  • For single-value lookups use ExecuteScalar rather than a SqlDataReader, and always close the reader before issuing other commands on the same connection (or enable MARS intentionally).

Coding and schema best practices

  • Keep ID columns numeric (INT) and define foreign keys. Reverting IDs to varchar is a brittle workaround. Use SqlDbType.Int for numeric parameters; use SqlDbType.VarChar/length only for text.
  • Use parameterized commands, never concatenate user text into SQL. Prefer using blocks for SqlConnection/SqlCommand and wrap DB work in try/catch so connections always close.
  • Don’t add the same parameter multiple times inside a loop; ensure the lookup returned a value before adding the parameter. If a lookup can return no rows, handle that (null check or default).

Notes on the thread

  • ’s stored-proc route and ’s T-SQL-variable approach are both valid. ’s move to a DataReader fixed the immediate type mismatch — the next step is to simplify by binding SelectedValue or moving the lookup into a single DB call.

Recommended Answers

All 4 Replies

If what you're trying to do is put the results of the SELECT statements in a and b into the parameters, then it's not going to work like you think it will. Your best bet is to use a stored procedure. That way you'll be able to use variables in the stored proc to hold the results of the two select statements. Then you just plug them into your insert statement in the same stored procedure.
Otherwise, you'll have to make two DB calls from the code before the insert to retrieve the values and then use those values for your insert.

Not necessarily. You could do this:

Declare @CityId int, @CategoryId int
Set @CityId = (select city_id from city_master where city_name= 'abc')
Set @CategoryId = (select city_id from city_master where city_name='123')

Insert into wines_available(name, address, city_id, category_id) values (@name, @address, @cityid, @categoryid)

Thanks for the reply. I was getting error in the i/p parameters data type.

The use of DR and change in parameter worked.

I'll also try with stores precedure n variables as suggested

protected void btnWinesAvailable_Click(object sender, EventArgs e)
    {
        conn.Open();

        SqlCommand cmd1 = new SqlCommand("Insert into wines_available(name, address, city_id, category_id) values (@name, @address, @cityid, @categoryid)", conn);

        SqlCommand a = new SqlCommand("select city_id from city_master where city_name= '" + ddlCityname.SelectedItem + "'", conn);
        SqlCommand b = new SqlCommand("select category_id from category_master where category = '" + ddlCategoryname.SelectedItem + "'", conn);


        cmd1.Parameters.Add(new SqlParameter("@name", txtOrgName.Text));
        cmd1.Parameters.Add(new SqlParameter("@address", txtAddress.Text));

        SqlDataReader dr1;
        dr1 = a.ExecuteReader();
        while (dr1.Read())
        {
            cmd1.Parameters.Add(new SqlParameter("@cityid", SqlDbType.Char, dr1["city_id"].ToString().Trim().Length)).Value = dr1["city_id"].ToString().Trim();
        }
        dr1.Close();

        SqlDataReader dr2;
        dr2 = b.ExecuteReader();
        while (dr2.Read())
        {
            cmd1.Parameters.Add(new SqlParameter("@categoryid", SqlDbType.Char, dr2["category_id"].ToString().Trim().Length)).Value = dr2["category_id"].ToString().Trim();
        }

        dr2.Close();
        
        txtOrgName.Text = "";
        txtAddress.Text = "";
        //txtCityID1.Text = "";
        //txtCategoryID1.Text = "";

        cmd1.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

If what you're trying to do is put the results of the SELECT statements in a and b into the parameters, then it's not going to work like you think it will. Your best bet is to use a stored procedure. That way you'll be able to use variables in the stored proc to hold the results of the two select statements. Then you just plug them into your insert statement in the same stored procedure.
Otherwise, you'll have to make two DB calls from the code before the insert to retrieve the values and then use those values for your insert.

I'm glad you got it working

Please mark this thread as solved if you have found an answer to your question and good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.