473,395 Members | 1,368 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,395 developers and data experts.

How to Add New Row to a Gridview Dynamically

85 64KB
in this article I will explain how you can add a row with template fields dynamically in grid view in asp.net using c#

For this you will need to write 3 functions.
Lets assume that we have a grid view in which we are going to add the subject, note, Speaker Name, Time, order, start and end of a particular event.

Here is the ASP.NET code for the GridView:
Expand|Select|Wrap|Line Numbers
  1. <asp:GridView ID="gvSpeakersAgenda" runat ="server"
  2.               AutoGenerateColumns ="false" Width ="100%"
  3.               GridLines="None" CssClass="mGrid" 
  4.               PagerStyle-CssClass="pgr"
  5.               AlternatingRowStyle-CssClass="alt"
  6.               HeaderStyle-CssClass="headercss">
  7.   <Columns>
  8.     <asp:TemplateField HeaderText ="Order">
  9.       <ItemTemplate>
  10.         <asp:TextBox ID ="txtOrder" ReadOnly ="true" runat ="server" Width ="40px"></asp:TextBox>
  11.       </ItemTemplate>
  12.     </asp:TemplateField>
  13.     <asp:TemplateField HeaderText ="Subject">
  14.       <ItemTemplate>
  15.         <asp:TextBox ID="txtSubject" Width ="145px" runat ="server" TextMode ="MultiLine"></asp:TextBox>
  16.       </ItemTemplate>
  17.     </asp:TemplateField>
  18.     <asp:TemplateField HeaderText ="Speaker">
  19.       <ItemTemplate>
  20.         <asp:DropDownList ID ="ddlSpeakers" runat="server"></asp:DropDownList>
  21.       </ItemTemplate>
  22.     </asp:TemplateField>
  23.     <asp:TemplateField HeaderText ="Time">
  24.       <ItemTemplate>
  25.         <asp:TextBox ID="txtTime" runat ="server" Width ="60px"></asp:TextBox>
  26.       </ItemTemplate>
  27.     </asp:TemplateField>
  28.     <asp:TemplateField HeaderText ="Note">
  29.       <ItemTemplate>
  30.         <asp:TextBox ID="txtNote" Width ="145px" runat ="server" TextMode ="MultiLine"></asp:TextBox>
  31.       </ItemTemplate>
  32.     </asp:TemplateField>
  33.     <asp:TemplateField HeaderText ="Start" Visible ="false">
  34.       <ItemTemplate>
  35.         <asp:TextBox ID="txtStart" runat ="server" Width ="100px" ReadOnly ="true"></asp:TextBox>
  36.       </ItemTemplate>
  37.     </asp:TemplateField>
  38.     <asp:TemplateField HeaderText ="End" Visible="false">
  39.       <ItemTemplate >
  40.         <asp:TextBox ID ="txtEnd" runat ="server" Width ="100px" ReadOnly ="true"></asp:TextBox>
  41.       </ItemTemplate>
  42.     </asp:TemplateField>
  43.   </Columns>
  44. </asp:GridView>
  45.  
We will write three functions as follows.
Expand|Select|Wrap|Line Numbers
  1. private void SetInitialRow()
  2.         {
  3.             DataTable dt = new DataTable();
  4.             DataRow dr = null;
  5.  
  6.             dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
  7.             dt.Columns.Add(new DataColumn("Subject", typeof(string)));
  8.             dt.Columns.Add(new DataColumn("Speaker", typeof(string)));
  9.             dt.Columns.Add(new DataColumn("Time", typeof(string)));
  10.             dt.Columns.Add(new DataColumn("Note", typeof(string)));
  11.             dt.Columns.Add(new DataColumn("Order", typeof(string)));
  12.             dt.Columns.Add(new DataColumn("Start", typeof(string)));
  13.             dt.Columns.Add(new DataColumn("End", typeof(string)));
  14.             dr = dt.NewRow();
  15.             dr["RowNumber"] = 1;
  16.             dr["Subject"] = string.Empty;
  17.             dr["Speaker"] = string.Empty;
  18.             dr["Time"] = string.Empty;
  19.             dr["Note"] = string.Empty;
  20.             dr["Order"] = string.Empty;
  21.             dr["Start"] = string.Empty;
  22.             dr["End"] = string.Empty;
  23.             dt.Rows.Add(dr);
  24.  
  25.  
  26.  
  27.             ViewState["CurrentTable"] = dt;
  28.  
  29.  
  30.             gvSpeakersAgenda.DataSource = dt;
  31.             gvSpeakersAgenda.DataBind();
  32.  
  33.  
  34.         }
  35.  
