2014-01-24 215 views
-3

幫助,Im得到「InvalidArgument ='-1'的值對'index'無效 參數名稱:index」。我不知道我搞錯了哪一部分。希望你們能幫助我。先謝謝了。InvalidArgument ='-1'的值對'index'無效。參數名稱:索引

private void bankerCard_DrawItem(object sender, DrawItemEventArgs e) 
    { 
     e.DrawBackground(); 
     Brush myBrush = Brushes.Black; 

     if (bankerCard.Items[e.Index].ToString().Contains("♥")) 
      myBrush = Brushes.Red; 
     else if (bankerCard.Items[e.Index].ToString().Contains("♦")) 
      myBrush = Brushes.Red; 
     else 
      myBrush = Brushes.Black; 

     e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), 
      e.Font, myBrush, e.Bounds, StringFormat.GenericDefault); 

     e.DrawFocusRectangle(); 
    } 

上面的代碼測試沒問題。問題發生在下面。任何線索?

private void playerCard_DrawItem(object sender, DrawItemEventArgs e) 
    { 
     e.DrawBackground(); 
     Brush myBrush = Brushes.Black; 

     switch (e.Index) 
     { 
      case 0: 
       myBrush = Brushes.Red; 
       break; 
      case 1: 
       myBrush = Brushes.Orange; 
       break; 
      case 2: 
       myBrush = Brushes.Purple; 
       break; 
     } 

     e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), 
      e.Font, myBrush, e.Bounds, StringFormat.GenericDefault); `error over here` 

     e.DrawFocusRectangle(); 
    } 

回答

0

的錯誤是不言自明的,這裏大概e.Index-1和您試圖訪問(ListBox)sender).Items[-1]

((ListBox)sender).Items[e.Index].ToString() 

爲了解決這個問題,你可以添加一個if語句來檢查索引是否大於 - 1:

if(e.Index >= 0) 
{ 
    e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), 
     e.Font, myBrush, e.Bounds, StringFormat.GenericDefault) 
} 
+0

已解決。非常感謝。 – user3230387

+0

@ user3230387,如果這回答了您的問題,您應該將其標記爲如此。 – davidsbro

相關問題