以下是该方案:
这确实很简单。但我有10个Checkboxlist / Radiobuttonlist夫妇。所以我创建了以下代码:
protected void cblAlcohol_SelectedIndexChanged(object sender, EventArgs e)
{
//I call the function with ID of Checkboxlist/Radiobuttonlist couple
BlaBla("rblAlcohol","cblAlcohol");
}
private void BlaBla(string rblID, string cblID)
{
RadioButtonList rbl;
CheckBoxList cbl;
foreach (Control ctrl in this.Page.Controls)
{
rbl = (RadioButtonList)FindControl(rblID);
cbl = (CheckBoxList)FindControl(cblID);
}
int counter = 0;
for (int i = 0; i < **cbl**.Items.Count; i++)
{
if (cbl.Items[i].Selected) counter++;
}
if (counter == cbl.Items.Count)
{
cbl.SelectedIndex = -1;
cbl.Visible = false;
**rbl**.SelectedIndex = 1;
}
}
错误1使用未分配的本地变量&#39; cbl&#39; (标记为粗体)
错误2使用未分配的本地变量&#39; rbl&#39; (标记为粗体)
<asp:RadioButtonList ID="rblAlcohol" runat="server" AutoPostBack="true" RepeatDirection="Horizontal" OnSelectedIndexChanged="rblAlcohol_SelectedIndexChanged">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem Selected="True">No</asp:ListItem>
</asp:RadioButtonList>
<asp:CheckBoxList ID="cblAlcohol" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="cblAlcohol_SelectedIndexChanged"> <asp:ListItem>Maybe</asp:ListItem> <asp:ListItem>No</asp:ListItem></asp:CheckBoxList>
我无法解决问题所在。
提前感谢。
答案 0 :(得分:0)
由于编译器不知道在foreach (Control ctrl in this.Page.Controls)
中是否会有要迭代的项目(例如,可能没有任何控件),它要求您为其提供默认值cbl
和rbl
:
RadioButtonList rbl = null;
CheckBoxList cbl = null;
确保在循环后检查null
以避免NullReferenceException
s。
此外,foreach
似乎没有任何用处。只需将其删除即可。
答案 1 :(得分:0)
问题是编译器没有知道将rbl和cbl分配到这里,即。它在逻辑上可能不会成为:
foreach (Control ctrl in this.Page.Controls)
{
rbl = (RadioButtonList)FindControl(rblID);
cbl = (CheckBoxList)FindControl(cblID);
}
只需将声明它们的行更改为:
RadioButtonList rbl = new RadioButtonList();
CheckBoxList cbl = new CheckBoxList();
答案 2 :(得分:0)
删除foreach
行:
foreach (Control ctrl in this.Page.Controls)
{
rbl = (RadioButtonList)FindControl(rblID);
cbl = (CheckBoxList)FindControl(cblID);
}
您执行的代码与this.Page
中的控件完全相同。
除非checkoxlist
和radiobuttonlist
是动态的,否则您已将其引用作为页面类成员。无需使用FindControl
搜索它们,只需将引用传递给BlaBla
:
protected void cblAlcohol_SelectedIndexChanged(object sender, EventArgs e)
{
//I call the function with ID of Checkboxlist/Radiobuttonlist couple
BlaBla(rblAlcohol, cblAlcohol);
}
private void BlaBla(RadioButtonList rbl, CheckBoxList cbl)
{
...
}