Introduction
In this article we will learn how bind multiple dropdown list from a single method using c# or by using single binding method bind multiple dropdowns or use a shortest way to bind multiple dropdowns.
Previous Updates
In previous articles we have learnt Showing Chart With Database In Asp.Net Using C#. Insert Only Numeric Values In Asp TextBox Using Regex . Get TextBox , Dropdown, CheckBox control Values In Aspx.cs Page From User Control Using C#. Maintain state of dynamic added userConrol in asp.net using c#. Load the Usercontrol In Aspx Page.
Explanation
In this example i will use a single BindDropdown function which calls every time when any dropdown needs to bind and make the binding easier. This scenario only a way to know you about how we can reuse the code in some situations. If you have many dropdowns in your web form then this example is best suit to you and don't use this if you are working with one or two dropdown lists only. Cause in that way it will not reduce your time and code quality.
private void BindDropDown(DropDownList drpObject, object dataSource,
string value, string text, string customSelectText = "-- Select --")
{
drpObject.DataSource = dataSource;
drpObject.DataTextField = text;
drpObject.DataValueField = value;
drpObject.DataBind();
var li = new ListItem { Text = customSelectText, Value = "0" };
drpObject.Items.Insert(0, li);
}
|
In the above given code that is the common DropDown binding method.
private void BindCountry()
{
SqlConnection con =
new SqlConnection("Data Source=MyPC;Initial Catalog=TsetDB;Integrated Security=True");
SqlCommand cmd =
new SqlCommand("SELECT CountryId, CountryName FROM Country", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet dsCountry = new DataSet();
adp.Fill(dsCountry);
if (dsCountry.Tables[0].Rows.Count > 0 && dsCountry.Tables[0].Rows != null)
{
BindDropDown(ddlState, dsCountry.Tables[0], "CountryId", "CountryName");
}
}
private void BindState()
{
SqlConnection con =
new SqlConnection("Data Source=MyPC;Initial Catalog=TsetDB;Integrated Security=True");
SqlCommand cmd =
new SqlCommand("SELECT StateId, StateName FROM State", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet dsState = new DataSet();
adp.Fill(dsState);
if(dsState.Tables[0].Rows.Count > 0 && dsState.Tables[0].Rows !=null)
{
BindDropDown(ddlState, dsState.Tables[0], "StateId", "StateName");
}
}
|
Now Call these method where you need to use. Here i call both methods in PageLoad.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindState();
BindCountry();
}
}
|
0 comments:
Post a Comment