Populating a SelectList from a DataTable

前端 未结 8 1113
说谎
说谎 2020-12-18 11:12

I ran a query and returned a datatable,

myDataAdapter.Fill(myDataTable);

Now what is the best way to load the row values \"Value\" and \"Te

8条回答
  •  难免孤独
    2020-12-18 11:28

    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.

提交回复
热议问题