- 1). Define a "Dictionary" object in your C# code and assign a "key" and a "value" to each row of the dictionary. The "key" and "value" can come from a database or be hard-coded. The values are hard-coded in the example below:
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("key 1", "value 1");
list.Add("key 2", "value 2");
list.Add("key 3", "value 3");
list.Add("key 4", "value 4"); - 2). Define the "Drop-down List" object and set the "Dictionary" object named "list" as the datasource. Name the drop-down "ddl." Set the "DataTextField" of "ddl" to the "key" from "list" and the "DataValueField" to the "value" from "list."
ddl.DataSource = list;
ddl.DataTextField = "Key";
ddl.DataValueField = "Value";
ddl.DataBind(); - 3). Search the "Dictionary" object using "ContainsKey" method. For example, you may want to search through the "Dictionary" to locate a specific value prior to adding it to the "drop-down list." "ContainsKey" is one of the fastest search methods of the "Dictionary" object.
if (list.ContainsKey("key 2")) - 4). Search the "drop-down list" object using the "FindByValue" method. This search method is case-sensitive and searches for the entire search parameter in its entirety.
if (ddl.Items.FindByValue("value 3") != null)
{
ddl.SelectedValue = "value 3";
}
If you entered "value" as the search parameter, null would have been returned, because there are no values in "ddl" that are equal to ONLY the word "value."
SHARE