In this article I will explain with an example, how to create dummy DataTable in Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
The following Form consists of:
DataGridView – For displaying data.
Namespaces
You will need to import the following namespace.
C#
VB.Net
Creating Dummy DataTable in Windows Forms
Inside the Form Load event handler, an object of DataTable is created.
Then, three columns are added to the DataTable Columns collection using the AddRange method.
Inside the AddRange method, an Array of the objects of type DataColumn is specified to which, the name and the optional parameter Data Type i.e. the Type of the column is passed.
Once the schema is ready i.e. all the columns are defined and some rows have been added using the Rows.Add method.
Finally, DataTable object is assigned to the DataSource property of the DataGridView and the DataGridView is populated.
C#
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country", typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
dataGridView1.DataSource = dt;
}
VB.Net
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(2) {
New DataColumn("Id", GetType(Integer)),
New DataColumn("Name", GetType(String)),
New DataColumn("Country", GetType(String))})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
dataGridView1.DataSource = dt
End Sub
Screenshot
Downloads