获取ListItem的ItemTemplate内的值

时间:2012-08-02 14:14:58

标签: c# asp.net listview itemtemplate

我正在尝试从我ItemTemplate控件中的ListView1获取值。

<ItemTemplate>
    <asp:Label ID="Label1" runat="server" Text="test message" />
    <asp:RadioButtonList ID="RadioButtonList1" runat="server" 
        RepeatDirection="Horizontal">
            <asp:ListItem>1</asp:ListItem>
            <asp:ListItem>2</asp:ListItem>
            <asp:ListItem>3</asp:ListItem>
            <asp:ListItem>4</asp:ListItem>
        <asp:ListItem Value="5">
    </asp:ListItem>
    </asp:RadioButtonList>
</ItemTemplate>

protected void btnSubmit_Click(object sender, EventArgs e)
{   
    int score = 0;
        foreach (ListViewItem item in RadioButtonList1.Items)
        {
            ListViewDataItem theValue = RadioButtonList1.Items[0];
            RadioButtonList myValue = (RadioButtonList)theValue.FindControl("RadioButtonList1");

            score += int.Parse(myValue.SelectedItem.Value);
    }
    // display score
}

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

更改了代码,因为它在尝试循环RBL中的项目之前找到它:

  foreach (ListViewItem item in ListView.Items)
        {
            if (item.ItemType != ListViewItemType.DataItem)
                 continue;

            var rbl = (RadioButtonList)item.FindControl("RadioButtonList1");
            if (!string.IsNullOrEmpty(rbl.SelectedValue))
                 score += int.Parse(rbl.SelectedValue);
    }