Use of GridView with DataSet and DataTable
Use of DataGridView with DataSet And DataTable:
· DataGridView is used to display data in C# application like data is displayed in Sql Server table.
· DataGridView provides easy manipulation of data you can insert, delete and update records in GridView and save changes in database.
Difference between DataSet and DataTable:
The functionality of DataTable and DataSet classes is available in the namespace System. Data. If you do not include this namespace in your application you cannot use these classes.
DataTable:
DataTable holds record of only a single table associated with it.
DataSet:
DataSet is a collection of multiple DataTable.
We can use the table we want by specifying its index in DataSet or by specifying its name.
Now let’s look at an example which will display data from database in DataGridView first by using DataTable and then by DataSet.
Example:
· Start a new WindowsFormApplication.
· Add a button on the form.
· Add a DataGridView on the form located in Data section of toolbox.
· Select the DataGridView and go to properties.
· Change the name property of DataGridView to MyDataGridView.
· Data will be displayed in GridView when button will be clicked.
Using DataTable:
public partial class DataTableForm : Form
{
SqlConnection Con = new SqlConnection(@"Data Source=MINHAS-A65DA31B\SQLEXPRESS;Initial Catalog=CIS;Integrated Security=True");
public DataTableForm ()
{
InitializeComponent();
}
private void ShowData_Click(object sender, EventArgs e)
{
Con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from person",Con)
DataTable dt = new DataTable();
da.Fill(dt);
MydataGridView.DataSource = dt;
Con.Close();
}
}
Using DataSet:
public partial class DataSetForm : Form
{
SqlConnection Con = new SqlConnection(@"Data Source=MINHAS-A65DA31B\SQLEXPRESS;Initial Catalog=CIS;Integrated Security=True");
public DataSetForm()
{
InitializeComponent();
}
private void ShowData_Click(object sender, EventArgs e)
{
Con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from person",Con);
DataSet ds = new DataSet();
da.Fill(ds);
MydataGridView.DataSource = ds.Tables[0];
Con.Close();
}
}
Data will be displayed in GridView like this.
The KetticDataGridView is capable of populating the GridView with database table or dataset
ReplyDelete