Question what is the difference between DataTable and DataSet?

marjune

Member
Joined
May 4, 2010
Messages
16
Programming Experience
Beginner
i want to display data to DataGridView using DataSet which is didn't work DataTable instead,,thanks hers my code!!


Using DataSet

Dim Sql As String
Dim Command As New SqlCommand... See More
Dim Adapter As New SqlDataAdapter
Dim Sqlconn As New SqlConnection
Dim ds As New DataSet

Sql = "Sql Statement here;"

Sqlconn.ConnectionString = connection
Try

Command.Connection = Sqlconn
Command.CommandText = Sql
Adapter.SelectCommand = Command
Adapter.Fill(ds)

If dt.Tables(0).Rows.Count() > 0 Then
DataGridView1 = dt
Else
DataGridView1 = Nothing
End If

Catch ex As Exception
MsgBox(ex.Message)
End Try


Using DataTable then its work



Dim Sql As String



Dim Command As New SqlCommand



Dim Adapter As New SqlDataAdapter



Dim Sqlconn As New SqlConnection



Dim dt As New DataTable

Sql = "Sql Statement here;"

Sqlconn.ConnectionString = connection
Try

Command.Connection = Sqlconn
Command.CommandText = Sql
Adapter.SelectCommand = Command
Adapter.Fill(dt)

If dt.Rows.Count() > 0 Then
DataGridView1 = dt
Else
DataGridView1 = Nothing
End If

Catch ex As Exception
MsgBox(ex.Message)
End Try
 
The difference between a DataSet and a DataTable is analogous to the difference between a database and a table in that database. A DataSet is supposed to represent an in-memory database. It doesn't contain data directly, but rather contains DataTables and, optionally, DataRelations. If you want to store data then you need a DataTable, whether it's in a DataSet or not. All three of the following code snippets achieve the same thing:
VB.NET:
Dim data As New DataSet

myDataAdapter.Fill(data, "TableName")

myDataGridView.DataMember = "TableName"
myDataGridView.DataSource = data
VB.NET:
Dim data As New DataSet

myDataAdapter.Fill(data, "TableName")

myDataGridView.DataSource = data.Tables("TableName")
VB.NET:
Dim table As New DataTable

myDataAdapter.Fill(table)

myDataGridView.DataSource = table
 
thank you for your post!!! but which TableName i'll used in function myDataAdapter.Fill(data, "TableName") if my sql query is joining tables?
 
thank you for your post!!! but which TableName i'll used in function myDataAdapter.Fill(data, "TableName") if my sql query is joining tables?

That's completely up to you. That table name has no specific connection to the name of any table in the database. Generally speaking, if your query gets data from a single table then you would use the name of that table, but there's no requirement for you to do so. Most importantly, as always, the name you use should be descriptive and representative of the data.
 

Latest posts

Back
Top