locked
Gridview rowcount problem when new row is inserted in the Grid for SubHeading based on the business logic RRS feed

  • Question

  • User244471529 posted

    Hello Team,

    I am facing the similar problem what "Rameezwaheed" has posted in 2011. here is the thread, I don't find the answer for that.

    https://forums.asp.net/t/1749430.aspx?Gridview+Rows+count+Porblem

    When I am traversing the Grid view row by row,  after inserting the subheading rows (based on the business logic), it is not going to the last record of Grid view due to the subheading rows I have inserted.

    ------------ Below is the description of the issue which was posted by Rameezwaheed and I am facing the exactly the same issue ----------------

    I have Gridview  and i have added the Sub header row to Gridview at Row Databound event it displays correctly but while loop through the Gridview i am getting the original rows count not with the sub header row .

    Suppose there 8 data rows and two are sub header rows but while loop iam getting the original count 8

    Here is my code at row data bound event

    // If the current row is a DataRow (and not a Header or Footer row), then do stuff.
                  if (e.Row.RowType == DataControlRowType.DataRow)
                  {
                      DataRowView drv = (DataRowView)e.Row.DataItem;
                      if (tmpCategoryName != drv["MajorName"].ToString())
                      {
                          tmpCategoryName = drv["MajorName"].ToString();
                          // Get a reference to the current row's Parent, which is the Gridview (which happens to be a table)
                          Table tbl = e.Row.Parent as Table;
                          if (tbl != null)
                          {
                              GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
                              TableCell cell = new TableCell();
                              // Span the row across all of the columns in the Gridview
                              cell.ColumnSpan = this.grdProduction.Columns.Count;
                              cell.Width = Unit.Percentage(100);
                              cell.Style.Add("font-weight", "bold");
                              cell.Style.Add("text-align", "center");
                              HtmlGenericControl span = new HtmlGenericControl("span");
                              span.InnerHtml = "(" + tmpCategoryName + ")";
                              cell.Controls.Add(span);
                              row.Cells.Add(cell);
                           
                              tbl.Rows.AddAt(tbl.Rows.Count - 1, row);
                          }
                      }
                  }

     

    And iam traversing the Gridview like below

    for (int i = 0; i < Gridview1.Rows.Count; i++)
                    {
                        if (Gridview1.Rows[i].RowType == DataControlRowType.DataRow)
                        {
    }
    }
    Thursday, May 18, 2017 6:00 PM

All replies

  • User64294366 posted

    Suggestion, each time a sub header is created add a count of 1 to  variable x and assign to viewstate or hidden field. On Postback, retrieve the header count and add to Gridview.Rows.Count.

    Saturday, May 20, 2017 12:26 AM
  • User244471529 posted
    Thanks for your reply, I tried that already. If I add that subhead count and trying to find the controls roe by row, it throws an error saying row index is out of bound.
    If I don't add up the sub header count then it skips the last rows I.e, how many ever sub headings were added in between

    Saturday, May 20, 2017 1:00 AM
  • User-271186128 posted

    Hi konatham,

    konatham

    I have Gridview  and i have added the Sub header row to Gridview at Row Databound event it displays correctly but while loop through the Gridview i am getting the original rows count not with the sub header row .

    According to your code and description, I suppose the issue is related that you are adding client html elements, instead of web server control. And, even if you want to use web server control, the controls should add in the Page_Load or Page_Init event, instead of using GridView RowDataBound event.

    So, I suggest you could directly add rows in the GridView data source (suppose you are using DataTable to bind the GridView). Please refer to the following code:

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="EmployeeID">
                <Columns>
                    <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
                    <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                    <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                </Columns>
            </asp:GridView>
            <asp:Button ID="btnGetGroupName" runat="server" Text="Get Group Name" OnClick="btnGetGroupName_Click" />
            <asp:Label ID="lbloutput" runat="server" Text=""></asp:Label>

    Code in page (.aspx.cs)

           protected void Page_Load(object sender, EventArgs e)
            {
                BindGrid();
            }
    
            private void BindGrid()
            {
    //query database string query = "SELECT [EmployeeID], [Country], [FirstName], [LastName] FROM [Employees] order by [Country]"; string conString = ConfigurationManager.ConnectionStrings["MyTestDBConnStr2"].ConnectionString; using (SqlConnection con = new SqlConnection(conString)) { using (SqlCommand cmd = new SqlCommand(query)) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd;

    //create a DataTable to store the Data Source using (DataTable dt = new DataTable()) { sda.Fill(dt);
    //Loop through the DataTable and add sub group title. for(int i=dt.Rows.Count-1; i>= 0; i--) { if (i > 0) { if (!dt.Rows[i]["Country"].Equals(dt.Rows[i - 1]["Country"])) { var newrow = dt.NewRow(); //add a new row newrow["EmployeeID"] = DBNull.Value; //assign a null value. newrow["Country"] = dt.Rows[i]["Country"]; //assign the sub header dt.Rows.InsertAt(newrow, i); } } else { var newrow = dt.NewRow(); newrow["EmployeeID"] = DBNull.Value; newrow["Country"] = dt.Rows[i]["Country"]; dt.Rows.InsertAt(newrow, i); } } //Bind GridView using the new table GridView1.DataSource = dt; GridView1.DataBind(); } } } } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if(e.Row.RowType == DataControlRowType.DataRow) {
    //Find the Sub Heading row, and merge cells. var rowData = ((DataRowView)e.Row.DataItem).Row; if (rowData["EmployeeID"] == DBNull.Value) { e.Row.Cells.Remove(e.Row.Cells[3]); e.Row.Cells.Remove(e.Row.Cells[2]); e.Row.Cells[1].ColumnSpan = 4; e.Row.Cells.Remove(e.Row.Cells[0]); } } } protected void btnGetGroupName_Click(object sender, EventArgs e) { List<string> strlist = new List<string>();
    //loop through GridView for (int i = 0; i < GridView1.Rows.Count; i++) { if (GridView1.Rows[i].RowType == DataControlRowType.DataRow) { string name = GridView1.Rows[i].Cells[0].Text; //find the sub header row. if ( GridView1.Rows[i].Cells.Count ==1) { strlist.Add(name); } } } lbloutput.Text = string.Join(",", strlist); }

    The output as below:

    Best regards,
    Dillion

    Wednesday, May 24, 2017 3:18 AM