How to programmatically create and use a list of checkboxes from ASP.NET?

前端 未结 7 1243
礼貌的吻别
礼貌的吻别 2021-01-19 10:37

I have a page with a table of stuff and I need to allow the user to select rows to process. I\'ve figured out how to add a column of check boxes to the table but I can\'t se

7条回答
  •  借酒劲吻你
    2021-01-19 10:47

    Your post is a little vague. It would help to see how you're adding controls to the table. Is it an ASP:Table or a regular HTML table (presumably with a runat="server" attribute since you've successfully added items to it)?

    If you intend to let the user make a bunch of selections, then hit a "Submit" button, whereupon you'll process each row based on which row is checked, then you should not be handling the CheckChanged event. Otherwise, as you've noticed, you'll be causing a postback each time and it won't process any of the other checkboxes. So when you create the CheckBox do not set the eventhandler so it doesn't cause a postback.

    In your submit button's eventhandler you would loop through each table row, cell, then determine whether the cell's children control contained a checkbox.

    I would suggest not using a table. From what you're describing perhaps a GridView or DataList is a better option.


    EDIT: here's a simple example to demonstrate. You should be able to get this working in a new project to test out.

    Markup

        

    Code-behind

    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 10; i++)
        {
            var row = new HtmlTableRow();
            var cell = new HtmlTableCell();
            cell.InnerText = "Row: " + i.ToString();
            row.Cells.Add(cell);
            cell = new HtmlTableCell();
            CheckBox chk = new CheckBox() { ID = "chk" + i.ToString() };
            cell.Controls.Add(chk);
            row.Cells.Add(cell);
            tbl.Rows.Add(row);
        }
    }
    
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        foreach (HtmlTableRow row in tbl.Rows)
        {
            foreach (HtmlTableCell cell in row.Cells)
            {
                foreach (Control c in cell.Controls)
                {
                    if (c is CheckBox)
                    {
                        // do your processing here
                        CheckBox chk = c as CheckBox;
                        if (chk.Checked)
                        {
                            Response.Write(chk.ID + " was checked 
    "); } } } } } }

提交回复
热议问题