Thursday, June 9, 2016

Windows Form application: Binding data to Grid View


Whenever we want to display data in the form of a table or grid, we use the grid control available in the toolbox.  Before using this grid view, make sure that you have created a table in your database. For example, a table like student (UserId, UserName,FirstName,LastName ).

 You can create your own table with appropriate attributes. Once the table is created, insert some data into it.

Now, Open visual studio, open new project. Select Windows Form Application. change the name and stored location of the form as required.You can also add a new form to your existing project as follows.
solution Explorer->right click on project->add new form

Now, drag and drop the DataGridView control from the toolbox onto the form.
That will look like the figure given below.



 
DataGridView control




















 Now, right click on the form and click on view code option to get the code area. Add the following namespaces (if not added previously) at the beginning of the code.

using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

Use the following code appropriately. 


public partial class BindDataGridview : Form
{
public BindDataGridview()
{
InitializeComponent();
BindData();      // function definition given below.
}
// Bind Data to DataGridView
private void BindData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=Siyaram;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from student", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
dataGridView1.DataSource = dt;
}
}


Save your project, correct the errors if any. See the result as given below.

Result

 Enjoy Programming.

No comments:

Post a Comment