开发者

How to create a datatable using C# from SQL?

开发者 https://www.devze.com 2022-12-13 06:28 出处:网络
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 us

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

精彩评论

暂无评论...
验证码 换一张
取 消