Tuesday, June 28, 2011

how to bind Datagridview in windows application using c#.net

how to bind Datagridview in windows application using c#.net

Monday, December 27, 2010
Introduction

Here I will explain how to bind Datagridview in windows application using c#.net.

Description

I have started working on windows application at that time I don’t know how to use Datagridview and other controls. I face some problems to bind data to Datagridview and to other controls that’s why I am writing this post to explain how to bind data to Datagridview in windows application. In windows application binding Datagridview is somewhat different when compared with web application Datagridview binding.

First create one windows forms application now form.cs will open after that drag and drop Datagridview from All windows form category after that write the following code in code behind to bind data to Datagridview.


//This connection string is used to connect to database
String strConnection = "Data Source=MYSYSTEM;Initial Catalog=MySamplesDB;Integrated Security=True";
//Establish SQL Connection
SqlConnection con = new SqlConnection(strConnection);
//Open database connection to connect to SQL Server
con.Open();
//Data table is used to bind the resultant data
DataTable dtusers = new DataTable();
// Create a new data adapter based on the specified query.
SqlDataAdapter da = new SqlDataAdapter("Select * from User_Information", con);
//SQl command builder is used to get data from database based on query
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
//Fill data table
da.Fill(dtusers);
//assigning data table to Datagridview
dataGridView1.DataSource = dtusers;
//Resize the Datagridview column to fit the gridview columns with data in datagridview
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();

After bind data to datagridview that should be like this

Demo



No comments:

Post a Comment