GridView Binding With Dynamic table with Add and Remove Records features

Hi Guys,

Several times during development we do have to face some situations where we need to Bind GridView with Dynamic tables where you may need to add new records or delete existing records from the dynamic tables. Below is the code to do so which i wrote while developing an application.

HTML Code: Paste this code in design mode(html view)

<asp:GridView ID=”grvStudentDetails” runat=”server” ShowFooter=”True” AutoGenerateColumns=”False”
CellPadding=”4″ ForeColor=”#333333″ GridLines=”None”
OnRowDeleting=”grvStudentDetails_RowDeleting” EnableModelValidation=”True”>
<Columns>
<asp:BoundField DataField=”RowNumber” HeaderText=”SNo” />
<asp:TemplateField HeaderText=”Student Name”>
<ItemTemplate>
<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Student Age”>
<ItemTemplate>
<asp:TextBox ID=”txtAge” runat=”server”></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Student Address”>
<ItemTemplate>
<asp:TextBox ID=”txtAddress” runat=”server” Height=”55px” TextMode=”MultiLine”></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=”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>
<FooterStyle HorizontalAlign=”Right” />
<FooterTemplate>
<asp:Button ID=”ButtonAdd” runat=”server” Text=”Add New Row” OnClick=”ButtonAdd_Click” CausesValidation=”true” />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton=”True” />
</Columns>
<FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<RowStyle BackColor=”#EFF3FB” />
<EditRowStyle BackColor=”#2461BF” />
<SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />
<PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />
<HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<AlternatingRowStyle BackColor=”White” />
</asp:GridView>

CodeBehind: Write below code appropriately in code behind file.

This method will create the GUI or first row in grid view.

private void FirstGridViewRow()
{
DataTable dt = new DataTable();
DataRow dr = 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();
}

This methods will create a new record on each Add Button click event.

private void AddNewRow()
{
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++)
{
TextBox TextBoxName =
(TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl(“txtName”);
TextBox TextBoxAge =
(TextBox)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl(“txtAge”);
TextBox TextBoxAddress =
(TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl(“txtAddress”);
RadioButtonList RBLGender =
(RadioButtonList)grvStudentDetails.Rows[rowIndex].Cells[4].FindControl(“RBLGender”);
DropDownList DrpQualification =
(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();
}

This methods will hold the previous data / records in a Data Table in ViewState while post back for adding new record.

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 TextBoxName = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl(“txtName”);
TextBox TextBoxAge = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl(“txtAge”);
TextBox TextBoxAddress =
(TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl(“txtAddress”);
RadioButtonList RBLGender =
(RadioButtonList)grvStudentDetails.Rows[rowIndex].Cells[4].FindControl(“RBLGender”);
DropDownList DrpQualification =
(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++;
}
}
}
}

This methods will hold current record while inserting new row in Data Table

private void SetRowData()
{
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++)
{
TextBox TextBoxName = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl(“txtName”);
TextBox TextBoxAge = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl(“txtAge”);
TextBox TextBoxAddress = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl(“txtAddress”);
RadioButtonList RBLGender =
(RadioButtonList)grvStudentDetails.Rows[rowIndex].Cells[4].FindControl(“RBLGender”);
DropDownList DrpQualification =
(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();
}

At button click event you will have to call the AddNewRow() method to create a new record.

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

And at Page Load Event you should call the FirstGridViewRow() methods will will create an initial record for you in GUI.

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

That’s all. Hope this will help you . Thank a lot for visiting to my blog.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s