Friday, July 4, 2008

Binding DropDown List from Web.Config

Add the keys in the Web.Config under App Settings as given below.






Call up the Method BindColors() from Page Load by passing the DropDown Object

using System.Configuration; // This name space to be added in the page.
// If this is not available, Add Reference to the System.Configuration dll// from the .Net Tab by right clicking on the website and adding.
BindColors(DrpColor);

private void BindColors(DropDownList oDrp)
{
String ColorTexts = ConfigurationManager.AppSettings["ColorText"];
String ColorValues = ConfigurationManager.AppSettings["ColorValue"];

string[] ColorText = ColorTexts.Split(';');
string[] ColorValue = ColorValues.Split(';');

ListItemCollection oCollection = new ListItemCollection();

for (int i = 0; i < ColorText.Length; i++)
{
ListItem oItem = new ListItem();
oItem.Value = ColorValue[i].ToString();
oItem.Text = ColorText[i];
oCollection.Add(oItem);
}

oDrp.DataTextField = "Text";
oDrp.DataValueField = "Value";
oDrp.DataSource = oCollection;
oDrp.DataBind();
}
Dropdown’s Text and Values are bound.

No comments: