获取错误“;索引越界”;同时检索用于检查从sql到c#中选择的值的复选框

本文关键字:sql 选择 复选框 检查 用于 索引 取错误 越界 检索 获取 | 更新日期: 2023-09-27 18:23:47

我已经通过将复选框的检查值拆分到不同的列,将它们插入到表中,就像我想从要检查到复选框的表中检索值一样,这是通过错误

"索引越界"

有关的代码低于

foreach (DataRow Recpt in ds.Tables[5].Rows)
{
        for (var i = 0; i <= chkPrdRecipients.Items.Count-1; i++)
        {
            var Recipients = Recpt["RecipientId"].ToString();
            Array arrRecipients = Recipients.Split(',');
            for (var j = 0; j <= Recipients.Length - 1; j++)
            {
                if (arrRecipients.GetValue(j).ToString().Trim().ToLower() ==
                    chkPrdRecipients.Items[i].Value.Trim().ToLower())
                {
                    chkPrdRecipients.Items[i].Selected = true;
                }
            }
        }
}

请找到解决方案。。。。

获取错误“;索引越界”;同时检索用于检查从sql到c#中选择的值的复选框

问题是您使用字符串的长度作为j的上界,而不是数组的长度。您将使用来消除此即时错误

for (int j = 0; j < arrRecipient.Length; j++)

然而,代码仍然非常难看——为什么要使用Array而不是string[]?这样代码会简单得多。我也会重命名变量以遵循正常的约定。例如:

foreach (DataRow recipientRow in ds.Tables[5].Rows)
{
    // We don't need to fetch this multiple times, or trim them each time.
    string[] recipients = ((string) recipientRow["RecipientId"])
        .Split(',')
        .Select(x => x.Trim())
        .ToArray();
    // It's possible that you could use a foreach loop here, but
    // we don't know the type of chkPrdRecipients...
    for (int i = 0; i < chkPrdRecipients.Items.Count; i++)
    {
        var item = chkPrdRecipients.Items[i];
        foreach (var recipient in recipients)
        {
            if (recipient.Equals(item.Value.Trim(), 
                                 StringComparison.InvariantCultureIgnoreCase))
            {
                item.Selected = true;
                break; // No need to check the rest of the recipients
            }
        }
    }
}