Thursday, May 2, 2013

How to bind Dropdownlist with database in Asp.net?


Introduction: In this post I will explain how we can bind the Dropdownlist control with database in Asp.net.
Description:
Open the Visual Studio>Go to File>New>Website. Add the Connectionstring in web.config file of website.
<configuration>
       <connectionStrings>
    <add name="connection" connectionString="Data Source=SYS-1F78031ED0A;Initial Catalog=TestBlog;Integrated Security=True"/>
       </connectionStrings>
       <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>

After that add new web form to website. Take a Dropdownlist from Toolbox>>Standard.
<asp:DropDownList ID="ddlstate" runat="server">
        </asp:DropDownList>

I have created a table name TB_STATE.
ID
int
STATE
varchar(50)

Here ID is primary key.
Now go to the aspx.cs page, firstly add namespace and create a function to fill dropdown.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString.ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
        {
Filldropdown();
  }
       
}
  private void Filldropdown()
    {
        try
        {
            SqlCommand cmd = new SqlCommand("select * from TB_STATE", con);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            ddlstate.DataSource = dt;
            ddlstate.DataValueField = "ID";
            ddlstate.DataTextField = "STATE";
            ddlstate.DataBind();
            ddlstate.Items.Insert(0,new ListItem("--Select--","0"));
        }
        catch (Exception ex)
        {
            Response.Write("Error Occured"+ex.Message);
        }

    }
Now debug the application and check the result.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

No comments:

Post a Comment