ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

DataBind

Bind to a ListControl (Dropdownlist, listbox, checkboxlist, radiobutton) in minimal amounts of code. Also returns true false if items are in the control after binding and sets the selected index to first value.

Source

public static bool DataBind(this ListControl control, object datasource, string textField, string valueField)
{
    return DataBind(control, datasource, textField, null, valueField);
}

public static bool DataBind(this ListControl control, object datasource, string textField, string textFieldFormat, string valueField)
{
    control.DataTextField = textField;
    control.DataValueField = valueField;

    if (!string.IsNullOrEmpty(textFieldFormat))
        control.DataTextFormatString = textFieldFormat;

    control.DataSource = datasource;
    control.DataBind();

    if (control.Items.Count > 0)
    {
        control.SelectedIndex = 0;
        return true;
    }
    else return false;
}

Example

Dictionary<int, string> data = new Dictionary<int,string>();
data.Add(0,"Apple");
data.Add(1,"Orange");
data.Add(2,"Pair");

DropDownList ddl = new DropDownList();
ddl.DataBind(data, "value", "key");

ListBox lbx = new ListBox();
lbx.DataBind(data, "value", "key");

Author: Matt G

Submitted on: 30 jul. 2009

Language: C#

Type: System.Web.UI.WebControls.ListControl

Views: 4953