Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to bind DropDownList from DataBase in asp.net

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 156
    Comment on it

    Hello all,

    In asp.net we use DropDownList control which has multiple select items(options) from which we can select one. We can either set the values of DropDownList list items by hard coding it or we can also bind the the select items and select value from the DataBase.

    To bind the Value from the DataBase we have the following block of code:

    In ASPX we have:

    <asp:DropDownList ID="myDropDownList" runat="server">
                   <asp:ListItem Selected="True">--Select--</asp:ListItem>
    </asp:DropDownList>
    

    And in C# we have :

     protected void binddept()
        {
            DataTable dataTable = new DataTable();        
            dataTable = // Your DataAccess code goes here which will return a DataTable;
            if (dataTable .Rows.Count > 0)
            {
                myDropDownList.DataSource = dataTable ;
                myDropDownList.DataTextField = "countryName"; // This will be the column name present in DataTable and it will set the Text Field of the DropDownList control
                myDropDownList.DataValueField = "countryId";  // This will be the column name present in DataTable and it will set the Value Field of the DropDownList control
                myDropDownList.DataBind();
                myDropDownList.Items.Insert(0, "--Select--");
            }
    
        }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: