locked
Gridview Column Not Merging Perfect Why RRS feed

  • Question

  • User2033107836 posted

    Hello

    This is the code im using in asp.net 2.0 C#

    public partial class WebForm138 : System.Web.UI.Page
        {
            private string constr = "data source=.;initial catalog=NORTHWND;integrated security=SSPI";
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable dt = GetSampleData();
                    GridView3.DataSource = dt;
                    GridView3.DataBind();
                }
            }
    
            protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
            {
                Session["__dt"] = null;
                DataTable dt = GetSampleData();
                GridView3.DataSource = dt;
                GridView3.DataBind();
            }
    
            private DataTable GetSampleData()
            {
                DataTable dt = new DataTable();
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string cmdtext = "select DateValue, BelongsTo, ItemName, Qty, Rate from TestTable t2 where BelongsTo = " + (DropDownList1.Text.Equals("Select") ? "BelongsTo" : "'" + DropDownList1.Text + "'");
                    // string cmdtext = "select BelongsTo, ItemName, Qty, Rate from TestTable t2";
                    using (SqlCommand cmd = new SqlCommand(cmdtext, con))
                    {
                        con.Open();
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
                        DataView dv = new DataView(dt);
                        dv.Sort = "BelongsTo ASC";
                        GridView3.DataSource = dt;
                        GridView3.DataBind();
                    }
                }
                return dt;
            }
    
            protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow && null != e.Row.DataItem)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    if (Session["__dt"] == null)
                        Session["__dt"] = dt;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    string currentItem = string.Empty;
                    string NextItem = string.Empty;
                    if (e.Row.RowIndex >= 1)
                    {
                        currentItem = dt.Rows[e.Row.RowIndex]["ItemName"].ToString();
                        NextItem = dt.Rows[e.Row.RowIndex - 1]["ItemName"].ToString();
    
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
    
                        string span = string.Empty;
                        if (NextItem.Equals(currentItem) && NextNum.Equals(currentNum))
                        {
                            if (null != Session["__spanCnt"])
                                span = Convert.ToString(Session["__spanCnt"]);
                            span += (e.Row.RowIndex - 1).ToString() + ",";
                            Session["__spanCnt"] = span;
    
                        }
                        else
                        {
                            if (null != Session["__spanCnt"])
                                span = Convert.ToString(Session["__spanCnt"]);
                            span += (e.Row.RowIndex - 1).ToString() + ",";
                            int tempCnt = 1;
                            int firstIdx = 0;
                            foreach (string item in span.Split(new char[] {',' },StringSplitOptions.RemoveEmptyEntries))
                            {
                                if (tempCnt > 1)
                                    GridView3.Rows[Convert.ToInt32(item)].Cells.RemoveAt(1);
                                if (tempCnt == 1)
                                    firstIdx = Convert.ToInt32(item);
                                GridView3.Rows[Convert.ToInt32(firstIdx)].Cells[1].RowSpan = tempCnt;
                                tempCnt++;
                            }
                            Session["__spanCnt"] = null;
                        }
    
                        decimal RateTotal = 0;
                        if (currentNum != NextNum)
                            AddTotalRow("Belongs To: " + currentNum, GetTotal(dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
                    }
                    else if (e.Row.RowIndex == 0)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        AddTotalRow("Belongs To: " + currentNum, null, null);
                    }
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    if (Session["__dt"] != null)
                    {
                        decimal RateTotal = 0;
                        DataTable dt = (Session["__dt"] as DataTable);
                        AddTotalRow(null, GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
    
                        decimal qtyTotal = 0;
                        decimal rateTotal = 0;
                        foreach (DataRow item in dt.Rows)
                        {
                            qtyTotal += Convert.ToDecimal(item["Qty"]);
                            rateTotal += Convert.ToDecimal(item["Rate"]);
                        }
                        GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                        row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                        row.Cells.AddRange(new TableCell[]
                        { new TableCell() { Text = "Grand Total: ", CssClass="GrandTotal", ForeColor = Color.Red}, new TableCell() { Text = qtyTotal.ToString(), CssClass="GrandTotal", ForeColor = Color.Red}, new TableCell() { Text = rateTotal.ToString(), CssClass="GrandTotal", ForeColor = Color.Red} });
                        GridView3.Controls[0].Controls.Add(row);
                    }
                }
            }
    
            private decimal GetTotal(string BelongsTo, out decimal RateTotal)
            {
                decimal retResult = 0;
                RateTotal = 0;
                if (Session["__dt"] != null)
                {
                    DataTable dt = (Session["__dt"] as DataTable);
                    foreach (DataRow row in dt.Rows)
                    {
                        if (Convert.ToString(row["BelongsTo"]).Equals(BelongsTo))
                        {
                            retResult += Convert.ToDecimal(row["Qty"]);
                            RateTotal += Convert.ToDecimal(row["Rate"]);
                        }
                    }
                }
                return retResult;
            }
    
            private void AddTotalRow(string value, string Total, string RateTotal)
            {
                if (!string.IsNullOrEmpty(Total))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.AddRange(new TableCell[]
                    { new TableCell() { Text = "Total: ", CssClass="SubTotal"}, new TableCell() { Text = Total, CssClass="SubTotal"}, new TableCell() { Text = RateTotal, CssClass="SubTotal"} });
                    GridView3.Controls[0].Controls.Add(row);
                }
                if (!string.IsNullOrEmpty(value))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.Add(new TableCell() { ColumnSpan = 3, CssClass = "BelongHeading", Text = value });
                    GridView3.Controls[0].Controls.Add(row);
                }
            }
        }

    If i pass cell number like 5 in this below code

     if (tempCnt > 1)
                                    GridView3.Rows[Convert.ToInt32(item)].Cells.RemoveAt(5);
                                if (tempCnt == 1)
                                    firstIdx = Convert.ToInt32(item);
                                GridView3.Rows[Convert.ToInt32(firstIdx)].Cells[5].RowSpan = tempCnt;
                                tempCnt++;

    Then its merging data here and there..

    I want to do that only cell 5 not before cell..

    Give me the code based on above code

    Thank You

    Friday, June 30, 2017 3:14 PM

Answers

  • User-271186128 posted

    Hi asp.ambur,

    Then its merging data here and there..

    I want to do that only cell 5 not before cell..

    Give me the code based on above code

    If you want to merge the 5th column, the index should be 4. It starts from 0.
    If you still fail to get your expected result, I suggest you share some sample data and your expected result here.

    Here is my test data and the result using your code to merge cells in the 5th column.

    Code as below:

     if (tempCnt > 1)
                                    GridView3.Rows[Convert.ToInt32(item)].Cells.RemoveAt(4);
                                if (tempCnt == 1)
                                    firstIdx = Convert.ToInt32(item);
                                GridView3.Rows[Convert.ToInt32(firstIdx)].Cells[4].RowSpan = tempCnt;
                                tempCnt++;

    The test data as below:

    The output as below:

    Best regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 3, 2017 9:11 AM