This blog is based on the DataTable and DataGridView operations in C# WinForms application.
Here, my table name is Users which contains the data of the users of a company stored into the DataTable named as dt3.
no | Emp_name |
1 | Ramesh |
2 | Satish |
3 | Anant |
I want to display this data table in GridView like in the following image.
Output
no | company_name | user1 | user2 | user3 |
1 | TCS | Ramesh | Satish | Anant |
Note
Before writing the code, add the "usingsystem.data.sqlclient" namespace to your file.
Step 1
Make a database with a table in SQL Server.
Step 2
Create a Windows application and add DataGridView on the form. Now, add a DataGridView control to the form by selecting it from the Toolbox and set properties according to your need.
Step 3 - Adding Source Code for GridView
Now, you can add these few lines of code anywhere in your file to load the data from the database. Using the below-mentioned code, you can add a column to the DataGridView manually. Here, I have created a function named as display() to add a column manually and call it at the form load event.
- public void display() {
- try {
- DataTable dt2 = new DataTable();
- dt2.Columns.Add("Id", Type.GetType("System.String"));
- dt2.Columns.Add("company_name", Type.GetType("System.String"));
- dt2.Columns.Add("user1", Type.GetType("System.String"));
- dt2.Columns.Add("user2", Type.GetType("System.String"));
- dt2.Columns.Add("user3", Type.GetType("System.String"));
- } catch (Exception e) {
- MessageBox.Show(e.Message);
- }
- }
- private void Form2_Load(object sender, EventArgs e) {
- display();
- }
Step 4
Here, I am filling the dt3 data table with the employee names.
- string str = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\audit\employees\employees\App_data\Database1.mdf;Integrated Security=True";
- SqlConnection sc = new SqlConnection(str);
- sc.Open();
- SqlDataAdapter sda = new SqlDataAdapter("select top 3 Id,Emp_name from Users", sc);
- DataTable dt3 = new DataTable();
- sda.Fill(dt3); //fill datatable by top3 employee name
- sc.Close();
Step 5
After step 4, I am adding the following code to display the datatable data in different columns of DataGridView.
- if (dt3.Rows.Count != 0)
- {
- DataRow dr = dt2.NewRow();
- dr["Id"] = dt3.Rows[0]["Id"].ToString();
- dr["company_name"] = "TCS";
- int tbl_cnt = dt3.Rows.Count;
- int cnt = 0;
- dr["user1"] = dr["user1"] + dt3.Rows[cnt]["Emp_name"].ToString();
- cnt++;
- if (cnt < tbl_cnt) {
- dr["user2"] = dr["user2"] + dt3.Rows[cnt]["Emp_name"].ToString();
- }
- cnt++;
- if (cnt < tbl_cnt) {
- dr["user3"] = dr["user3"] + dt3.Rows[cnt]["Emp_name"].ToString();
- }
- dt2.Rows.Add(dr);
- }
- DataTable result = dt2;
- result.AcceptChanges();
- dataGridView1.DataSource = dt2;
Output