动态创建checkboxlist并插入数据库

时间:2013-11-14 11:46:09

标签: c# asp.net

我创建了LabelsCheckBoxes ...... 但我想在检查后将CheckBox值保存为0或1,以便'on'或'off'进入sql server。 我该怎么办?

   protected void EventDuration_DDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        con.Open();
        DateTime dt = DateTime.Parse(StartDate_TB.Text);

        int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
        for (int i = 0; i < n; i++)
        {

            Label NewLabel = new Label();
            NewLabel.ID = "Label" + i;
            var eventDate = dt.AddDays(i);
            NewLabel.Text = eventDate.ToLongDateString();

            CheckBox newcheck = new CheckBox();
            newcheck.ID = "CheckBox" + i;
            newcheck.AutoPostBack = true;
            newcheck.CausesValidation = false;
            newcheck.CheckedChanged += new EventHandler(newcheck_CheckedChanged);
            this.Labeldiv.Controls.Add(new LiteralControl("<span class='h1size'>"));
            this.Labeldiv.Controls.Add(NewLabel);
            this.Labeldiv.Controls.Add(new LiteralControl("</span>"));
            this.Labeldiv.Controls.Add(new LiteralControl("<div class='make-switch pull-right' data-on='info'>"));
            this.Labeldiv.Controls.Add(newcheck);
            this.Labeldiv.Controls.Add(new LiteralControl("</div>"));
            this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
        }

        con.Close();
    }

    void newcheck_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox currentCheckbox = sender as CheckBox;
        string extractInteger = Regex.Match(currentCheckbox.ID, @"\d+").Value;
        Label currentlabel = (Label)Labeldiv.FindControl("Label" + extractInteger);
        con.Open();

        int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
        for (int i = 0; i < n; i++)
        {
            SqlCommand cmd = new SqlCommand("insert into EventDays(EventDay,EventStatus)values(@EventDay,@EventStatus)", con);
            cmd.Parameters.AddWithValue("@EventDay", currentlabel.Text);
            cmd.Parameters.AddWithValue("@EventStatus", currentCheckbox.Checked ? "true" : "false");
            cmd.ExecuteNonQuery();

        }
        con.Close();
    }

复选框必须根据ddl选择创建....如果我们选择6则必须创建6个复选框,之后当我们选中复选框时,值必须存储到sql-server ....

这些值没有存储到sql server ......

1 个答案:

答案 0 :(得分:0)

假设EventStatus是一个数字列,我能想到的最懒的解决方案是

cmd2.Parameters.AddWithValue("@EventStatus", newcheck.Checked ? 1 : 0);