.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh
Melody Anderson
Eminent IT

Home >> Forum >> ASP.Net >> Post New QuestionBookmark and Share Subscribe to Forum

How to add control dynamically in Gridview

Posted By: Ramesh     Posted Date: April 20, 2011    Points:5   Category :ASP.Net

How to add control dynamically in Gridview in asp.net. I want to add Textbox and CheckBox controls programmatically inside Gridview when user click on add new row button.


Author: shankey             
Posted Date: April 21, 2011     Points: 20   

To achieve this we normally use templates.

==>ItemTemplate to display values
==>EditItemTemplate to edit values
==>FooterTemplate/InsertItemTemplate to insert values

Suppose the three fields in the GridView are Employee Name, Gender and Country.

(For ItemTemplates, labels are used to display data in non edit mode as per convention.)

<asp:Label ID="EmployeeName" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="FooterEmployeeName" runat="server">
<asp:Label ID="EmployeeGender" runat="server" Text="Label"></asp:Label>
<asp:DropDownList ID="FooterEmployeeGender" runat="server">
<asp:Label ID="EmployeeCountry" runat="server" Text="Label"></asp:Label>
<asp:DropDownList ID="FooterEmployeeCountry" runat="server">

Steps for Adding a New Row at a Button Click

1. Place a "Add New Row" button outside the gridview.(id="btnAddNewRow" Text="Add New Row")

2. Place a Insert Button(id="btnInsert" Text="Insert") and Cancel Button(id="btnCancel" Text="Cancel") next to btnAddNewRow.

3. Set Visible = "false" for Insert Button and Cancel button

4. Create a function SetVisibilities()

private void SetVisibilities(bool isVisible)
btnAddNewRow.Visible = !isVisible;
GridView1.FooterRow.Visible = isVisible;
btnInsert.Visible = isVisible;
btnCancel.Visible = isVisible;

5. Inside the Add New Row Buttons(btnAddNewRow) OnClick event

string EmployeerName = ((TextBox)gvwUsers.FooterRow.FindControl("FooterEmployeeName")).Text;
string EmployeeSex = ((DropDownList)gvwUsers.FooterRow.FindControl("FooterEmployeeSex")).SelectedItem.Text;
string EmployeeCountry = ((DropDownList)gvwUsers.FooterRow.FindControl("FooterEmployeeCountry")).SelectedItem.Text;

// now write ur code to insert the data to database
//after that rebind the GridView


Hope this helps!



Post Reply

You must Sign In To post reply
Find more Forum Questions on C#, ASP.Net, Vb.Net, SQL Server and more Here
Quick Links For Forum Categories:
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  OOPs  SilverlightIISJQuery

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend