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 に答える