0

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.

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;  
}

5 Comments

Thanx. But how to run this at program start then? Just remove the public DataTable MakeDataTable() ?
what do you want to put in the DataTable that needs to be there when the program starts?
I want the data that is in my database to be showed when I start up the form4.cs That is the all.
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; }
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.