帮助,我得到“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 :(得分:1)
错误是自解释的,可能此处e.Index
值为-1
,您尝试访问(ListBox)sender).Items[-1]
((ListBox)sender).Items[e.Index].ToString()
要解决此问题,您可以添加if语句来检查index是否大于-1:
if(e.Index >= 0)
{
e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault)
}