Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

c# - How do add image to System.Windows.Forms.ListBox?

I'm developing chatting program using C# and I manage nickname list using ListBox. But, client have nickname, and state (online, away)

So, in order to manage the state, I want to add image (online - green circle, away - red circle) to ListBox (it is my idea)

How can add image to ListBox? Please help me.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't do that easily in the ListBox. And drawing them using Graphics is not easy at all. I suggest using a DataGridView o ListView control instead.

Result:

enter image description here

DataGridView: There's a ColumnType called DataGridViewImageColumn that you can use to show your status icon.

public void FillDataGridView()
{
    //images
    var greenImg = Resources.green;
    var redImg = Resources.red;
    var yellowImg = Resources.yellow;

    dataGridView1.Rows.Add(new object[] {"Vland", greenImg});
    dataGridView1.Rows.Add(new object[] {"John", yellowImg });
    dataGridView1.Rows.Add(new object[] {"Paul", greenImg});
    dataGridView1.Rows.Add(new object[] {"George", redImg});
    dataGridView1.Rows.Add(new object[] {"Ringo", redImg });
}

How to: Display Images in Cells of the Windows Forms DataGridView Control

ListView: can add items composed by text + image. If you use the ListView, you need to add an imageList component to your form (with your images in it) and call their imageKey value like shown in the example

public void fillListView()
{
    listView1.SmallImageList = imageList1;

    listView1.Items.Add("BombPenguin", "green");
    listView1.Items.Add("Vland", "yellow");
    listView1.Items.Add("John", "red");
    listView1.Items.Add("Paul", "green");
    listView1.Items.Add("Ringo", "red");
}

How to: Display Icons for the Windows Forms ListView Control


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...