Setting dropdownlist selecteditem programmatically

前端 未结 11 1726
北海茫月
北海茫月 2020-11-28 07:47

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

11条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 08:28

    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.

提交回复
热议问题