How to set DropDownList.SelectedValue for unit testing in ASP .NET web forms.

If you want to set the [SelectedValue] property of a DropDownList in a unit test, you must first add items to the [Items] property of the DropDownList. If you don’t add items, setting the SelectedValue to a value will not persist.

public void TestMethod1()
var dropDownList = new DropDownList();
dropDownList.SelectedValue = "First item";
Assert.AreEqual(string.Empty, dropDownList.SelectedValue);
dropDownList.Items.Add("First item");
Assert.AreEqual("First item", dropDownList.SelectedValue);

Leave a Reply

Your email address will not be published. Required fields are marked *