Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to change the number of rows in ASP .NET GridView

In this article, we will learn about adding and deleting the number of rows in the GridView of ASP .NET.

Many a times, we come across in various situations when we do not know about the total number of data that we want to enter. In that situation there is always a need of increasing and decreasing the rows.

Shows the image of entering the data for a single entry

Figure 1: Shows the image of entering the data for a single entry

Listing 1: Shows the code for designing the above template field

<asp:GridView ID="grvStudentDetails" runat="server" 
ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" 
GridLines="None" OnRowDeleting="grvStudentDetails_RowDeleting">
<Columns>
<asp:BoundFieldDataField="RowNumber" HeaderText="SNo" />
<asp:TemplateFieldHeaderText="Student Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateFieldHeaderText="Student Age">
<ItemTemplate>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateFieldHeaderText="Student Address">
<ItemTemplate>
<asp:TextBox ID="txtAddress" runat="server" 
                   Height="55px" TextMode="MultiLine"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateFieldHeaderText="Gender">
<ItemTemplate>
<asp:RadioButtonList ID="RBLGender" 
runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="M">Male</asp:ListItem>
<asp:ListItem Value="F">Female</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateFieldHeaderText="Qualification">
<ItemTemplate>
<asp:DropDownList ID="drpQualification" runat="server">
<asp:ListItem Value="G">Graduate</asp:ListItem>
<asp:ListItem Value="P">Post Graduate</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyleHorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" 
                        Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandFieldShowDeleteButton="True" />
</Columns>
<FooterStyleBackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyleBackColor="#EFF3FB" />
<EditRowStyleBackColor="#2461BF" />
<SelectedRowStyleBackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyleBackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyleBackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyleBackColor="White" />
</asp:GridView>

From the above coding, we have dynamically changed data source of this GridView. By doing this, we will have a single row as default and whenever the user wants to add a new row, it will get added in the GridView.

Listing 2: Shows the code have a default single row

private void FirstGridViewRow()
{
DataTabledt = new DataTable();
DataRowdr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
dt.Columns.Add(new DataColumn("Col3", typeof(string)));
dt.Columns.Add(new DataColumn("Col4", typeof(string)));
dt.Columns.Add(new DataColumn("Col5", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Col1"] = string.Empty;
dr["Col2"] = string.Empty;
dr["Col3"] = string.Empty;
dr["Col4"] = string.Empty;
dr["Col5"] = string.Empty;
dt.Rows.Add(dr);

ViewState["CurrentTable"] = dt;

grvStudentDetails.DataSource = dt;
grvStudentDetails.DataBind();
}

In the above coding, the view state has been kept to facilitate the dynamic addition and deletion of rows functionality because we need to preserve the data of rows other than row being added or deleted we need some place to keep this data. Now for adding a new row, the user has to do two things. They are as follows:

  1. Firstly, we need to add row in the grid.
  2. Secondly, we need to set the data entered in the already added rows.

Listing 3: Shows the code for adding a new row

private void AddNewRow()
{
introwIndex = 0;

    if (ViewState["CurrentTable"] != null)
    {
DataTabledtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRowdrCurrentRow = null;
        if (dtCurrentTable.Rows.Count> 0)
        {
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
TextBoxTextBoxName = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
TextBoxTextBoxAge = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
TextBoxTextBoxAddress = 
                  (TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
RadioButtonListRBLGender = 
                  (RadioButtonList)grvStudentDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
DropDownListDrpQualification = 
                  (DropDownList)grvStudentDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;

dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxAge.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxAddress.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = RBLGender.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col5"] = DrpQualification.SelectedValue;
rowIndex++;
            }
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;

grvStudentDetails.DataSource = dtCurrentTable;
grvStudentDetails.DataBind();
        }
    }
    else
    {
Response.Write("ViewState is null");
    }
SetPreviousData();
}

Listing 4: Shows the code to set the previously entered data

private void SetPreviousData()
{
introwIndex = 0;
    if (ViewState["CurrentTable"] != null)
    {
DataTabledt = (DataTable)ViewState["CurrentTable"];
        if (dt.Rows.Count> 0)
        {
            for (int i = 0; i <dt.Rows.Count; i++)
            {
TextBoxTextBoxName = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
TextBoxTextBoxAge = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
TextBoxTextBoxAddress = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
RadioButtonListRBLGender = (RadioButtonList)grvStudentDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
DropDownListDrpQualification = (DropDownList)grvStudentDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");

TextBoxName.Text = dt.Rows[i]["Col1"].ToString();
TextBoxAge.Text = dt.Rows[i]["Col2"].ToString();
TextBoxAddress.Text = dt.Rows[i]["Col3"].ToString();
RBLGender.SelectedValue = dt.Rows[i]["Col4"].ToString();
DrpQualification.SelectedValue = dt.Rows[i]["Col5"].ToString();
rowIndex++;
            }
        }
    }
}

The same things need to be done when it comes to delete the rows.

Listing 5: Shows the code to delete the rows

protected void grvStudentDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
    if (ViewState["CurrentTable"] != null)
    {
DataTabledt = (DataTable)ViewState["CurrentTable"];
DataRowdrCurrentRow = null;
introwIndex = Convert.ToInt32(e.RowIndex);
        if (dt.Rows.Count> 1)
        {   
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;                 
grvStudentDetails.DataSource = dt;
grvStudentDetails.DataBind();

            for (int i = 0; i <grvStudentDetails.Rows.Count - 1; i++)
            {
grvStudentDetails.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
            }
SetPreviousData();
        }
    }
}

Listing 6: Shows the code for resetting the data in other rows

private void SetRowData()
{
introwIndex = 0;

    if (ViewState["CurrentTable"] != null)
    {
DataTabledtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRowdrCurrentRow = null;
        if (dtCurrentTable.Rows.Count> 0)
        {
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
TextBoxTextBoxName = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
TextBoxTextBoxAge = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
TextBoxTextBoxAddress = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
RadioButtonListRBLGender = (RadioButtonList)grvStudentDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
DropDownListDrpQualification = (DropDownList)grvStudentDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxAge.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxAddress.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = RBLGender.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col5"] = DrpQualification.SelectedValue;
rowIndex++;
            }

ViewState["CurrentTable"] = dtCurrentTable;
           //grvStudentDetails.DataSource = dtCurrentTable;
            //grvStudentDetails.DataBind();
        }
    }
    else
    {
Response.Write("ViewState is null");
    }
    //SetPreviousData();
}

Conclusion

In this way, we can add and delete the rows in ASP .NET GridView by following the above coding in a easy and effective manner!



I am well versed with Computer Programming languages and possess good working knowledge on software languages such as C, Java, PHP, HTML and CSS

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login