Friday, 14 September 2012

Beginning .Net : Raise server side event on selection of item in the DropDownList or ComboBox with C# Examples and VB.Net Examples

There is a situation where you want to select an item from drop down list or combo box and raise server side event to do some processing at server side. You can raise or fire server side event on selection of item from drop down list or combo box. It will raise "onselectedindexchanged" event.
For that you need to set AutoPostBack="true" property.

Here is example for this.
In this example we take on product drop down list and select an item from that after item selected dropdonwlist's "onselectedindexchanged" event raised.

ASPX Code :
   <b>Product List :</b>  <asp:DropDownList runat="server" ID="ddlProductList" AutoPostBack="true"
                            onselectedindexchanged="ddlProductList_SelectedIndexChanged"></asp:DropDownList>

C# Examples :
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            ddlProductList.Items.Add(new ListItem("[select]", "-1"));
            ddlProductList.Items.Add(new ListItem("CPU", "1"));
            ddlProductList.Items.Add(new ListItem("LCD", "2"));
            ddlProductList.Items.Add(new ListItem("LED", "3"));
        }
    }

    protected void ddlProductList_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Write("Selected Value : " + ddlProductList.SelectedValue);
        Response.Write("</br>Selected Text : " + ddlProductList.SelectedItem.Text);
        Response.Write("</br></br></br>");
    }

VB.net Example :
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Page.IsPostBack = False Then
            ddlProductList.Items.Add(New ListItem("[select]", "-1"))
            ddlProductList.Items.Add(New ListItem("CPU", "1"))
            ddlProductList.Items.Add(New ListItem("LCD", "2"))
            ddlProductList.Items.Add(New ListItem("LED", "3"))
        End If
    End Sub

    Protected Sub ddlProductList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Response.Write("Selected Value : " & ddlProductList.SelectedValue)
        Response.Write("</br>Selected Text : " & ddlProductList.SelectedItem.Text)
        Response.Write("</br></br></br>")
    End Sub

Output :


For Beginning .Net articles. Click Here...

This type of .Net Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



No comments:

Post a Comment