0

如何解决问题如下:

当我drawItem,然后得到消息错误:“无法将'System.Collections.Generic.List`1[mypro.InfoDialog+Mycontact]'类型的对象转换为'Mycontact'。”

行号处的 C# 代码:

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);
            }
        }
}
4

2 回答 2

4

似乎整个列表被添加到 listbox1 而不是单个项目 (listBox1.Items.Add(fbList))

不应该是:

listBox1.Items.Add(fbContact);

或者,您可以在循环后设置 listBox1.DataSource = fbList

于 2012-06-07T08:14:10.133 回答
1

您正在将完整列表作为单个项目添加到列表框中:

listBox1.Items.Add(fbList);

所以这条线

(Mycontact)listBox1.Items[e.Index];

返回 MyContact 对象的列表,而不是单个 MyContact 对象。

因此,要修复它,您可以像这样将每个联系人的联系人添加到列表中

listBox1.Items.Add(fbContact);

于 2012-06-07T08:15:47.533 回答