0

I am using this code to put a image in listbox but the text does not show . When I click on the list then it shows . What is the problem ?

form_load()
{
   listbox1.Items.Add("string");
   listbox1.DrawMode = DrawMode.OwnerDrawVariable;
}

private void listbox1_DrawItem(object sender, DrawItemEventArgs e)
{
   ListBox lst = sender as ListBox;
   e.Graphics.DrawImage(imageList1.Images[0], 0, 0, 10, 10);
   e.Graphics.DrawString(lst.Text, this.Font,SystemBrushes.ControlDark, 11, 0);
}
4

1 回答 1

2

Well, it looks like you're drawing your items incorrectly. DrawItem event is being called for each item in the listbox, but you're drawing all the times the same text at the same position. You should use e.Bounds to determine position of each item. Also you can handle MeasureItem event to set custom bounds for each item if you need some non-standard dimensions.

Also lst.Text doesn't has much sense here, it should be text of current item to draw, based on e.Index.

Thus, part of your code drawing string could look something like:

e.Graphics.DrawString(lst.GetItemText(lst.Items[e.Index]), 
                      this.Font, SystemBrushes.ControlDark, e.Bounds.Left, e.Bounds.Top);

Also you may find useful some example at MSDN.

于 2015-12-03T11:37:32.687 回答