then write the method for adding new row like this
Expand|Select|Wrap|Line Numbers
  1. private void AddNewRowToGrid()
  2.         {
  3.  
  4.             int rowIndex = 0;
  5.  
  6.  
  7.  
  8.             if (ViewState["CurrentTable"] != null)
  9.             {
  10.  
  11.                 DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
  12.  
  13.                 DataRow drCurrentRow = null;
  14.  
  15.                 if (dtCurrentTable.Rows.Count > 0)
  16.                 {
  17.  
  18.                     for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
  19.                     {
  20.  
  21.                         //extract the TextBox values
  22.                         TextBox txtSubject = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[0].FindControl("txtSubject");
  23.                         DropDownList ddlSpeakers = (DropDownList)gvSpeakersAgenda.Rows[rowIndex].Cells[1].FindControl("ddlSpeakers");
  24.                         TextBox txtTime = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[2].FindControl("txtTime");
  25.                         TextBox txtNote = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[3].FindControl("txtNote");
  26.                         TextBox txtOrder = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[4].FindControl("txtOrder");
  27.                         TextBox txtStart = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[5].FindControl("txtStart");
  28.                         TextBox txtEnd = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[6].FindControl("txtEnd");
  29.                         drCurrentRow = dtCurrentTable.NewRow();
  30.                         drCurrentRow["Subject"] = txtSubject.Text;
  31.                         drCurrentRow["Speaker"] = ddlSpeakers.Text;
  32.                         drCurrentRow["Time"] = txtTime.Text;
  33.                         drCurrentRow["Note"] = txtNote.Text;
  34.                         // int order = Convert.ToInt32(txtOrder.Text);
  35.                         drCurrentRow["Order"] = txtOrder.Text;
  36.                         drCurrentRow["Start"] = txtStart.Text;
  37.                         drCurrentRow["End"] = txtEnd.Text;
  38.                         //drCurrentRow["Order"] = order + 1;
  39.                         rowIndex++;
  40.                         txtSubject.Focus();
  41.                         txtOrder.ReadOnly = true;
  42.                     }
  43.  
  44.                     //add new row to DataTable
  45.  
  46.                     dtCurrentTable.Rows.Add(drCurrentRow);
  47.  
  48.                     //Store the current data to ViewState
  49.  
  50.                     ViewState["CurrentTable"] = dtCurrentTable;
  51.  
  52.  
  53.  
  54.                     //Rebind the Grid with the current data
  55.                     gvSpeakersAgenda.DataSource = dtCurrentTable;
  56.                     gvSpeakersAgenda.DataBind();
  57.  
  58.                 }
  59.  
  60.             }
  61.  
  62.             else
  63.             {
  64.  
  65.                 Response.Write("ViewState is null");
  66.  
  67.             }
  68.  
  69.  
  70.  
  71.             //Set Previous Data on Postbacks
  72.  
  73.             SetPreviousData();
  74.  
  75.         }
  76.  
