简体   繁体   中英

how to insert selected asp.net c# checkbox value to the sql database

i have four check box.but i can not insert selected check box value my SQL table.

my code:-

protected void btnADDSAVE_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=SONU-PC\\SQLEXPRESS; Initial Catalog=Prashant-Online_Store-DB; Integrated Security=true");
        SqlCommand cmd = new SqlCommand();

        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "sp_addnewproduct";

        cmd.Parameters.Add("@name", SqlDbType.VarChar,50).Value = checkbox.Text.Trim();
        cmd.Parameters.Add("@code", SqlDbType.NVarChar, 100).Value = checkbox1.Text.Trim();
        cmd.Parameters.Add("@name", SqlDbType.VarChar,50).Value = checkbox3.Text.Trim();
        cmd.Parameters.Add("@code", SqlDbType.NVarChar, 100).Value = checkbox4.Text.Trim();
        cmd.Connection = con;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            Response.Write("Add new product..");

        }
        catch
        {
            Response.Write("Not add new product.?");
        }
        finally
        {
            con.Close();
            con.Dispose();
        }

    }

As SpiderCode has pointed out, you are trying to get the checkbox text value without checking if the checkbox is checked or not.

use conditional operator to insert the value if checked else insert empty string;

cmd.Parameters.Add("@name", SqlDbType.VarChar,50).Value = checkbox.IsChecked ? checkbox.Text.Trim() : string.Empty;

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