Reputation: 82
How to fix problem follow :
when I drawItem, then get message error: "Unable to cast object of type 'System.Collections.Generic.List`1[mypro.InfoDialog+Mycontact]' to type 'Mycontact'."
C# code at line number:
public class Mycontact
{
public string P_DISPLAY_NAME { get; set; }
public string P_AVAILABILITY { get; set; }
public string P_AVATAR_IMAGE { get; set; }
}
Mycontact fbContact;
private void AddDataToList()
{
var fbList = new List<Mycontact>();
foreach (dynamic item in result.data)
{
fbContact = new Mycontact() { P_DISPLAY_NAME = (string)item["name"], P_AVAILABILITY = (string)item["online_presence"]};
fbList.Add(fbContact);
listBox1.Items.Add(fbList);
}
}
private int mouseIndex = -1;
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index == -1) return;
line number:
Mycontact contact = (Mycontact)listBox1.Items[e.Index];
Brush textBrush = SystemBrushes.WindowText;
if (e.Index > -1)
{
// Drawing the frame
if (e.Index == mouseIndex)
{
e.Graphics.FillRectangle(SystemBrushes.HotTrack, e.Bounds);
textBrush = SystemBrushes.HighlightText;
}
else
{
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
textBrush = SystemBrushes.HighlightText;
}else{
e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);
}
// Drawing the text
e.Graphics.DrawString(contact.P_DISPLAY_NAME, e.Font, textBrush, e.Bounds.Left + 20, e.Bounds.Top);
}
}
}
Upvotes: 0
Views: 355
Reputation: 683
You are adding the full list to the listbox as a single item:
listBox1.Items.Add(fbList);
So the line
(Mycontact)listBox1.Items[e.Index];
Returns a list of MyContact objects instead of a single MyContact object.
So to fix it you could just add contact per contact to the list like this
listBox1.Items.Add(fbContact);
Upvotes: 1
Reputation: 12544
It seems the whole listed is added to listbox1 instead of a single item (listBox1.Items.Add(fbList))
Shouldn't it be:
listBox1.Items.Add(fbContact);
Alternatively, you could set listBox1.DataSource = fbList after the loop
Upvotes: 4