Generally GridView is used to show data in tabular format. It also provide ways to modify and delete records but currently there is no way to insert record using GridView. In this article, I shall describe an easy work around to insert record using GridView.
Introduction
GridView is a successor of DataGrid in ASP.NET 1.x version. This is one of the most powerful control in asp.net to work with data. For more details on GridView read http://www.dotnetfunda.com/tutorials/controls/gridview.aspx and http://www.dotnetfunda.com/articles/article29.aspx article.
How it works
Lets see how to insert record using GridView. I have taken an example of a simple database table of having UserName, Password, SuperPassword, UserType, Admin Desc and Active fields. For simplicity reason I shall not show the database manipulation code here.
The first thing we need to consider here is that if there is no record in the GridView Datasource, it should display a Form to insert records, so we shall use EmptyDataTemplate to render the Insert form. That will look similar to picture below.
GridView with No Record
When there is data in the GridView, EmptyDataTemplate form will not display. To display the insert form, we shall place a button called Add New Record either in the top or bottom of GridView. When Add New Record button will be clicked, we need to show the Insert form so we shall place respective textboxes and dropdownlist box inside the FooterTemplate and on the click event of the button we shall show the footer. The GridView will look similar to the picture below.
GridView after clicking Add New Record button
GridView Code
<
p style="text-align:right;"><asp:Button ID="btnAdd" runat="Server" Text="Add New Record" OnClick="AddNewRecord" /></p><asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False"BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"CellPadding="4" ForeColor="Black" GridLines="Vertical" SkinID="RecordList" Width="100%"OnRowCommand="GridView1_OnRowCommand1" ShowFooter="False" AutoGenerateEditButton="true" OnRowEditing="EditRecord" OnRowCancelingEdit="CancelRecord"OnRowUpdating="UpdateRecords" DataKeyNames="AutoID" EnableViewState="True"><Columns>
<asp:BoundField DataField="AutoID" HeaderText="AutoID" ReadOnly="True" /><asp:TemplateField HeaderText="UserName">
<ItemTemplate><%
# Eval("UserName") %></ItemTemplate><EditItemTemplate>
<asp:TextBox ID="txtUserName" runat="Server" Text='<%# Eval("UserName") %>'></asp:TextBox></EditItemTemplate><FooterTemplate>
<asp:TextBox ID="txtUserName" runat="Server"></asp:TextBox></FooterTemplate></asp:TemplateField><asp:TemplateField HeaderText="Password">
<ItemTemplate><%
# Eval("Password") %></ItemTemplate><EditItemTemplate>
<asp:TextBox ID="txtPassword" runat="Server" Text='<%# Eval("Password") %>'></asp:TextBox></EditItemTemplate><FooterTemplate>
<asp:TextBox ID="txtPassword" runat="Server"></asp:TextBox></FooterTemplate></asp:TemplateField><asp:TemplateField HeaderText="SuperPassword">
<ItemTemplate><%
# Eval("SuperPassword") %></ItemTemplate><EditItemTemplate>
<asp:TextBox ID="txtSuperPassword" runat="Server" Text='<%# Eval("SuperPassword") %>'></asp:TextBox></EditItemTemplate><FooterTemplate>
<asp:TextBox ID="txtSuperPassword" runat="Server"></asp:TextBox></FooterTemplate></asp:TemplateField><asp:TemplateField HeaderText="UserType">
<ItemTemplate><%
# Eval("UserType") %></ItemTemplate><EditItemTemplate>
<asp:DropDownList ID="dropType" runat="server" SelectedValue='<%# Eval("UserType").ToString() %>'><asp:ListItem Text="Admin" Value="Admin"></asp:ListItem><asp:ListItem Text="Maint" Value="Maint"></asp:ListItem></asp:DropDownList></EditItemTemplate><FooterTemplate>
<asp:DropDownList ID="dropType" runat="server"><asp:ListItem Text="Admin" Value="Admin"></asp:ListItem><asp:ListItem Text="Maint" Value="Maint"></asp:ListItem></asp:DropDownList></FooterTemplate></asp:TemplateField><asp:TemplateField HeaderText="AdminDesc">
<ItemTemplate><%
# Eval("AdminDesc") %></ItemTemplate><EditItemTemplate>
<asp:TextBox ID="txtAdminDesc" Columns="30" runat="Server" Text='<%# Eval("AdminDesc") %>'></asp:TextBox></EditItemTemplate><FooterTemplate>
<asp:TextBox ID="txtAdminDesc" runat="Server" Text='<%# Eval("AdminDesc") %>'></asp:TextBox></FooterTemplate></asp:TemplateField><asp:TemplateField HeaderText="Active">
<ItemTemplate><%
# Eval("Active") %></ItemTemplate><EditItemTemplate>
<asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active").ToString().ToLower().Equals("true") ? "True" : "False" %>'><asp:ListItem Text="Yes" Value="True"></asp:ListItem><asp:ListItem Text="No" Value="False"></asp:ListItem></asp:DropDownList></EditItemTemplate><FooterTemplate>
<asp:DropDownList ID="dropActive" runat="server"><asp:ListItem Text="Yes" Value="True"></asp:ListItem><asp:ListItem Text="No" Value="False"></asp:ListItem></asp:DropDownList> <br /><asp:Button ID="btnInsert" runat="Server" Text="Insert" CommandName="Insert" UseSubmitBehavior="False" /></FooterTemplate></asp:TemplateField></Columns><FooterStyle BackColor="#CCCC99" /><RowStyle BackColor="#F7F7DE" /><SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" /><PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" /><HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" /><AlternatingRowStyle BackColor="White" /><EmptyDataTemplate>UserName
<asp:TextBox ID="txtUserName" runat="Server"></asp:TextBox> Password <asp:TextBox ID="txtPassword" runat="Server"></asp:TextBox> SuperPassword <asp:TextBox ID="txtSuperPassword" runat="Server"></asp:TextBox> User Type
<asp:DropDownList ID="dropType" runat="server"><asp:ListItem Text="Admin" Value="Admin"></asp:ListItem><asp:ListItem Text="Maint" Value="Maint"></asp:ListItem></asp:DropDownList> Admin Desc <asp:TextBox ID="txtAdminDesc" runat="Server" /> Active <asp:DropDownList ID="dropActive" runat="server"><asp:ListItem Text="Yes" Value="True"></asp:ListItem><asp:ListItem Text="No" Value="False"></asp:ListItem></asp:DropDownList><asp:Button ID="btnInsert" runat="Server" Text="Insert" CommandName="EmptyInsert" UseSubmitBehavior="False" /></EmptyDataTemplate></asp:GridView>
Now, let me describe how it works.
When there is no record in the DataSource
When there is no record in the DataSource, we don't need to do anything to display the Insert form because we have already placed this form inside EmptyDataTemplate. GridView automatically takes care and display EmptyDataTemplate block.
When Add New Record button will be clicked
As we have kept the respective field textboxes and dropdownlist box in the footer so we need to show the footer on click event of this button. The code for the click event will be like this. (Notice that I have specified AddNewRecord method in OnClick event of the button)
///
<summary>/// Show Add new record/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void AddNewRecord(object sender, EventArgs e){
GridView1.ShowFooter =
true;BindCurrentUsers();
}
When Insert Button of the form will be clicked
When Insert button of either Insert form will be clicked, GridView1_OnRowCommand1 will fire as I have specified OnRowCommand event of the GridView as GridView1_OnRowCommand1. Again, notice that I have specified CommandName as "EmptyInsert" for the insert button inside EmptyDataTemplate and "Insert" for Footer template, so I need to check that which Insert button is being clicked before actually calling the Insert method of the business layer. Below is the code for GridView1_OnRowCommand1 method.
///
<summary>/// Insert records into datbase/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void GridView1_OnRowCommand1(object sender, GridViewCommandEventArgs e){
if (e.CommandName.Equals("EmptyInsert")){
TextBox u = GridView1.Controls[0].Controls[0].FindControl("txtUserName") as TextBox;TextBox p = GridView1.Controls[0].Controls[0].FindControl("txtPassword") as TextBox;TextBox sp = GridView1.Controls[0].Controls[0].FindControl("txtSuperPassword") as TextBox;DropDownList dT = GridView1.Controls[0].Controls[0].FindControl("dropType") as DropDownList;TextBox ad = GridView1.Controls[0].Controls[0].FindControl("txtAdminDesc") as TextBox;DropDownList dA = GridView1.Controls[0].Controls[0].FindControl("dropActive") as DropDownList;
new AdminBAL().Insert(u.Text, p.Text, sp.Text, dT.SelectedValue, ad.Text, bool.Parse(dA.SelectedValue));
lblError.Text = "<br />Record inserted successfully<br />";
BindCurrentUsers(); // rebind the dat
}
if (e.CommandName.Equals("Insert"))
{
TextBox u = GridView1.FooterRow.FindControl("txtUserName") as TextBox;
TextBox p = GridView1.FooterRow.FindControl("txtPassword") as TextBox;
TextBox sp = GridView1.FooterRow.FindControl("txtSuperPassword") as TextBox;
DropDownList dT = GridView1.FooterRow.FindControl("dropType") as DropDownList;
TextBox ad = GridView1.FooterRow.FindControl("txtAdminDesc") as TextBox;
DropDownList dA = GridView1.FooterRow.FindControl("dropActive") as DropDownList;
new AdminBAL().Insert(u.Text, p.Text, sp.Text, dT.SelectedValue, ad.Text, bool.Parse(dA.SelectedValue));
lblError.Text = "<br />Record inserted successfully<br />";
BindCurrentUsers(); // rebind the data
}
}
BindCurrentUsers() is a method in which I have bound the GridView.
///
<summary>/// Bind current users/// </summary>void BindCurrentUsers(){
AdminBAL admin = new AdminBAL();try{
GridView1.DataSource = admin.LoadAll();
GridView1.DataBind();
}
catch (Exception ee){
lblError.Text =
ThrowError.LogAndThrowError(ee);}
finally{
admin =
null;}
}
Conclusion
By using EmptyDataTemplate and FooterTemplate of GridView we can insert records into database on the same page where we are displaying records.