简体   繁体   English

如何将选定的asp.net c#复选框值插入sql数据库

[英]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. 我有四个checkbox。但是我无法在SQL表中插入选定的复选框值。

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. 正如SpiderCode指出的那样,您试图获取复选框文本值而不检查是否选中了该复选框。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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