Repeater 实现 OnSelectedIndexChanged

时间:2023-12-09 20:34:13

在Repeater中使用DropDownList的方法

在Repeater中使用DropDownList的方法

以下代码并不完整,只记录了关键的方法

aspx代码中

假设这是一个用户管理的系统的模型,有一个下拉菜单来操作用户状态

<asp:Repeater ID="RepeaterArticleList" runat="server" onitemdatabound="RepeaterArticleList_ItemDataBound"> 
   <ItemTemplate
           <asp:HiddenField ID="HiddenField1" Value=<%#Eval("ID") %> runat="server" /> 
   
    <asp:DropDownList ID="droplist1" runat="server" OnSelectedIndexChanged="DropDownList1_Change" AutoPostBack="true" > 
                  <asp:ListItem Text="启用" Value="1"></asp:ListItem
                  <asp:ListItem Text="禁用" Value="2"></asp:ListItem
                  <asp:ListItem Text="删除" Value="3"></asp:ListItem
         </asp:DropDownList>  
   </ItemTemplate
</asp:Repeater

cs代码中对应的DropDownList1_Change方法,取到用户ID,执行操作

Repeater 实现 OnSelectedIndexChanged
protected void DropDownList1_Change(object sender, EventArgs e)  
{
DropDownList drd = sender as DropDownList;
Repeater rps = drd.Parent.Parent as Repeater;
int n = ((RepeaterItem)drd.Parent).ItemIndex;
HiddenField hid = (HiddenField)(rps.Items[n].FindControl("HiddenField1"));
string userid= hid.Value;
string userState = Convert.ToInt32(drd.SelectedValue); //已经拿到了id,可以进行操作 YourFunction(userid,userState);
}
Repeater 实现 OnSelectedIndexChanged

在前台显示的时候,再根据用户的状态值,来选择下拉菜单的默认选中值首先为RepeaterRepeater 控件添加事件 onitemdatabound="RepeaterArticleList_ItemDataBound" 接下来是完成代码

protected void RepeaterArticleList_ItemDataBound(object sender, RepeaterItemEventArgs e) 
    {         
        DropDownList drd = (DropDownList)e.Item.FindControl("droplist1"); 
        HiddenField hid = (HiddenField)(e.Item.FindControl("HiddenField1")); 
        //用你的方法通过ID得到状态值到userstate   
        string userstate = getUserStateByID(hid.Value); 
        drd.SelectedValue = userstate ; 
   
    

转自https://www.cnblogs.com/zdkjob/articles/2256917.html