1

I am developing a windows forms application and load the list from this code:

private void showList()
    {
        TeamTableAdapter teamAdapter = new TeamTableAdapter();
        lstTeamName.DataSource = teamAdapter.GetTeamsActive();
        lstTeamName.DisplayMember = "TeamName";
        lstTeamName.ValueMember = "TeamID";

    }

I want to enable a button if the user selects one of the items. What event should I put the code into. I the following code but the event seems to fire before the user clicks on the list.

 private void lstTeamName_Click(object sender, EventArgs e)
    {
        if (lstTeamName.SelectedIndex > -1)
            btnImportXML.Enabled = true;

    }

I moved my code to the SelectedIndexChange event but it still fires before the user selects an item and the selectedIndex is 0.

Paul
  • 757
  • 3
  • 10
  • 38
  • 3
    Maybe `SelectedValueChanged` or `SelectedIndexChanged`? There are lots of events to choose from: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox_events.aspx – David Nov 18 '13 at 19:56

2 Answers2

2

You dont want to bind to the Click event but to the SelectedIndexChanged event. You should be able to accomplish this by simply double clicking on the Control in designer.

Wjdavis5
  • 3,952
  • 7
  • 35
  • 63
  • I moved my code to the SelectedIndexChange event but it still fires before the user selects an item and the selectedIndex is 0. – Paul Nov 18 '13 at 23:47
  • Did you wire up the event handler? – Wjdavis5 Nov 19 '13 at 01:35
  • What version of Vs are you using? – Wjdavis5 Nov 19 '13 at 01:37
  • http://stackoverflow.com/questions/1135299/microsoft-visual-studio-and-c-how-to-visually-add-events-to-controls – Wjdavis5 Nov 19 '13 at 01:38
  • I know how to wire up an event handler and I don't think the version of VS is relevant. – Paul Nov 19 '13 at 18:16
  • Ok if you say so - But you obviously haven't wired up the correct event handler else the event wouldnt fire until the Index changes – Wjdavis5 Nov 20 '13 at 18:39
  • If you re-read my question that is what I am asking. Not how to wire up an event handler. – Paul Nov 20 '13 at 22:21
  • I dont need to re-read it - I and a couple of other people have told you that the event you need to wire up is the SelectedIndexChanged event or even the SelectedItemChanged event. The link I posted above provides a pictorial walkthrough on accomplishing this. If you are still struggling then the help you need is beyond this forum. – Wjdavis5 Nov 21 '13 at 02:53
1

I would agree that you don't want to bind to Click as that will likely fire too early.

I recommend you look into the DropDownStyle property. http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle(v=vs.110).aspx. If you set that to DropDownList then the SelectedItemChanged will fire and SelectedIndex could be > -1

If you leave it as the default DropDown then you may want to use TextChanged and check the Text property.

jaquesri
  • 188
  • 2