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

前端 未结 7 1301
礼貌的吻别
礼貌的吻别 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:57

    I'm going to assume you're using a DataList but this should work with and Control that can be templated. I'm also going to assume you're using DataBinding.

    Code Front:

    
        
            
            " target="_blank">
                <%# DataBinder.Eval(Container, "DataItem.Title")%>
        
    
    
    

    Code Behind:

    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                LoadList();
        }
    
        protected void DeleteListItem_Click(object sender, EventArgs e)
        {
            foreach (DataListItem li in List.Items)
            {
                CheckBox delMe = (CheckBox)li.FindControl("DeleteMe");
    
                if (delMe != null && delMe.Checked)
                        //Do Something
                }
            }
    
            LoadList();
        }
    
        protected void LoadList()
        {
            DataTable dt = //Something...
            List.DataSource = dt;
            List.DataBind();
        }
    
        protected void List_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                string id = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
                CheckBox delMe = (CheckBox)e.Item.FindControl("DeleteMe");
    
                if (delMe != null)
                    delMe.Attributes.Add("value", id);                
            }
        }
    }
    

提交回复
热议问题