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 に答える