Reputation: 888
How can I bind multiple controls to the same data source?
I get data from a table via a stored procedure call and want all controls to bind to that data.
The dropdownlist binds successfully but the others do not. To get it to work I have to create a separate function for each control and call the stored procedure and bind.
private void BindServerControls()
{
string strErrorMessage = "";
SqlDataReader LanguagesDataReader = null;
try
{
dbFunc.OpenDB();
SqlCommand LanguagesCmd = new SqlCommand("dbo.SelectAllLanguages", dbFunc.objConn);
LanguagesCmd.Parameters.Clear();
LanguagesCmd.CommandType = CommandType.StoredProcedure;
LanguagesDataReader = LanguagesCmd.ExecuteReader();
if (LanguagesDataReader.HasRows == true)
{
// Bind a dropdownlist.
DropDownList1.DataSource = LanguagesDataReader;
DropDownList1.DataTextField = "ProgrammingLanguage";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "Choose...");
// Bind a list of Radio buttons.
RadioButtonList1.DataSource = LanguagesDataReader;
RadioButtonList1.DataTextField = "ProgrammingLanguage";
RadioButtonList1.DataValueField = "ID";
RadioButtonList1.DataBind();
// Bind a ListBox.
ListBox1.DataSource = LanguagesDataReader;
ListBox1.DataTextField = "ProgrammingLanguage";
ListBox1.DataValueField = "ID";
ListBox1.DataBind();
// Bind a CheckBoxList.
CheckBoxList1.DataSource = LanguagesDataReader;
CheckBoxList1.DataTextField = "ProgrammingLanguage";
CheckBoxList1.DataValueField = "ID";
CheckBoxList1.DataBind();
// Bind a BulletList.
BulletedList1.DataSource = LanguagesDataReader;
BulletedList1.DataTextField = "ProgrammingLanguage";
BulletedList1.DataValueField = "ID";
BulletedList1.DataBind();
}
else
{
Status.Text = "There are currently no entries in the
database.";
}
}
catch (Exception ex)
{
Status.Text = "Unable to get the entries from the database.";
}
finally
{
if (LanguagesDataReader != null)
{
LanguagesDataReader.Close();
}
dbFunc.CloseDB();
}
}
Upvotes: 0
Views: 406
Reputation: 4236
Instead of binding a dataReader object load data in DataTable and then use it for binding
DataTable dtLanguages = new DataTable();
using(SqlDataReader LanguagesDataReader = LanguagesCmd.ExecuteReader()) {
dtLanguages.Load(LanguagesDataReader);
}
if(dtLanguages.Rows.Count > 0) {
// Bind a dropdownlist.
DropDownList1.DataSource = dtLanguages;
DropDownList1.DataTextField = "ProgrammingLanguage";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "Choose...");
}
The reason is that DataReader is sequential, forward-only connected datasource and once you finished traversing data through it you can not go back to start and read again.
Upvotes: 1