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.
Santhakumar MunuswamyPosted Jun 22, 2015, 2:43 PM
Nice one