Binding to an SqlDataReader: I normally use a static function to actually fill the list using the database 'Id' as the DataValueField and a field called 'Name' as the DataTextField. I pass the DropDownList and the Select statement and let the function do the work.
public static bool FillDropDownList(DropDownList dDl,string Select)
{
SqlConnection m_SqlConnection = new SqlConnection(CRbvDB.RbvWebDSN);
SqlCommand m_SqlCommand = new SqlCommand(Select,m_SqlConnection);
try
{
dDl.DataValueField = "Id";
dDl.DataTextField = "Name";
m_SqlConnection.Open();
SqlDataReader m_SqlDataReader = m_SqlCommand.ExecuteReader();
dDl.DataSource = m_SqlDataReader;
dDl.DataBind();
m_SqlDataReader.Close(); // Close DataReader
} // try
catch // (Exception e) // Exception Removed
{
return false;
//throw new Exception("Error in FillDropDownLit -> " + e.ToString());
} // catch
finally
{
m_SqlCommand.Dispose();
m_SqlConnection.Close(); // Close Connection
m_SqlConnection.Dispose();
}
return true;
}
In this example the DropDownList is filled with members of the database. Included in the list are Sales Manages [Id= SLS] only and is named ddlSlsId. Usr is a class that defines members and SLS is a field in the database. All database members have a SLS field. A Sales Manager's 'SLS' field is equal to the 'Id' field. Where they are not equal the field is a pointer to the database member's Sales Manager.
string selectCmd = "SELECT Id,LastName +', '+ FirstName AS Name ";
selectCmd += "FROM aRepresentative WHERE Id=SLS ORDER BY LastName ";
dDl.FillDropDownList(sslSlsId,selectCmd);
We can't use the standard SelectIndex property since we want to set the initial field value based on the value in the current database record so we use theFindByValue property top set the initial value.
atSlsId.Items.FindByValue( Usr.SLS.ToString()).Selected=true;
To get the value if a different Sales Manager has been assigned, we use the SelectedItem.Value property.
Usr.SLS = Convert.ToInt32(atSlsId.SelectedItem.Value);
Top 