I want to set the selecteditem
attribute for an ASP.Net dropdownlist control programmatically.
So I want to pass a value to the dropdownlist control to
ddlemployee.DataSource = ds.Tables[0];
ddlemployee.DataTextField = "Employee Name";
ddlemployee.DataValueField = "RecId";
ddlemployee.DataBind();
ddlemployee.Items.Insert(0, "All");
Assuming the list is already data bound you can simply set the SelectedValue
property on your dropdown list.
list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";
list.DataBind();
list.SelectedValue = myValue.ToString();
The value of the myValue
variable would need to exist in the property specified within the DataValueField
in your controls databinding.
UPDATE:
If the value of myValue
doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.
On load of My Windows Form the comboBox
will display the ClassName
column of my DataTable
as it's the DisplayMember
also has its ValueMember
(not visible to user) with it.
private void Form1_Load(object sender, EventArgs e)
{
this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
}
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
Safety check to only select if an item is matched.
//try to find item in list.
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;