DevPinoy.org
A Filipino Developers Community
   
How To: Create dynamic input rows in a GridView with ASP.NET

 

Sorry for not being able to post anything interesting the past few months. Anyway, I saw this old thread at DevPinoy.org the other day and I realized that nobody has posted a complete sample solution that would solve and show how to accomplish dynamic input rows in a GridView. I was thinking of replying to it a few months back but i guess work caught up at me and I wasn't able to do so. I found some free time last week and decided to build an app to demonstrate how to solve this question.

Ok, lets start by analyzing the question:

Hi guys,

I have a problem here. How can i create a dynamic row in gridview the row will defend from the user input. For example the user enter a 4 then the gridview will generate 4 rows. Please site me an example.

Thanks,
D_Conqueror

From what I understood the user wants to be able to create dynamically rows of data in the GridView depending on the number he enters on a Textbox. We can accomplish this by creating a datasource with the same number of rows as the user specified and binding it to our GridView.

To demonstrate how to solve this problem i decided to create this sample.

To start off with our tiny project we need to create a page that would ask the user for the number of rows he wan'ts to display on the GridView. The page will contain a TextBox for input and a LinkButton that we will use for submitting the value to a seperate page. Below is the HTML code for our first page (Default.aspx):

dynamiggridview01.jpg

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dynamic GridView Input Rows</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width:330px;">
        Number of rows to create:&nbsp; 
        <asp:TextBox ID="numberOfRowsTextBox" runat="server"></asp:TextBox>
        <div style="text-align:right;">
            <asp:LinkButton ID="submitLinkButton" runat="server" 
                onclick="submitLinkButton_Click">Submit</asp:LinkButton>
        </div>
    </div>
    </form>
</body>
</html>

and below is the code listing for Default.aspx

using System;

public partial class _Default : System.Web.UI.Page 
{
    protected void submitLinkButton_Click(object sender, EventArgs e)
    {
        Response.Redirect(String.Format(
                            "DynamicGridViewPage.aspx?rows={0}"
                            , numberOfRowsTextBox.Text));
    }
}

As you can see, all we are doing is passing the value of our TextBox as a query string parameter to our second page. The true juice of our solution is on the next page. But before we go into detail to that we need to setup first what type of values needs to be shown on the page. For this example i've decided to display a simple Person class that has for fields. An ID, a Firstname, a Lastname, and a boolean field called IsChristian. Below is the code for our Person class:

using System;

/// <summary>
/// Summary description for Person
/// </summary>
public class Person : IPerson
{
    private int _ID;
    private string _firstname;
    private string _lastname;
    private bool _isChristian;

    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }

    public string Firstname 
    {
        get { return _firstname; }
        set { _firstname = value; }
    }

    public string Lastname
    {
        get { return _lastname; }
        set { _lastname = value; }
    }

    public bool IsChristian
    {
        get { return _isChristian; }
        set { _isChristian = value; }
    }

    public Person()    {}

    public override string ToString()
    {
        string returnValue = @"ID: " + this.ID.ToString() + "<br />"
                            + "Firstname: " + this.Firstname + "<br />"
                            + "Lastname: " + this.Lastname + "<br />"
                            + "Is Christian: " + this.IsChristian.ToString();
        
        return returnValue;
    }
}

I also created a class Persons that is a generic list of type Person. In that class I created a contructor that accepts a integer value that we will use to create the dummy list of person. The code for our Persons class is listed below:

using System;
using System.Collections.Generic;

/// <summary>
/// Summary description for Persons
/// </summary>
public class Persons: List<Person>
{
    public Persons() {}

    public Persons(int rowCount) {
        this.Clear();
        for (int i = 1; i <= rowCount; i++)
        {
            Person p = new Person();
            p.ID = i;
            this.Add(p);
        }
    }
}

Now on our second page, DynamicGridViewPage.aspx, I decided to place 4 controls. A GridView that would contain our input boxes, a label to display messages, a button to submit the fields and another GridView to show the submit values. I've added these few quirks on the page to demonstrate how you can retrieve entered values in a GridView. Below is the HTML listing for the DynamicGridViewPage.aspx.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="dynamicGridView" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="ID">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="idLabel" 
                            runat="server" 
                            Text='<%# Bind("ID") %>'>
                        </asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Firstname">
                    <ItemTemplate>
                        <asp:TextBox ID="firstnameTextBox" 
                            runat="server">
                        </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Lastname">
                    <ItemTemplate>
                        <asp:TextBox ID="lastnameTextBox" 
                            runat="server">
                        </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Christian">
                    <ItemTemplate>
                        <asp:CheckBox ID="isChristianCheckBox" 
                            runat="server" 
                            Enabled="true" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:LinkButton ID="submitLinkButton" runat="server" 
            onclick="submitLinkButton_Click">Submit</asp:LinkButton>
        <br />
        <br />
        <asp:Label ID="messageLabel" runat="server"></asp:Label>
        <asp:GridView ID="submitedRecordsGridView"
            runat="server">
            <EmptyDataTemplate>
                <b>No record submitted!</b>
            </EmptyDataTemplate>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

One of the things that you would quickly realize on our page is that the only thing I'm binding to our GridView is the ID property. The reason is because we don't really need to bind all the fields to our GridView because we are just creating rows. Next, lets look at the code behind for our page.

