C# 開発

【C#】ListBox

2025.01.19 ListBox にアイコン付きのアイテムを追加する

private void button1_Click(object sender, EventArgs e)
{
   listBox1.DrawMode = DrawMode.OwnerDrawFixed;
   listBox1.ItemHeight = 40;

   string[] s1 = { "NEC", "SONY", "DELL" };

   foreach (string item in s1)
   {
      listBox1.Items.Add(item);
   }
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
  if (e.Index == -1) return;

  string vsICO = "C:\\Program Files\\Internet Explorer\\images\\bing.ico";
  e.Graphics.DrawImage(Image.FromFile(vsICO), e.Bounds.X, e.Bounds.Y);

  e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),
                        new Font(listBox1.Font.Name, listBox1.Font.Size),
                        new SolidBrush(Color.Black),
                        e.Bounds.X + Image.FromFile(vsICO).Width,
                        e.Bounds.Y);
}

-C# 開発