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 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
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?
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));