using System;
using System.Web.UI.WebControls;
using System.Text;

public partial class DynamicGridViewPage : System.Web.UI.Page
{
    public int RowCount
    {
        get
        {
            int returnValue = 0;

            if (Request.QueryString["rows"] != null)
            {
                try
                {
                    int.TryParse(Request.QueryString["rows"].ToString()
                                , out returnValue);
                }
                catch{
                    messageLabel.Text = @"Invalid row count! 
                                        Go back to the <a href="" temp_href=""Default.aspx"">home page</a> 
                                        to enter a value!";
                }
            }

            return returnValue;
        }
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Persons listOfPersons = new Persons(RowCount);

            dynamicGridView.DataSource = listOfPersons;
            dynamicGridView.DataBind();
        }
    }
    protected void submitLinkButton_Click(object sender, EventArgs e)
    {
        Persons listOfPerson = new Persons();
        StringBuilder messageBuilder = new StringBuilder();

        foreach (GridViewRow gr in dynamicGridView.Rows)
        {
            if (gr.RowType == DataControlRowType.DataRow)
            {
                Person p = new Person();

                if (gr.FindControl("idLabel") != null)
                {
                    p.ID = int.Parse((gr.FindControl("idLabel") as Label).Text);
                }

                if (gr.FindControl("firstnameTextBox") != null)
                {
                    p.Firstname = (gr.FindControl("firstnameTextBox") as TextBox).Text;
                }

                if (gr.FindControl("lastnameTextBox") != null)
                {
                    p.Lastname = (gr.FindControl("lastnameTextBox") as TextBox).Text;
                }

                if (gr.FindControl("isChristianCheckBox") != null)
                {
                    p.IsChristian = (gr.FindControl("isChristianCheckBox") as CheckBox).Checked;
                }

                if (!p.Firstname.Equals(String.Empty) 
                    && !p.Lastname.Equals(String.Empty))
                {
                    listOfPerson.Add(p);
                }
                else
                {
                    messageBuilder.Append(String.Format(
                                            @"Record on line number {0} 
                                              was not submitted because 
                                              it doesn''t have a 
                                              Firstname or Lastname!<br />"
                                            , p.ID));
                }
            }
        }

        if (messageBuilder.Length > 0)
        {
            messageLabel.Text = messageBuilder.ToString();
        }
        else
        {
            messageLabel.Text = String.Empty;
        }

        submitedRecordsGridView.DataSource = listOfPerson;
        submitedRecordsGridView.DataBind();
    }
}

What happens on the code-behind is pretty simple. When the page loads it checks to see if it is not a PostBack, if it's not then it tries to retrieve the rows to create using the RowCount property. Once retrieved, that value is then passed to the contructor of the Persons class to create a dummy list of items that would then be assigned to the DataSource property of our GridView.

dynamiggridview02.jpg

dynamiggridview03.jpg

I've added code to the submit button to simulate submissions to show how you can retrieve the values entered on our GridView.

dynamiggridview04.jpg

And that's it. Thats how you create a dynamic rows in a GridView and access the values. I hope i was to shed light on this issue. Thanks!

Want the source code? Download it here: KeithRull.DynamicGridViewRows.v2.zip (6.37 KB)


Posted 07-28-2008 1:15 PM by keithrull

Comments

lamia wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 07-28-2008 7:21 PM

Create a blog from unanswered posts. Very good idea and very interesting keith! :)

kumar wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 08-18-2008 7:22 PM

 how  to create a textbox in grid view  dynamically. . where the  headers of the  grid view  are dynamic, below the   grid view i need  to cretae a textbox dynamiclly,  . not at the  design time

keithrull wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 08-19-2008 9:36 AM

Just specify the AutoGenerate option of the GridView to true. Then add an edit button to the column and that should do the trick.

darry wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 08-26-2008 4:45 PM

HDohWp ligh29d9F4CsjK0A

Parrot wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 10-14-2008 12:12 AM

Nice Example keithrull ,

if we are adding Drop Down List in row then How can we get the selected row index value of GridView onSelectedIndexChanged event of that Drop Down List .

keithrull wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 10-14-2008 10:52 AM

You can get the selected row index inside the submitLinkButton_Click and just add an IF statement for your dropdownlist.

Thanks,

keith

Anvie wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 10-20-2008 10:38 AM

I been searching for ages na po on how to build gridview dynamically using vb codes. I hope somebody can help me. thank!

as of now po ito lang merun ako but I know I am missing someting. if I can just make this work I can out this on the loop.

       Dim DataGridColumn As New BoundField

       Dim Col As DataControlField = DataGridColumn

       DataGridColumn.DataField = "FieldName"

       DataGridColumn.HeaderText = "HeaderName"

       GrdTradeBreak.Columns.Add(Col)

       GrdTradeBreak.Rows(1).Cells(1).Text = "Test Value"

keithrull wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 10-20-2008 4:24 PM
query wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 11-08-2008 6:07 AM

its really interesting idea to add dynamically rows in gridnview

zakizakaria69 wrote re: How To: Create dynamic input rows in a GridView with ASP.NET
on 11-28-2010 1:00 AM

Very good and xcellent solutions. This technique is very useful to many situations.

Congratulations- 5 stars

Copyright DevPinoy 2005-2008