SlideShare a Scribd company logo
Add row in asp.net Gridview on button click using C# and vb.net
In this article I am going to explain how to add a row in gridview to insert the record into
database on add new button click in asp.net.
In the previous article I have explained how to avoid (prevent) duplicate record insert on
page refresh in asp.net , how to auto generate and display Serial number (row number) in
asp.net gridview and how to check uncheck OR select/deselect checkboxes in asp.net
gridview control using Jquery.
Description:
We have 2 ways to implement this functionality. 1st
one to add new row to Gridview dynamically
(code behind). Toimplementthisrefertothislink how toaddmultiple rowstoGridview control
dynamicallyinasp.net.2nd
isuse the Gridview FooterTemplate.Putall the required control infooter
template andenable the footertemplate onbuttonclick.
Implementation:
HTML Markup:
<asp:Button ID="btnaddrow" runat="server" Text="Add New Record" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowPaging="True" DataKeyNames="Id"
CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Movie Name">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtname" runat="server" Text='<%# Eval("Name")
%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtname" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Enter Movie Name"
ControlToValidate="txtname"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Genre">
<ItemTemplate>
<%# Eval("Genre") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtgenre" runat="server" Text='<%# Eval("Genre")
%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtgenre" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="Enter Genre"
ControlToValidate="txtgenre"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Budget">
<ItemTemplate>
<%# Eval("Budget") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtbudget" runat="server" Text='<%# Eval("Budget")
%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtbudget" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ErrorMessage="Enter Budget"
ControlToValidate="txtbudget"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="Edit"
CausesValidation="false"/><asp:Button ID="btndelete" runat="server" Text="Delete"
CommandName="Delete" CausesValidation="false" CssClass="btn"/>
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btnupdate" runat="server" Text="Update"
CommandName="Update" CausesValidation="false"/><asp:Button ID="btncancel"
runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="false"
CssClass="btn" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btninsert" runat="server" Text="Insert Record"
CommandName="Insert" />
</FooterTemplate>
<ItemStyle VerticalAlign="Top" />
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True"
ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
Add the namespace
C# code:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.net code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Bind data to Gridview
Create a function to fetch the record from database and bind to Gridview and call the
function on page laod.
C# code:
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
public void BindGridview()
{
try
{
SqlDataAdapter adp = new SqlDataAdapter("Select * from Tb_Movie", con);
DataTable dt = new DataTable();
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
VB.net code:
Dim con As New
SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
Public Sub BindGridview()
Try
Dim adp As New SqlDataAdapter("Select * from Tb_Movie", con)
Dim dt As New DataTable()
adp.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
Catch ex As Exception
End Try
End Sub
Enable the Gridview Footer
On add new record button click write the below given to show the FooterTemplate of
gridview.
C# code:
protected void btnaddrow_Click(object sender, EventArgs e)
{
GridView1.ShowFooter = true;
BindGridview();
}
VB.net code:
Protected Sub btnaddrow_Click(sender As Object, e As System.EventArgs) Handles
btnaddrow.Click
GridView1.ShowFooter = True
BindGridview()
End Sub
Ad

More Related Content

What's hot (20)

jQuery
jQueryjQuery
jQuery
Jay Poojara
 
div tag.pdf
div tag.pdfdiv tag.pdf
div tag.pdf
Kongu Engineering College, Perundurai, Erode
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
Data Binding
Data BindingData Binding
Data Binding
LAY Leangsros
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
Eliran Eliassy
 
CSS
CSSCSS
CSS
seedinteractive
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
Html Form Controls
Html Form ControlsHtml Form Controls
Html Form Controls
Bosco Technical Training Society, Don Bosco Technical School (Aff. GGSIP University, New Delhi)
 
Html5 and-css3-overview
Html5 and-css3-overviewHtml5 and-css3-overview
Html5 and-css3-overview
Jacob Nelson
 
Html coding
Html codingHtml coding
Html coding
Briana VanBuskirk
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
Mindy McAdams
 
CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout
Rachel Andrew
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
Jalpesh Vasa
 
Basic-CSS-tutorial
Basic-CSS-tutorialBasic-CSS-tutorial
Basic-CSS-tutorial
tutorialsruby
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
baabtra.com - No. 1 supplier of quality freshers
 
Java script
Java scriptJava script
Java script
Shyam Khant
 
Html ppt
Html pptHtml ppt
Html ppt
Ruchi Kumari
 

Similar to Add row in asp.net Gridview on button click using C# and vb.net (20)

Detail view in distributed technologies
Detail view in distributed technologiesDetail view in distributed technologies
Detail view in distributed technologies
jamessakila
 
Cis 407 i lab 5 of 7
Cis 407 i lab 5 of 7Cis 407 i lab 5 of 7
Cis 407 i lab 5 of 7
helpido9
 
Ôn tập KTTMDT
Ôn tập KTTMDTÔn tập KTTMDT
Ôn tập KTTMDT
mrcoffee282
 
RichFaces: more concepts and features
RichFaces: more concepts and featuresRichFaces: more concepts and features
RichFaces: more concepts and features
Max Katz
 
2. A parking garage charges a $2.00 minimum fee to park for up to thr.docx
 2. A parking garage charges a $2.00 minimum fee to park for up to thr.docx 2. A parking garage charges a $2.00 minimum fee to park for up to thr.docx
2. A parking garage charges a $2.00 minimum fee to park for up to thr.docx
ajoy21
 
SynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically developmentSynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically development
Synapseindiappsdevelopment
 
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the WireUn-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
Andreas Nedbal
 
Documentation For Tab Setup
Documentation For Tab SetupDocumentation For Tab Setup
Documentation For Tab Setup
vkeeton
 
Advanced dot net
Advanced dot netAdvanced dot net
Advanced dot net
ssa2010
 
Dat402
Dat402Dat402
Dat402
ssa2010
 
The Ring programming language version 1.6 book - Part 47 of 189
The Ring programming language version 1.6 book - Part 47 of 189The Ring programming language version 1.6 book - Part 47 of 189
The Ring programming language version 1.6 book - Part 47 of 189
Mahmoud Samir Fayed
 
Cis 407 i lab 4 of 7
Cis 407 i lab 4 of 7Cis 407 i lab 4 of 7
Cis 407 i lab 4 of 7
helpido9
 
The Ring programming language version 1.2 book - Part 33 of 84
The Ring programming language version 1.2 book - Part 33 of 84The Ring programming language version 1.2 book - Part 33 of 84
The Ring programming language version 1.2 book - Part 33 of 84
Mahmoud Samir Fayed
 
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
masahiroookubo
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular U
Joonas Lehtinen
 
Implement a Javascript application that allows the user to enter strin.docx
Implement a Javascript application that allows the user to enter strin.docxImplement a Javascript application that allows the user to enter strin.docx
Implement a Javascript application that allows the user to enter strin.docx
mckerliejonelle
 
ASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server Database
Christopher Singleton
 
Tutorial asp.net
Tutorial  asp.netTutorial  asp.net
Tutorial asp.net
Vivek K. Singh
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
Knoldus Inc.
 
Detail view in distributed technologies
Detail view in distributed technologiesDetail view in distributed technologies
Detail view in distributed technologies
jamessakila
 
Cis 407 i lab 5 of 7
Cis 407 i lab 5 of 7Cis 407 i lab 5 of 7
Cis 407 i lab 5 of 7
helpido9
 
Ôn tập KTTMDT
Ôn tập KTTMDTÔn tập KTTMDT
Ôn tập KTTMDT
mrcoffee282
 
RichFaces: more concepts and features
RichFaces: more concepts and featuresRichFaces: more concepts and features
RichFaces: more concepts and features
Max Katz
 
2. A parking garage charges a $2.00 minimum fee to park for up to thr.docx
 2. A parking garage charges a $2.00 minimum fee to park for up to thr.docx 2. A parking garage charges a $2.00 minimum fee to park for up to thr.docx
2. A parking garage charges a $2.00 minimum fee to park for up to thr.docx
ajoy21
 
SynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically developmentSynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically development
Synapseindiappsdevelopment
 
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the WireUn-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
Andreas Nedbal
 
Documentation For Tab Setup
Documentation For Tab SetupDocumentation For Tab Setup
Documentation For Tab Setup
vkeeton
 
Advanced dot net
Advanced dot netAdvanced dot net
Advanced dot net
ssa2010
 
The Ring programming language version 1.6 book - Part 47 of 189
The Ring programming language version 1.6 book - Part 47 of 189The Ring programming language version 1.6 book - Part 47 of 189
The Ring programming language version 1.6 book - Part 47 of 189
Mahmoud Samir Fayed
 
Cis 407 i lab 4 of 7
Cis 407 i lab 4 of 7Cis 407 i lab 4 of 7
Cis 407 i lab 4 of 7
helpido9
 
The Ring programming language version 1.2 book - Part 33 of 84
The Ring programming language version 1.2 book - Part 33 of 84The Ring programming language version 1.2 book - Part 33 of 84
The Ring programming language version 1.2 book - Part 33 of 84
Mahmoud Samir Fayed
 
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
masahiroookubo
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular U
Joonas Lehtinen
 
Implement a Javascript application that allows the user to enter strin.docx
Implement a Javascript application that allows the user to enter strin.docxImplement a Javascript application that allows the user to enter strin.docx
Implement a Javascript application that allows the user to enter strin.docx
mckerliejonelle
 
ASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server Database
Christopher Singleton
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
Knoldus Inc.
 
Ad

Recently uploaded (20)

UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Unlocking the Power of IVR: A Comprehensive Guide
Unlocking the Power of IVR: A Comprehensive GuideUnlocking the Power of IVR: A Comprehensive Guide
Unlocking the Power of IVR: A Comprehensive Guide
vikasascentbpo
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Top 10 IT Help Desk Outsourcing Services
Top 10 IT Help Desk Outsourcing ServicesTop 10 IT Help Desk Outsourcing Services
Top 10 IT Help Desk Outsourcing Services
Infrassist Technologies Pvt. Ltd.
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Unlocking the Power of IVR: A Comprehensive Guide
Unlocking the Power of IVR: A Comprehensive GuideUnlocking the Power of IVR: A Comprehensive Guide
Unlocking the Power of IVR: A Comprehensive Guide
vikasascentbpo
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Ad

Add row in asp.net Gridview on button click using C# and vb.net

  • 1. Add row in asp.net Gridview on button click using C# and vb.net In this article I am going to explain how to add a row in gridview to insert the record into database on add new button click in asp.net. In the previous article I have explained how to avoid (prevent) duplicate record insert on page refresh in asp.net , how to auto generate and display Serial number (row number) in asp.net gridview and how to check uncheck OR select/deselect checkboxes in asp.net gridview control using Jquery. Description: We have 2 ways to implement this functionality. 1st one to add new row to Gridview dynamically (code behind). Toimplementthisrefertothislink how toaddmultiple rowstoGridview control dynamicallyinasp.net.2nd isuse the Gridview FooterTemplate.Putall the required control infooter template andenable the footertemplate onbuttonclick. Implementation: HTML Markup: <asp:Button ID="btnaddrow" runat="server" Text="Add New Record" /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True" DataKeyNames="Id" CellPadding="4" ForeColor="#333333" GridLines="None"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <Columns> <asp:TemplateField HeaderText="Movie Name"> <ItemTemplate> <%# Eval("Name") %> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtname" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtname" runat="server" /> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Enter Movie Name" ControlToValidate="txtname"></asp:RequiredFieldValidator> </FooterTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField HeaderText="Genre">
  • 2. <ItemTemplate> <%# Eval("Genre") %> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtgenre" runat="server" Text='<%# Eval("Genre") %>'></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtgenre" runat="server" /> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Enter Genre" ControlToValidate="txtgenre"></asp:RequiredFieldValidator> </FooterTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField HeaderText="Budget"> <ItemTemplate> <%# Eval("Budget") %> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtbudget" runat="server" Text='<%# Eval("Budget") %>'></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtbudget" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Budget" ControlToValidate="txtbudget"></asp:RequiredFieldValidator> </FooterTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="Edit" CausesValidation="false"/><asp:Button ID="btndelete" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false" CssClass="btn"/> </ItemTemplate> <EditItemTemplate> <asp:Button ID="btnupdate" runat="server" Text="Update" CommandName="Update" CausesValidation="false"/><asp:Button ID="btncancel" runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="false" CssClass="btn" /> </EditItemTemplate> <FooterTemplate> <asp:Button ID="btninsert" runat="server" Text="Insert Record" CommandName="Insert" />
  • 3. </FooterTemplate> <ItemStyle VerticalAlign="Top" /> </asp:TemplateField> </Columns> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#E9E7E2" /> <SortedAscendingHeaderStyle BackColor="#506C8C" /> <SortedDescendingCellStyle BackColor="#FFFDF8" /> <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> </asp:GridView> Add the namespace C# code: using System.Data; using System.Data.SqlClient; using System.Configuration; VB.net code: Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Bind data to Gridview Create a function to fetch the record from database and bind to Gridview and call the function on page laod. C# code: SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString()); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack)
  • 4. { BindGridview(); } } public void BindGridview() { try { SqlDataAdapter adp = new SqlDataAdapter("Select * from Tb_Movie", con); DataTable dt = new DataTable(); adp.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } catch (Exception ex) { } } VB.net code: Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString()) Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not IsPostBack Then BindGridview() End If End Sub Public Sub BindGridview() Try Dim adp As New SqlDataAdapter("Select * from Tb_Movie", con) Dim dt As New DataTable() adp.Fill(dt) GridView1.DataSource = dt GridView1.DataBind() Catch ex As Exception End Try End Sub Enable the Gridview Footer On add new record button click write the below given to show the FooterTemplate of gridview.
  • 5. C# code: protected void btnaddrow_Click(object sender, EventArgs e) { GridView1.ShowFooter = true; BindGridview(); } VB.net code: Protected Sub btnaddrow_Click(sender As Object, e As System.EventArgs) Handles btnaddrow.Click GridView1.ShowFooter = True BindGridview() End Sub