Search
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Fri, 31-Oct-2014 Authors
Goud.Kv
250
All Time Authors
Sourav.Kayal
39750
Sheonarayan
38050
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

How to insert record using GridView

SheoNarayan
Posted by under ASP.NET category on for Intermediate level | Views : 407022 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 5 out of 5
4 vote(s)
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.

Page copy protected against web site content infringement by Copyscape
About the Author

SheoNarayan

Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Microsoft_MVP,Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com

Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan
Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Posted by: Getahamed on: 7/23/2010

Hey... very nice article... I tried this, but i dint get the emptyDataTemplate. Can u give me the code for the above demo.

Posted by: SheoNarayan on: 7/23/2010

@Getahamed,

I would suggest to exactly follow the mentioned steps, copy-paste the code and it should work. I do not have the code available to me right now as this article was published long back.

Thank you.


Posted by: Sougandhpavithran on: 8/17/2010 | Points: 10

Hi There,

I believe there should not be any problem using validators on fields in Empty Data Template or Edit Item Template. Am i right with the assumptions.

Regards,
Sougandh

Posted by: Lps22 on: 12/9/2010 | Points: 25

Sheo Narayan,

I implemented your code and it is working fine. But despite of your implementation, I am having problems while trying to limit the numbers of characeres in a textbox defined as a TemplateField of a GridView. The maxlength property dos not functions. Is there any way to limit it?

Thanks,

LPS22

Posted by: SheoNarayan on: 12/9/2010 | Points: 25

@Sougandhpavithran: Yes, Validators should also work, simply keep it as if you are keeping in any normal form.

@Lps22: There is no reason why maxlength will not work. Try to limit the number of characters using the MaxLength attribute of TextBox, something like below.

<asp:TextBox ID="txtBoxName1" MaxLength="60" runat="server" />


Thanks!

Posted by: Lps22 on: 12/10/2010 | Points: 25

That is what I did, but it is not limiting the number of characteres typed.

<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label CssClass="Field1" Text='<%#Eval("G_CARACTERISTICA_OPCAO_S_DESCRICAO")%>' runat="server"></asp:Label>
</ItemTemplate>

<EditItemTemplate>
<asp:TextBox ID="TBDescricao" TextMode="SingleLine" MaxLength="40" Width="80px" runat="server" Text='<%#BIND("G_CARACTERISTICA_OPCAO_S_DESCRICAO")%>'></asp:TextBox>
</EditItemTemplate>

<FooterTemplate>
<asp:TextBox ID="TBDescricao" TextMode="SingleLine" MaxLength="40" Width="80px" unat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>

Posted by: SheoNarayan on: 12/11/2010 | Points: 25

In my case its working. Try to write more than 40 characters manually in the TextBox and you will not be able to write.

Thanks

Posted by: Lps22 on: 12/12/2010 | Points: 25

I found it!!!! When I do not use "width" it works fine. It seems amazing to me.
Thank you for your article and for your attention.

Posted by: Mohankind_june4 on: 2/5/2012 | Points: 25


Hay SheoNarayan Sir,

Can i get the code for AdminBAL.cs file in order to clearly understand this article??? Reply me as soon as possible...


Posted by: Ashishnanmun on: 5/23/2014 | Points: 25

Dear Sir,

please send me AdminBAL.cs file.

Posted by: Sheonarayan on: 5/23/2014 | Points: 25

Hi Ashish.....

You can see the code similar to AdminBAL in this article http://www.dotnetfunda.com/articles/show/71/3-tier-architecture-in-aspnet-with-csharp

Thanks

Posted by: Sheonarayan on: 5/23/2014 | Points: 25
Posted by: Ashishnanmun on: 5/27/2014 | Points: 25

Thanks a ton for your article.

Login to post response

Comment using Facebook(Author doesn't get notification)