简体   繁体   中英

Populating a SelectList from a DataTable

I ran a query and returned a datatable,

myDataAdapter.Fill(myDataTable);

Now what is the best way to load the row values "Value" and "Text" into a SelectList?

Thanks

I couldn't find a way to directly bind the DataTable to a SelectList so I resolved creating an Extension method to accomplish this:

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");
    }

I wrote this for u

Assuming your DataTable has 2 columns (text and value), you have to

1. Set the DropDownList's DataSource to the table
2. Set the DataTextField to the text column name
3. Set the DataValueField to the value column name
4. Call the Databind method

Here is what I came up with it seems to work well, But I was wondering if this is the best way.

First I created an object that looks like my results form my query,

public class MyTestObj
{
    public string Value_CD { get; set; }
    public string Text_NA { get; set; }
}

Then I create a ILIST and populate it with the datatable rows

IList<MyTestObj> MyList = new List<MyTestObj>();
foreach (DataRow mydataRow in myDataTable.Rows)
{
  MyList.Add(new MyTestObj()
  {
    Value_CD = mydataRow["Value"].ToString().Trim(),
    Text_NA  = mydataRow["Text"].ToString().Trim()                      
  });
}

return new SelectList(MyList, "Value_CD", "Text_NA");

Any comments on this approach?

Datatable contains an extension method AsDataView . You can use this extension method to populate SelectList from a DataTable. A sample of code :

DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add("1", "test");
//populate selectlist with DataTable dt
var selectList = new SelectList(dt.AsDataView(), "Id", "Name");

Here Id in the SelectList is the selectedValue column and Name is the DisplayMember column.

Looks fine. I would make it a bit cleaner by creating a constructor for MyTestObj that accepted a DataRow. That would allow you to write:

MyList.Add(new MyTestObj(mydataRow));

It's way too late for me to answer but I think this might be an optimized way to do it, hope it works.

List<SelectListItem> listName= new List<SelectListItem>();

for (int i = 0; i < datatableName.Rows.Count; i++)
   {
     listName.Add(new SelectListItem { Text = datatableName.Rows[i]["ColumnName"].ToString(), Value = datatableName.Rows[i]["ColumnName"].ToString() });
   }

You can also loop through the column names as well by applying another loop and using that as an index at the column identifier of the datatable.

Thank You.

Completely in the line of 'Dot Net Developer' answer, I add my full implementation of his/her solution:

 /// <summary>
    /// retrieve the document types from the database
    /// </summary>
    /// <returns></returns>
    private SelectList FillDocumentTypes()
    {
        SqlCommand command = null;
        SqlConnection _sqlcon = null;
        SelectList result = null;
        try
        {
            _sqlcon = new SqlConnection(connectionString);
            string commandText = string.Concat("select Code, [Description] from tblC2scDocumentTypeCodes");

            command = new SqlCommand(commandText, _sqlcon);
            _sqlcon.Open();
            SqlDataAdapter dataAdapter = new SqlDataAdapter(commandText, _sqlcon);

            DataTable dataTable = new DataTable();

            dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(dataTable);

            //populate selectlist with DataTable dt
            result = new SelectList(dataTable.AsDataView(), "Code", "Description");

            _sqlcon.Close();
            return result;

        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
          }
        finally
        {
            command.Dispose();
            _sqlcon.Dispose();
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM