Selecting an item in a listbox control
-
Hi, I'm trying to select an item in a listbox control by right clicking on it, can you please tell me what's wrong with what I'm doing??
private void listbox1_MouseClick(object sender, MouseEventArgs e) { listbox1.SelectedItem = listbox1.GetChildAtPoint(listbox1.PointToClient(e.Location)); }
Thank you guys!
Smile: A curve that can set a lot of things straight! (\ /) (O.o) (><)
-
Hi, I'm trying to select an item in a listbox control by right clicking on it, can you please tell me what's wrong with what I'm doing??
private void listbox1_MouseClick(object sender, MouseEventArgs e) { listbox1.SelectedItem = listbox1.GetChildAtPoint(listbox1.PointToClient(e.Location)); }
Thank you guys!
Smile: A curve that can set a lot of things straight! (\ /) (O.o) (><)
Hi I suggest to use MouseDown or MouseUp events instead of Click because they give you the mouse button and position all together and you can find the index of pointed item by using
IndexFromPoint
method of listBox instance here is the code I tested to see how it can be donevoid listBox1\_MouseDown(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Right) return; int index=this.listBox1.IndexFromPoint(e.Location); if (index == -1) return; object selectedObj = this.listBox1.Items\[index\]; // if you want to select that in the list this.listBox1.SelectedIndex = index; MessageBox.Show(selectedObj.ToString());//just for test }
good luck :)
-
Hi I suggest to use MouseDown or MouseUp events instead of Click because they give you the mouse button and position all together and you can find the index of pointed item by using
IndexFromPoint
method of listBox instance here is the code I tested to see how it can be donevoid listBox1\_MouseDown(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Right) return; int index=this.listBox1.IndexFromPoint(e.Location); if (index == -1) return; object selectedObj = this.listBox1.Items\[index\]; // if you want to select that in the list this.listBox1.SelectedIndex = index; MessageBox.Show(selectedObj.ToString());//just for test }
good luck :)