m-u
9/16/2013 - 2:17 PM

Set select item to dropdownlist

Set select item to dropdownlist

using System;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

using MiniRideAndDrive.Web.Data;

public static partial class Helpers {

    public static string BaseUrl {
        get { return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/"); }
    }

    public static void SetSelectedListItem(this DropDownList ddl, string value) {
        ListItem li;

        li = ddl.Items.FindByValue(value);
        if (li != null) li.Selected = true;
    }

    public static void PopulateItems(this DropDownList ddl, object dataSource, string dataTextField, string dataValueField, string firstItemText) {
        if (ddl == null)
            return;

        ddl.DataTextField = dataTextField;
        ddl.DataValueField = dataValueField;
        ddl.DataSource = dataSource;
        ddl.DataBind();
        
        if(!string.IsNullOrEmpty(firstItemText))
            ddl.Items.Insert(0, new ListItem(firstItemText, "null"));
    }
}