面板控件[i] - 索引超出范围

时间:2013-06-19 09:25:51

标签: asp.net sql-server exception indexing controls

构想

我在网页上有一个面板个人资料列表。它包含多个小面板,就像包含行的项目列表一样。这里的项目是个人资料。每个配置文件实际上都是一个小面板 SingleProfile ,里面有复选框。 Checkbox 是此处的核心,因为它有一个 ID ,用于查找相同的项目。

在这个页面上还有另一个类似的大面板。我应该只在第二个面板中添加第一个不存在的项目。因此,任务是在第二个面板中仅显示那些未在第一个面板中显示的配置文件。使用两个列表中复选框的 ID 检查。

要检查第一个面板中是否已存在第二个面板中新添加的配置文件,我尝试通过 Controls [] 属性访问第一个面板中每个项目的ID属性。我在循环中这样做:

if (ProfilesPanel1.Controls.Count > 0)
{
    for (int i = 0; i <= ProfilesPanel1List.Controls.Count - 1; i++)
    {
        //label1.Text += " "+Convert.ToString(sqlReader["chain_id"]); //Bug #2 - see Stored Procedure description
        cbx1 = new CheckBox();
        cbx1 = (CheckBox)ProfilesPanel1List.Controls[i].Controls[1]; //Bug #1 - here the Exception occurs
        if (cbx1.ID == Convert.ToString(sqlReader["chain_id"])) //if profile already exists in the first panel
        {
            //Do not add this profile to the second panel
        }
    }
}

BUG#1

异常“System.ArgumentOutOfRangeException”出现在标有“Bug#1”的行中。

BUG#2

如您所见,我使用sqlReader从存储过程中获取ID。存储过程在Sql Server中正常工作。但是,当我将sqlReader的值输出到网页上的标签中时(参见代码中的注释),每个值都加倍,如“1 1 2 2 3 3 4 4 5 5”。

现在,在消除Bug#1后,一切正常

已解决

谢谢,伙计们,有用的更正和准备帮助

2 个答案:

答案 0 :(得分:1)

解决BUG#1

在调试模式下从快速监视器检查控件及其名称的数量,并查看ProfilesPanel1List.Controls[i]面板或其他控件。在调试模式下检查后,请正确选择索引。 而且您也不需要使用cbx1 = new CheckBox();代码行。它的下一行代码足以初始化Checkbox。

你的 sqlReader 代码不足以得到第二个错误的实际原因。

答案 1 :(得分:1)

对于 Bug#1 ,“Controls [i]”下可能没有嵌套控件。因此,为了防止该错误,您可以首先检查当前元素下是否有嵌套控件,然后在类型转换之前检查控件的类型。

    if(ProfilesPanel1List.Controls[i].Controls.Count>1 && ProfilesPanel1List.Controls[i].Controls[1] is CheckBox) //Iff you are double sure about layout structure and assured that it is not going to 
//change. If changes are anticipated then again doing a foreach(..) over nested 'Controls' and type 
//checking is much better.
    {
     //Do the type conversion etc., as per your requirement.  
    }

对于 Bug#2 ,你认为“每个值加倍”是什么意思?我可以看到你在循环中附加了相同的Label(ID:Label1),因此有可能在每次迭代时连接文本。另外,请确保根据您的要求,是否需要在父面板的嵌套控件内操作相同标签的文本或标签。