如何在DB中保存动态创建的复选框选定值

时间:2012-01-27 10:08:44

标签: c# asp.net sql sql-server

我有一个从两个数据库表(tblPrivileges,tblViews)动态创建的复选框矩阵,如图所示:

Array of checkboxes

垂直记录来自tblPrivileges,水平3记录来自tblViews。以下是上述矩阵的代码:

protected override void OnInit(EventArgs e)
    {
        int rowCnt;
        int rowCtr;

        rowCnt = 1;
        con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
        SqlDataAdapter adp1 = new SqlDataAdapter("select * from tblViews", con);
        DataSet ds1 = new DataSet();
        adp1.Fill(ds1);
        DataTable g = new DataTable();
        adp1.Fill(g);


        for (rowCtr = 1; rowCtr <= rowCnt; rowCtr++)
        {
            TableRow tRow = new TableRow();
            privilegeTable.Rows.Add(tRow);
            foreach (DataRow checkboxTitle in g.Rows)
            {
                TableCell tc = new TableCell();
                //System.Web.UI.WebControls.CheckBox cb = new System.Web.UI.WebControls.CheckBox();


                tc.Text = checkboxTitle.ItemArray[1].ToString();
                TableCell tCell = new TableCell();
                tRow.Cells.Add(tCell);
                tCell.Controls.Add(new LiteralControl(checkboxTitle.ItemArray[1].ToString()));

            }
        }
        CheckBoxList chklist = new CheckBoxList();
        //SqlDataAdapter adp = new SqlDataAdapter("select v.View_ID,v.View_Name,p.Privilege_ID,p.Privilege_Name from tblViews as v right outer join tblPrivileges p on v.View_ID = p.Privilege_ID", con);
        SqlDataAdapter adp = new SqlDataAdapter("select * from tblPrivileges", con);
        DataSet ds = new DataSet();
        adp.Fill(ds);

        DataTable dt = new DataTable();
        adp.Fill(dt);

        foreach (DataRow name in dt.Rows)
        {

            TableRow tr = new TableRow();
            TableCell tcTitle = new TableCell();

            tcTitle.Text = name.ItemArray[1].ToString();
            tr.Cells.Add(tcTitle);

            foreach (DataRow checkboxTitle in g.Rows)
            {
                TableCell tc = new TableCell();
                System.Web.UI.WebControls.CheckBox cb = new System.Web.UI.WebControls.CheckBox();

                tc.Text = checkboxTitle.ItemArray[1].ToString();

                tc.Controls.Add(cb);
                tr.Cells.Add(tc);


            }

            privilegeTable.Rows.Add(tr);
            base.OnInit(e);
        }

    }

我需要选中复选框值,单击一个按钮后,所选的复选框值应该转到公共表。此外,我无法设置复选框的属性“ID”。如何在数据库表中单击按钮时保存选定的复选框值?

请帮助!!!

1 个答案:

答案 0 :(得分:0)

您需要了解asp.net page lifecycle才能动态地向页面添加服务器控件。您要将控件添加到页面中太迟了。