What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 15107 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > How to insert record using GridView

How to insert record using GridView

3 vote(s)
Rating: 5 out of 5
Article posted by SheoNarayan on 11/9/2008 | Views: 153922 | Category: ASP.NET | Level: Intermediate red flag


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.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

 Responses
Posted by: Getahamed | Posted on: 23 Jul 2010 07:58:17 AM

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 | Posted on: 23 Jul 2010 09:32:29 PM

@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 | Posted on: 17 Aug 2010 01:56:26 AM | 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 | Posted on: 09 Dec 2010 02:53:25 PM | 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 | Posted on: 09 Dec 2010 06:49:09 PM | 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 | Posted on: 10 Dec 2010 03:54:06 PM | 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 | Posted on: 11 Dec 2010 12:35:28 AM | 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 | Posted on: 12 Dec 2010 10:24:27 PM | 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 | Posted on: 05 Feb 2012 03:12:32 AM | 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...


>> Write Response - Respond to this post and get points
Related Posts

3-Tier architecture is a very well know buzz word in the world of software development whether it web based or desktop based. In this article I am going to show how to design a web application based on 3-tier architecture.

Following is the table containing entities or characters used for referencing in HTML, XSLT, and XML as a complete reference.

Many times we want certain set of validation to fire for some user and certain set of validation to fire for some other user. In the section we will see how we can achieve the same using Microsoft enterprise validation blocks.

Form Authentication in web.config file

After studying a lot on Adrotator control, I came to this point, and tried my best to give my knowledge on this control to my readers. I hope u all will like this article of mine.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/22/2013 12:37:41 PM