C# 函数包含FindControl
以下是场景:C# 函数包含FindControl,c#,asp.net,C#,Asp.net,以下是场景: 选中Radiobuttonlist的索引=0时,将显示复选框列表 复选框列表有X个项目。用户可以选择Y个项目(Y
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;
}
}
protectedvoid cblalchol\u SelectedIndexChanged(对象发送方,事件参数e)
{
//我调用ID为Checkboxlist/Radiobuttonlist的函数
布拉布拉(“RBLALCOOL”、“CBLALCOOL”);
}
私有无效BlaBla(字符串rblID、字符串cblID)
{
无线电按钮列表;
检查列表cbl;
foreach(此.Page.Controls中的控件ctrl)
{
rbl=(RadioButtonList)FindControl(rblID);
cbl=(复选框列表)FindControl(cblID);
}
int计数器=0;
对于(int i=0;i<**cbl**.Items.Count;i++)
{
if(cbl.Items[i].选中)计数器++;
}
if(计数器==cbl.Items.Count)
{
cbl.SelectedIndex=-1;
cbl.Visible=false;
**rbl**.SelectedIndex=1;
}
}
错误1使用未分配的局部变量“cbl”(标记为粗体)
错误2使用未分配的局部变量“rbl”(标记为粗体)
对
不
也许没有
我不知道问题出在哪里
提前感谢。由于编译器不知道在
foreach(在这个.Page.Controls中控制ctrl)
(例如,可能没有任何控件),它要求您为cbl
和rbl
提供默认值:
RadioButtonList rbl = null;
CheckBoxList cbl = null;
确保在循环后检查null
,以避免NullReferenceException
s
而且,
foreach
似乎在任何方面都没有用处。只需删除它。问题在于编译器不知道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();
删除中的foreach行:
foreach (Control ctrl in this.Page.Controls)
{
rbl = (RadioButtonList)FindControl(rblID);
cbl = (CheckBoxList)FindControl(cblID);
}
您执行的代码与此.Page
中的控件的执行次数完全相同
除非复选框列表
和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)
{
...
}
我永远不会给他们分配
新的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(RadioButtonList rbl, CheckBoxList cbl)
{
...
}