How to create a datatable using C# from SQL?
I need some help with make a datatable from sql. I'm a Newbie.
I want to make my own datatable f开发者_C百科rom scratch in codebehind and now with the premade that is in Visual Studio.
You need to use a SqlDataAdapter
to fill the DataTable
.
Try something like this:
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(yourConnectionString))
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(yourQuery, connection))
{
adapter.Fill(dataTable);
}
}
Here's probably the most basic approach, using a IDataReader
(in this case, a SqlDataReader
) to populate a DataTable
public DataTable MakeDataTable()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection("ConnectionStringHere"))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.Text = "SELECT * FROM MyTable";
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
table.load(rdr);
}
}
}
return table;
}
精彩评论