I need some help with make a datatable from sql. I'm a Newbie.
I want to make my own datatable from 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;
}
load event. Double-click this in the properties pane to create an EventHandler for the event. Inside of the event handler, put DataTable table = MakeDataTable(); and then set the data source of whatever control you are using to present the data to the user to be table