开发者

c# if i need just one table, should i be using DataSet or DataTable?

here is my code.

public DataSet ConnectandReadList()
{
    DataSet ds = new DataSet();

    string connection_string="Data Source=hermes;database=qcvalues; Integrated Security=SSPI;";            

    using (var myConnection = new SqlConnection(connection_string))
    {

        myConnection.Open();
        var command = new SqlCommand(InitializeQuery(), myConnection);
        var adapter = new SqlDataAdapter(command);

        adapter.Fill(ds);
    }

    return ds;

}

i then set the datasource this way:

dataGridView1.Data开发者_Go百科Source = ds.Tables[0];

the question is should i be returning a dataset or datatable? how would my code change if i were to be returning datatable?


I just return a DataTable when in your situation. And the more correct code is

using (var command = new SqlCommand(InitializeQuery(), myConnection))
using (var adapter = new SqlDataAdapter(command))
    adapter.Fill(ds);


Change the word DataSet to DataTable and recompile. You will get an error where you consume this method's result, but you just need to change dataGridView1.DataSource = ds.Tables[0]; to dataGridView1.DataSource = ds;


Just replace all of your DataSet by DataTable (and for readability, all ds by resultTable) - or did I miss anything?


http://imar.spaanjaars.com/406/filling-a-datatable-or-dataset-the-quick-way

private DataTable GetDataTable()
{
  string sql = "SELECT Id, Description FROM MyTable";
  using (SqlConnection myConnection = new SqlConnection(connectionString))
  {
    using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
    {
      myConnection.Open();
      using (SqlDataReader myReader = myCommand.ExecuteReader())
      {
        DataTable myTable = new DataTable();
        myTable.Load(myReader);
        myConnection.Close();
        return myTable;
      }
    }
  }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