Populating a SelectList from a DataTable

From https://stackoverflow.com/questions/1439374/populating-a-selectlist-from-a-datatable

public static SelectList ToSelectList(this DataTable table, string valueField, string textField)
{
    List<SelectListItem> list = new List<SelectListItem>();

    foreach (DataRow row in table.Rows)
    {
        list.Add(new SelectListItem() 
        {
            Text = row[textField].ToString(), 
            Value = row[valueField].ToString()
        });
    }

    return new SelectList(list, "Value", "Text");
}


public static System.Web.Mvc.SelectList DT2SelectList(DataTable dt, string valueField, string textField){            
        if (dt == null || valueField == null || valueField.Trim().Length == 0
            || textField == null || textField.Trim().Length ==0)
            return null;


        var list = new List<Object>();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            list.Add(new
            {
                value = dt.Rows[i][valueField].ToString(),
                text = dt.Rows[i][textField].ToString()
            });
        }
        return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text");
    }

About Nguyễn Viết Hiền

Passionate, Loyal
This entry was posted in ASP.NET MVC, C#, Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s