C# adding click events to a list box

拈花ヽ惹草 提交于 2019-12-14 03:54:18

问题


I'm trying to add a click event to a list box but for some reason nothing happens when I click an item in my list box.

My guess and from what I've read, the code should look something like this

private void listBox1_Click(object sender, EventArgs e)
        {
            //Code Ex. TextBox1.Text = "Success";
    }

That's not working though. Anyone know how to get this to happen? Wouldn't mind knowing the double click and other click variations too....


回答1:


If you want it to trigger when you 'click an item' in the box, why don't you try SelectedIndexChanged instead?




回答2:


You coded the event handler but didn't add it to the click event... something like this:

listBox1.Click += new EventHandler( listBox1_Click );



回答3:


Webform? if so, did you check 'autopostback' = true?

Example with selectindexchanged:

<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
    <asp:ListItem>a</asp:ListItem>
    <asp:ListItem>b</asp:ListItem>
</asp:ListBox>

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{

}

That will make a postback as soon as the user clicks on one item. I'm not sure there is a doubleclick for that kind of stuff.




回答4:


Have you checked that the property "AutoPostBack" is enabled (="True")? :-) That happens often to me!




回答5:


I'm not sure the click events apply to the listbox items, probably just the parent box. I'd loop through the items and register the events. Or do it on databind.




回答6:


In Microsoft visual studio 2017 Get your main form ( with the list box ) into Form design view Select your list box item which you have dragged onto the main form Now your properties box for the list box has come live on the right hand side of the development window Now look at the top of the properties box for the menu item with the 'jag of lightning' on it Click on that...Voila your double click event is there

private void lbx _DoubleClick(object sender, EventArgs e)
{
    /*  Do good stuff here  */
}

Cheers me dears Jim



来源:https://stackoverflow.com/questions/15646214/c-sharp-adding-click-events-to-a-list-box

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!