Find Tables in a Dataset - Sql Server

The DataSet in ADO.NET consists of a DataTableCollection and a DataRelationCollection. The DataTableCollection serves as a container that holds zero or more DataTable objects. Each DataTable object represents a structured table of data within the DataSet.

The DataSet itself is capable of accommodating data for one or more members, which corresponds to the number of rows present. This means that the DataSet can store and manage multiple sets of data within its structure.

Determine the number of tables present in a DataSet

In certain situations, it becomes necessary to determine the number of tables present in a DataSet. We can achieve this by accessing the DataTableCollection property of the DataSet. This collection provides access to the DataTables contained within the DataSet. By examining the count or using other appropriate methods, we can retrieve the number of tables residing in the DataSet.

Full Source C#
using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connetionString = null; SqlConnection connection; SqlCommand command ; SqlDataAdapter adapter = new SqlDataAdapter(); DataSet ds = new DataSet(); string sql = null; connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"; sql = "Your SQL Statement Here"; connection = new SqlConnection(connetionString); try { connection.Open(); command = new SqlCommand(sql, connection); adapter.SelectCommand = command; adapter.Fill(ds, "SQL Temp Table"); adapter.Dispose(); command.Dispose(); connection.Close(); foreach (DataTable tables in ds.Tables) { MessageBox.Show (tables.TableName); } } catch (Exception ex) { MessageBox.Show("Can not open connection ! "); } } } }

To populate the DataTables within a DataSet, we can utilize the SqlDataAdapter object. The SqlDataAdapter provides a convenient way to retrieve data from a data source and populate the DataTables within the DataSet accordingly. It acts as a bridge, facilitating the communication between the data source and the DataSet.

Conclusion

ADO.NET provides data table creation capability and enables its insertion into the data set that already exist . The DataSet containing ample space for the DataTableCollection and DataRelationCollection will accordingly accommodate the detection of numerous DataTables and their intricate relationships. When we implement SqlDataAdapter we will have a collection of DataTables in DataSet filled with data from data source. On some instances, we shall have to figure out the number of tables exemplified on a DataSet, which can be confirmed through the DataTableCollection property.