Dec 17

Using the syntax ‘DropDownList1.SelectedIndex = 10;’ does not create an exception, but using the syntax ‘DropDownList.Items.FindByValue(“10”).Selected = true;’ can create the following exception:

Cannot have multiple items selected in a DropDownList.   at System.Web.UI.WebControls.DropDownList.VerifyMultiSelect()

Calling ClearSelection() on the DropDownList first will avoid this exception. It is also a good idea to first check and make sure that the value actually exists as an item within the DropDownList as in the following example:

private void SetDropDownListSelectedItem(string selectedValue)

{

  ListItem li = DropDownList1.Items.FindByValue(selectedValue);

  if (li != null)

  {

    DropDownList1.ClearSelection();

    li.Selected = true;

  }

}

Tagged with:
Dec 15

A simple method to highlight the text within a textbox control when the control gets the focus:

protected void Page_Load(object sender, EventArgs e)

        {

            //Add client javascript to highlight the value when the control receives the focus

            txtMyTextBox.Attributes.Add("onfocus", "this.select();");

        }


This is a nice and easy way to highlight a default value in a form or a search box.

Tagged with:
preload preload preload