Here we will discuss the following concepts:
- How to bind the data to GridView using stored procedure.
- Merge the cells in GridView.
At Database:
Create the following table in your database to demonstrate the above concepts.
Copy the following script and run in your database to create USP_GetAllEmployeesByDept stored procedure.
- Create procedure [dbo].[USP_GetAllEmployeesByDept]
- AS
- Begin
- SELECT DeptID, Name, Salary
- FROM Mas_Employee
- GROUP BY DeptID, Name, Salary
- END
Implementation:
Create new ASP.NET Empty Web Application and give it a meaningfull name. Add one webform to your project.
In Web.config:
Make the connection string in web.Config.
- <connectionStrings>
- <add name="conStr" connectionString="Password = 1234; User ID=sa; Database = DB_DEV_JAI; Data Source = ."
- providerName="System.Data.SqlClient" />
- </connectionStrings>
Design Your.aspx:
Copy the following code in your design page.
- <div>
- <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound">
- <Columns>
- <asp:BoundField DataField="DeptId" HeaderText="DeptId" ItemStyle-Width="120" />
- <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
- <asp:BoundField DataField="Salary" HeaderText="Salary" ItemStyle-Width="120" />
- </Columns>
- </asp:GridView>
- </div>
CodeBehind :
Add the following namespaces:
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
Next copy the following code in your .cs file:
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!this.IsPostBack)
- {
- BindGrid();
- }
- }
- private void BindGrid()
- {
- try
- {
- SqlCommand cmd = new SqlCommand("USP_GetAllEmployeesByDept", con);
- cmd.CommandType = CommandType.StoredProcedure;
- SqlDataAdapter adp = new SqlDataAdapter(cmd);
- DataSet ds = new DataSet();
- adp.Fill(ds);
- if (ds.Tables[0].Rows.Count > 0)
- {
- GridView1.DataSource = ds;
- GridView1.DataBind();
- }
- else
- {
- GridView1.DataSource = null;
- GridView1.DataBind();
- }
- }
- catch (Exception ex) {} finally
- {
- con.Close();
- }
- }
-
- protected void OnDataBound(object sender, EventArgs e)
- {
- for (int i = GridView1.Rows.Count - 1; i > 0; i--)
- {
- GridViewRow row = GridView1.Rows[i];
- GridViewRow previousRow = GridView1.Rows[i - 1];
- for (int j = 0; j < row.Cells.Count; j++) {
- if (row.Cells[j].Text == previousRow.Cells[j].Text)
- {
- if (previousRow.Cells[j].RowSpan == 0)
- {
- if (row.Cells[j].RowSpan == 0)
- {
- previousRow.Cells[j].RowSpan += 2;
- }
- else
- {
- previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
- }
- row.Cells[j].Visible = false;
- }
- }
- }
- }
- }
That's it, run the application and the output will be the following:
I hope you enjoyed it. Please provide your valuable feedback and suggestions if you found this article helpful.