I have legacy code that I am slowly moving to C# MVC. How would I create a dropdownlist from a data table or dataset? I do not want to create properties and loop through a list because I have too many ancient MS Access queries to deal with.
CONTROLLER:
using (SqlConnection Connection = new SqlConnection(ConnectionString))
{
string commandstring = "select column1 from table1";
SqlCommand command = new SqlCommand(commandstring, Connection);
Connection.Open();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = command;
da.Fill(ds, "data1");
Connection.Close();
}
As George stated, I would suggest moving the domain logic into a data access layer and using entities to hold your objects that were returned from a query. You can use Dapper which allows you to use raw SQL queries and have the results mapped to models. Its performance is same as
SqlDataReader. Here is an extension method that will take a list of models and turn them into a dropdown list.Then you can use the code like …