views:

273

answers:

1

Hi,

I've created a custom ListBox like in here. Thing is it doesn't raise any of the item specific events like DrawItem and SelectedIndexChanged.

Any idea why? Thanks.

+1  A: 

It worked just fine when I tried this code:

  public partial class Form1 : Form {
    MyListBox mList;
    public Form1() {
      InitializeComponent();
    }

    protected override void OnLoad(EventArgs e) {
      mList = new MyListBox(this);
      mList.Location = new Point(5, 10);
      mList.Size = new Size(50, this.ClientSize.Height + 50);
      for (int ix = 0; ix < 100; ++ix) mList.Items.Add(ix);
      mList.SelectedIndexChanged += new EventHandler(mList_SelectedIndexChanged);
    }

    void mList_SelectedIndexChanged(object sender, EventArgs e) {
      MessageBox.Show(mList.SelectedIndex.ToString());
    }

    protected override void Dispose(bool disposing) {
      // Moved from Designer.cs file
      if (disposing) mList.Dispose();
      if (disposing && (components != null)) {
        components.Dispose();
      }
      base.Dispose(disposing);
    }

  }
Hans Passant
Could it be because I've deleted the line that sets the CreateParams Style (otherwise I can't see the listbox at all)? What is it needed for?
Meidan Alon
The Style member is crucial to make the class work as intended. As noted in the original post, you cannot use it in the designer. You must create it at runtime. I gave sample code how to do this in this post.
Hans Passant