0

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

“索引超出范围”

有关的代码如下

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;
                }
            }
        }
}

请找到解决方案....

4

1 回答 1

4

问题是您使用字符串的长度作为 的上限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
            }
        }
    }
}
于 2013-07-18T07:19:09.010 回答