2013-07-18 28 views
0

我已將複選框的選中值插入到表中,方法是將它們拆分爲不同的列,與我想要檢索的相同從表中的值來簽入複選框它是通過錯誤獲取錯誤「INDEX WAS OUT OF BOUNDS」,同時檢索複選框以檢查從sql選擇的值到c#

「索引出界」

的代碼就低於

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

請找到一個解決辦法....

+3

快速注 - 它更慣用的寫:'用於(INT I = 0; I <大小;我++)'比'的for(int i = 0; I <=大小 - 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 
      } 
     } 
    } 
} 
+0

如果我可能會建議,而不是'foreach(var receient)','recipients.Contains(item)'可以提供幫助。你怎麼看? – shahkalpesh

+0

hiii @Jon Skeet thx因爲我仍然收到錯誤,如 「無法投射'System.Int32'類型的對象來鍵入System.String'。」 – Haritha

+0

@shahkalpesh:如果不區分大小寫,這是行不通的,這是一個更大的變化。 –