Using DataGridView in Windows Application

In this article we will see how to use DataGridView. DataGridView is used to display data. In web applications we use Grid View and in Windows application we use the DataGridView.

First of all we add App.config file and write the connection String in it. The contents of the app.config file are as follows.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=DataDirectory\Database1.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
</configuration>

Add the control to the form
Drag and drop a DataGridView from the toolbox on to the form in design mode.

Add Reference
Right click on your project in Solution explorer and select “Add Reference”.In .NET Tab
select “System.Configuration” and add it.

Code
In Form1.cs

Add the following code
using System.Configuration;

public Form1()
{
InitializeComponent();
dataGridView1.DataSource = getData();
dataGridView1.DataMember = "Table1";
}

private DataSet getData()
{
DataSet ds = null;
SqlConnection conn = null;
try
{
string connString = ConfigurationManager.ConnectionStrings
["MyConnectionString"].ConnectionString;
conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoredProcName";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
ds = new DataSet();
sda.Fill(ds);
ds.Tables[0].TableName = "Table1";
conn.Close();
}
catch (SqlException se)
{
}
finally
{
if (conn != null)
conn.Close();
}
return ds;
}