ASP.NET: How to access repeater generated form input elements?

前端 未结 4 1582
青春惊慌失措
青春惊慌失措 2020-12-16 19:17

i\'m want to have a repeater generate a bunch of checkboxes, e.g.:

 <         


        
4条回答
  •  借酒劲吻你
    2020-12-16 20:09

    Use the server control instead of making an input control runat=server

     
    

    When you set the value in your ItemDataBound, you use FindControl

    CheckBox checkBox = (CheckBox)e.Item.FindControl("whatever");
    checkBox.Checked = true;
    

    When you get the items, you also use FindControl from the item in a foreach construct. Also, depending on how you databound it, the DataItem may no longer be there after a postback.

    foreach (RepeaterItem item in myRepeater.Items)
    {
        if (item.ItemType == ListItemType.Item 
            || item.ItemType == ListItemType.AlternatingItem) 
        { 
            CheckBox checkBox = (CheckBox)item.FindControl("whatever");
            if (checkBox.Checked)
            { /* do something */ }
        }
    }
    
    • Many people are tempted to 'safe cast' using the as operator with FindControl(). I don't like that because when you change the control name on the form, you can silently ignore a development error and make it harder to track down. I try to only use the as operator if the control isn't guaranteed to be there.

    Update for: Which CheckBox is which? In the rendered html you'll end up having all these checkbox name like

    ctl00_cph0_ParentContainer_MyRepeater_ctl01_MyCheckbox
    ctl00_cph0_ParentContainer_MyRepeater_ctl02_MyCheckbox
    ctl00_cph0_ParentContainer_MyRepeater_ctl03_MyCheckbox
    

    You don't care what the names are because the foreach item.FindControl() gets them for you, and you shouldn't assume anything about them. However, when you iterate via foreach, you usually need a way to reference that back to something. Most of the time this is done by also having an asp:HiddenField control alongside each CheckBox to hold an identifier to match it back up to the correct entity.

    Security note: there is a security issue with using hidden fields because a hidden field can be altered in javascript; always be conscious that this value could have been modified by the user before the form was submitted.

提交回复
热议问题