13 January, 2009

Bind DropdownList with Data From SQL



Try these Examples to Bind DropdownList with Data from SQL Server with Two ways

First Example :

Step1 : Create new ASPX page and Drag DropdownList Control
Step2
: In Code behind of your Page create new method to Bind your Dropdownlist control and then in Page_Loag call your method

this is my method to Bind Dropdownlist control



public void Bind()
{
// Open the Connection
SQLConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["Bag_ConnStr"].ConnectionString);
Con.Open();
// SQL Statement
string strSQL = null;
strSQL = "SELECT State_Name, State_Code FROM TableState ORDER BY State_Name";
// Command, Data Reader
SQLCommand Com = new SQLCommand(strSQL, Con);
SQLDataReader rdr = Com.ExecuteReader();
// Populate the Control
while (rdr.Read()) {
ListItem newListItem = new ListItem();
newListItem.Text = rdr.GetString(0);
newListItem.Value = rdr.GetString(1);
DropDownList1.Items.Add(newListItem);
}
}

protected void Page_Load(object sender, EventArgs e)
{
if(! IsPostBack)
{
Bind();
}
}

and in web.config file

<connectionStrings>
<remove name="Bag_ConnStr"/>
<add name="Bag_ConnStr" connectionString="Data Source=.;Initial Catalog=DataBase;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

Second Example:

Step1
: Create new ASPX page and Drag DropdownList Control
Step2 : In Code behind of your Page create new method to Bind your Dropdownlist control and then in Page_Loag call your method

this is my method to Bind Dropdownlist control



public void Bind()
{
SqlDataReader ddDR = null;
SqlConnection ddSqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Bag_ConnStr"].ConnectionString);
SqlCommand ddSqlCommand = new SqlCommand("SELECT Id,Name FROM Education_Level ", ddSqlConnection);
ddSqlCommand.CommandType = CommandType.Text;
ddSqlConnection.Open();
ddDR = ddSqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
ddl_Education_Level.DataSource = ddDR;
ddl_Education_Level.DataTextField = "Name";
ddl_Education_Level.DataValueField = "Id";
ddl_Education_Level.DataBind();
}

protected void Page_Load(object sender, EventArgs e)
{
if(! IsPostBack)
{
Bind();
}
}

and in web.config file

<connectionStrings>
<remove name="Bag_ConnStr"/>
<add name="Bag_ConnStr" connectionString="Data Source=.;Initial Catalog=DataBase;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

Note : Don't forget to Import System.Data.SqlClient

No comments:

Post a Comment

Suggestions are invited from readers