How to Add Row in Gridview Dynamically in Asp.Net

Description:-

This article talks about a small project that presents the idea of having a GridView which facilitates the add rows dynamically at run time. In this article, I'm going to wrap up everything into one for easy reference. The following are the main features that you will see: 
  • Adding rows of TextBox, DropDownlist, Radio button and Checkbox.
  • Retain TextBox values and DropDownlist selected values across postback
  • Ability to remove rows
  • Save all values at once 
To get started fire up Visual Studio and then add a new Web Form page. Add a GridView control to the page. Here's the GridView HTML markup:

Html Markup:-

<div>
  <asp:GridView ID="Gridview1" runat="server" ShowFooter="True"
  AutoGenerateColumns="False" BackColor="White" BorderColor="#999999"
  BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black"
  GridLines="Vertical">
  <AlternatingRowStyle BackColor="#CCCCCC" />
  <Columns>
    <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
      <asp:TemplateField HeaderText="First Name">
        <ItemTemplate>
          <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="Last Name">
        <ItemTemplate>
          <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="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:TemplateField HeaderText="Status">
        <ItemTemplate>
          <asp:CheckBoxList ID="Status" runat="server" RepeatDirection="Horizontal">
            <asp:ListItem>Single</asp:ListItem>
            <asp:ListItem>Married</asp:ListItem>
          </asp:CheckBoxList>
        </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="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>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="Grade">
        <ItemTemplate>
          <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        </ItemTemplate>
        <FooterStyle HorizontalAlign="Right" />
        <FooterTemplate>
          <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
        </FooterTemplate>
      </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#CCCCCC" />
    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#F1F1F1" />
    <SortedAscendingHeaderStyle BackColor="#808080" />
    <SortedDescendingCellStyle BackColor="#CAC9C9" />
    <SortedDescendingHeaderStyle BackColor="#383838" />
  </asp:GridView>
</div>

Code behind:-

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    SetInitialRow();
  }
}

private void SetInitialRow()
{
  DataTable dt = new DataTable();
  DataRow dr = null;
  dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
  dt.Columns.Add(new DataColumn("Column1", typeof(string)));
  dt.Columns.Add(new DataColumn("Column2", typeof(string)));
  dt.Columns.Add(new DataColumn("Column3", typeof(string)));
  dt.Columns.Add(new DataColumn("Column4", typeof(string)));
  dt.Columns.Add(new DataColumn("Column5", typeof(string)));
  dt.Columns.Add(new DataColumn("Column6", typeof(string)));

  dr = dt.NewRow();
  dr["RowNumber"] = 1;
  dr["Column1"] = string.Empty;
  dr["Column2"] = string.Empty;
  dr["Column3"] = string.Empty;
  dr["Column4"] = string.Empty;
  dr["Column5"] = string.Empty;
  dr["Column6"] = string.Empty;

  dt.Rows.Add(dr);
  //dr = dt.NewRow();
  //Store the DataTable in ViewState
  ViewState["CurrentTable"] = dt;
  Gridview1.DataSource = dt;
  Gridview1.DataBind();
}

private void AddNewRowToGrid()
{
  int rowIndex = 0;
  if (ViewState["CurrentTable"] != null)
  {
    DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
    DataRow drCurrentRow = null;
    if (dtCurrentTable.Rows.Count > 0)
    {
      for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
      {
        //extract the TextBox values
        TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
        TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
        TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
        RadioButtonList box4 = (RadioButtonList)Gridview1.Rows[rowIndex].Cells[3].FindControl("RBLGender");
        DropDownList box5 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("drpQualification");
        CheckBoxList box6 = (CheckBoxList)Gridview1.Rows[rowIndex].Cells[6].FindControl("Status");
        drCurrentRow = dtCurrentTable.NewRow();
        drCurrentRow["RowNumber"] = i + 1;
        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
        dtCurrentTable.Rows[i - 1]["Column4"] = box4.SelectedValue;
        dtCurrentTable.Rows[i - 1]["Column5"] = box5.SelectedValue;
        dtCurrentTable.Rows[i - 1]["Column6"] = box6.SelectedValue;
        rowIndex++;
      }
      dtCurrentTable.Rows.Add(drCurrentRow);
      ViewState["CurrentTable"] = dtCurrentTable;
      Gridview1.DataSource = dtCurrentTable;
      Gridview1.DataBind();
    }
  }
  else
  {
    Response.Write("ViewState is null");
  }
  //Set Previous Data on Postbacks
  SetPreviousData();
}

private void SetPreviousData()
{
  int rowIndex = 0;
  if (ViewState["CurrentTable"] != null)
  {
    DataTable dt = (DataTable)ViewState["CurrentTable"];
    if (dt.Rows.Count > 0)
    {
      for (int i = 0; i < dt.Rows.Count; i++)
      {
        TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
        TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
        TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
        RadioButtonList box4 = (RadioButtonList)Gridview1.Rows[rowIndex].Cells[4].FindControl("RBLGender");
        DropDownList box5 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("drpQualification");
        CheckBoxList box6 = (CheckBoxList)Gridview1.Rows[rowIndex].Cells[6].FindControl("Status");
        box1.Text = dt.Rows[i]["Column1"].ToString();
        box2.Text = dt.Rows[i]["Column2"].ToString();
        box3.Text = dt.Rows[i]["Column3"].ToString();
        box4.SelectedValue = dt.Rows[i]["Column4"].ToString();
        box5.SelectedValue = dt.Rows[i]["Column5"].ToString();
        box6.SelectedValue = dt.Rows[i]["Column6"].ToString();
        rowIndex++;
      }
    }
  }
}

protected void ButtonAdd_Click(object sender, EventArgs e)
{
  AddNewRowToGrid();
}

Now run your Web Application and Add value click on AddNewRow button to generate new row with previous Row Maintain Data. 


Related Posts

Previous
Next Post »

Thanks for comments.....