我正在Windows窗体上的程序上工作我有一个列表框,并且正在验证数据,我希望将正确的数据添加到绿色的列表框中,而将无效数据添加到红色,并且我还希望从列表框中自动向下滚动添加了一个项目,谢谢
代码 :
try
{
validatedata;
listBox1.Items.Add("Successfully validated the data : "+validateddata);
}
catch()
{
listBox1.Items.Add("Failed to validate data: " +validateddata);
}
最佳答案
假设使用WinForms,这就是我要做的:
首先创建一个类以包含要添加到列表框中的项目。
public class MyListBoxItem {
public MyListBoxItem(Color c, string m) {
ItemColor = c;
Message = m;
}
public Color ItemColor { get; set; }
public string Message { get; set; }
}
使用以下代码将项目添加到您的列表框中:
listBox1.Items.Add(new MyListBoxItem(Colors.Green, "Validated data successfully"));
listBox1.Items.Add(new MyListBoxItem(Colors.Red, "Failed to validate data"));
在ListBox的属性中,将DrawMode设置为OwnerDrawFixed,然后为DrawItem事件创建一个事件处理程序。这使您可以根据需要绘制每个项目。
在DrawItem事件中:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
if (item != null)
{
e.Graphics.DrawString( // Draw the appropriate text in the ListBox
item.Message, // The message linked to the item
listBox1.Font, // Take the font from the listbox
new SolidBrush(item.ItemColor), // Set the color
0, // X pixel coordinate
e.Index * listBox1.ItemHeight // Y pixel coordinate. Multiply the index by the ItemHeight defined in the listbox.
);
}
else
{
// The item isn't a MyListBoxItem, do something about it
}
}
有一些限制-主要的限制是您需要编写自己的单击处理程序并重新绘制适当的项目以使它们显示为选中状态,因为Windows不会在OwnerDraw模式下执行此操作。但是,如果这仅是为了记录应用程序中发生的事情,则您可能不关心显示为可选项目。
要滚动到最后一个项目,请尝试
listBox1.TopIndex = listBox1.Items.Count - 1;