一个函数包含FindControl

时间:2015-03-30 13:38:02

标签: c# asp.net

以下是该方案:

  1. 当Radiobuttonlist = 0
  2. 的selectedindex出现时,会出现Checkboxlist
  3. Checkboxlist有X个项目。用户可以选择Y项(Y< X)
  4. 如果Y = X(我的意思是如果用户检查所有项目),则使Checkboxlist消失,并使radinobuttonlist的selectedindex = 1
  5. 这确实很简单。但我有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>
    

    我无法解决问题所在。

    提前感谢。

3 个答案:

答案 0 :(得分:0)

由于编译器不知道在foreach (Control ctrl in this.Page.Controls)中是否会有要迭代的项目(例如,可能没有任何控件),它要求您为其提供默认值cblrbl

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中的控件完全相同。

除非checkoxlistradiobuttonlist是动态的,否则您已将其引用作为页面类成员。无需使用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)
{
  ...
}