Saturday, 30 November 2013

Bind Value into Dropdown List from Database

1. Open Visual Studio
2. Create a New Website
3. Add web page
4. from WEbsite - >Add New Item -> WebPage- > Click Add.
5. From ToolBox -> Add DropdownList to WebPage.
6. Create StoredProcedure of Select Query.


7. Add namespaces to page

using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;


8. Write Connection String

  static string str = WebConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    SqlConnection con = new SqlConnection(str);

9. Write Code on Page Load Event

 if (!Page.IsPostBack)
        {
            SqlCommand cmd = new SqlCommand("Select_Employee", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            DataSet ds = new DataSet();
            da.SelectCommand = cmd;
            da.Fill(ds);


            if (ds.Tables[0].Rows.Count > 0)
            {
                DropDownList1.DataSource = ds;
                
                DropDownList1.DataTextField = "EmpName";
                DropDownList1.DataValueField = "EmpID";
                DropDownList1.DataBind();
            }
        }

10. Click F5.

No comments:

Post a Comment

Thanks

SQL server tricky questions