TOC

The community is working on translating this tutorial into Chinese, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

The basics:

More events

Okay, the onclick event from last chapter was easy, but let's try creating all the code required to use an event from scratch. We will also add yet a new control, to make things more interesting - the DropDownList, which allows the user to select an item from a list. Add the folowing code snippet somewhere in the Default.aspx file:

<asp:DropDownList runat="server" id="GreetList" autopostback="true">
    <asp:ListItem value="no one">No one</asp:ListItem>
    <asp:ListItem value="world">World</asp:ListItem>
    <asp:ListItem value="universe">Universe</asp:ListItem>
</asp:DropDownList>

This thing works just like a normal HTML SELECT element, which is of course what it's translated into upon rendering. The only attribute that would seem new to a person with basic HTML experience, is the autopostback. You will learn more about postbacks in one of the next chapters, but for now, just know that it makes the control contact the server eachtime an item is selected by the user. We will use this to our benefit now, by adding an event:

<asp:DropDownList runat="server" id="GreetList" autopostback="true" onselectedindexchanged="GreetList_SelectedIndexChanged">

We are using the onselectedindexchanged event, and assigning a method from CodeBehind which does not yet exist. You are free to choose the name of the method, but using a convention with the name of the control, an underscore, and then the name of the event, helps you keep track of it all. We better go create the event, so change to the Default.aspx.cs file, and add the following method:

protected void GreetList_SelectedIndexChanged(object sender, EventArgs e)
{
    HelloWorldLabel.Text = "Hello, " + GreetList.SelectedValue;
}

Once again, we make this extremely simple. We use the SelectedValue property of our dropdown list, which holds the text from the value property of the selected item. Try running the site, and select an item from the dropdown list. Pretty neat, huh? All commen controls come with a bunch of usefull events, which you can subscribe to like this.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!