The method SetPreviousData() will look like this
Expand|Select|Wrap|Line Numbers
  1.  private void SetPreviousData()
  2.         {
  3.             int rowIndex = 0;
  4.             if (ViewState["CurrentTable"] != null)
  5.             {
  6.                 DataTable dt = (DataTable)ViewState["CurrentTable"];
  7.  
  8.                 if (dt.Rows.Count > 0)
  9.                 {
  10.                     for (int i = 1; i < dt.Rows.Count; i++)
  11.                     {
  12.                         TextBox txtSubject = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[0].FindControl("txtSubject");
  13.                         DropDownList ddlSpeakers = (DropDownList)gvSpeakersAgenda.Rows[rowIndex].Cells[1].FindControl("ddlSpeakers");
  14.                         TextBox txtTime = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[2].FindControl("txtTime");
  15.                         TextBox txtNote = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[3].FindControl("txtNote");
  16.                         TextBox txtOrder = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[4].FindControl("txtOrder");
  17.                         TextBox txtStart = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[5].FindControl("txtStart");
  18.                         TextBox txtEnd = (TextBox)gvSpeakersAgenda.Rows[rowIndex].Cells[6].FindControl("txtEnd");
  19.                         txtSubject.Text = dt.Rows[i]["Subject"].ToString();
  20.                         ddlSpeakers.Text = dt.Rows[i]["Speaker"].ToString();
  21.                         txtTime.Text = dt.Rows[i]["Time"].ToString();
  22.                         txtNote.Text = dt.Rows[i]["Note"].ToString();
  23.                         txtOrder.Text = dt.Rows[i]["Order"].ToString();
  24.                         txtStart.Text = dt.Rows[i]["Start"].ToString();
  25.                         txtEnd.Text = dt.Rows[i]["End"].ToString();
  26.                         txtOrder.ReadOnly = true;
  27.                         rowIndex++;
  28.                     }
  29.                 }
  30.             }
  31.         }
  32.  
Now place a button and on the click event of that button simply call the method AddNewRowToGrid()
Aug 1 '12 #1
1 41403
Frinavale
9,735 Expert Mod 8TB
If you wanted to create dynamic columns (template fields) for your GridView, you would have to create a class that implements the ITemplate interface.

Could you please post the ASP.NET markup for the GridView that you used in your article.

-Frinny
Aug 1 '12 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Brad | last post by:
I am programatically trying to add a checkBox column to a gridView. This is what I have to do it (VB): Dim cbCol As New CheckBoxField cbCol.Text = "Enter this event" gvEvents.Columns.Add(cbCol)...
0
by: yeltsin27 | last post by:
I need some advice on handling dynamically added controls in a GridView. My app takes an uploaded CSV file containing addresses, converts it to a DataTable, databinds the DataTable to a...
4
by: bryan | last post by:
Hi all, I am working on a .net 2.0 web app. On page load I display a gridview with a drop down list (Employees), when the user selects from the drop down list, the grid view is filled with...
1
by: spitapps | last post by:
I have a gridview declaratively added to my webform. This gridview displays data from a stored procedure returned as a dataset. Once the dataset has been modified slightly i bind it to my...
4
by: Mark Olbert | last post by:
I'm running into a well-described issue in the ASPNET model that I haven't found a good work around for. I have a GridView to which I dynamically add data-bound TemplateFields at run-time. The...
2
by: =?Utf-8?B?Q2FybG8gTWFyY2hlc29uaQ==?= | last post by:
I am building a GridView dynamically adding templatFields according to a Microsoft article. I had to create a class with the ITemplate interface and a method called InstantiateIn. Everything works...
0
by: rogoflap | last post by:
I have a SQLDatasource I created on a form. It is tied to the GridView on that form. I would like to dynamically change the SQLStatement based on some criteria on the form. It seems to...
3
by: giveDsolution | last post by:
Hello Frds, I have bind a gridview with the help of a Datatable as the columns are added dynamically. But my problem is i have to add a gridview in any cell (which will be bind by another Query)...
4
by: jack | last post by:
Hi, Consider the following handler: protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e) { GridViewRow row = e.Row; if (row.RowType != DataControlRowType.DataRow)...
0
by: krishnaneeraja | last post by:
Hi I want to add link labels in gridview dynamically in windows application.
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.