tags:

views:

61

answers:

2

I need some help with make a datatable from sql. Is it someone that can help me please. I'm a Newbie. But I want to make my own datatable from scratch in codebehind and now with the premade that is in Visual Studio.

Can someone please help me do this?

A: 

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;  
}
Russ Cam
Thanx. But how to run this at program start then? Just remove the public DataTable MakeDataTable() ?
tkjensen
what do you want to put in the DataTable that needs to be there when the program starts?
Russ Cam
I want the data that is in my database to be showed when I start up the form4.cs That is the all.
tkjensen
Can't get it to start from Form start. Can you tell me please? This is my form start process. But it's nothing in it here. I want it to be in it but can't find out how.private void Vis_Load(object sender, EventArgs e){}public DataTable MakeDataTable(){DataTable table = new DataTable();Connection string her: =){using (SqlCommand cmd = conn.CreateCommand()){cmd.CommandText = "SELECT * FROM MyTable";conn.Open();using (SqlDataReader rdr = cmd.ExecuteReader()){table.Load(rdr);}}}return table;}
tkjensen
ok, your Form has a `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`
Russ Cam
Ok. I'll try. Thanx for the reply. =)
tkjensen
+1  A: 

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);
    }
}
Andrew Hare
Thanx a lot. I'll try. =)
tkjensen