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

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

how to apply validation controls on Gridview which is created dynamically

Posted By:      Posted Date: August 31, 2010    Points: 0   Category :ASP.Net
 hi, i created a gridview with two columns and 8 rows dynamically. All the rows are empty and editable at runtime. I am giving column names for this grid from some other .aspx page by passing column names using querystring.Because i am using this grid for three different pairs of column names.  i would like to know how to apply Required Field Validator, Regular Expression Validator  and Range Validator on Gridview textboxes. So that by using those validators i want to validate user inputs. And i would also like to know how to add rows at runtime for this grid. I am using ASP.net 2.0 and C#.net for this.(Visual Studio 2005) The code i am using to create gridview is below. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="LoadData.aspx.cs" Inherits="LoadData" %>  <form id="form1" runat="server">  <div> <asp:GridView ID="GrdDynamic" runat="server" AutoGenerateColumns="False" ForeColor="#333333" BorderColor="GradientInactiveCaption" BorderStyle="Solid" style="z-index: 108; left: 24px; position: absolute; top: 13px">  <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  <RowStyle BackColor="#EFF3FB"

View Complete Post

More Related Resource Links

Strange validation behaviour on dynamically created controls


I'm trying to debug an application which generates a fixed number of questions from a database of 20 questions, and validate them on button click. On postback, I want the incorrect questions to be labeled red. However, all the questions are labeled red on postback. I'm almost positive that the problem is with "page_init" and "page_load",  I'm using session variables to keep track of the question IDs and invalid questions. Any help is appreciated.

Here is the sample code.

Protected Sub Page_Init(ByVal s As Object, ByVal e As EventArgs)
       dim i as integer
       if Not Page.IsPostBack then
           // generates a random integer array for loading the questions
       For i = 0 To 1  // I'm only loading two questions 
              //extract_question queries the database and load the controls dynamically
         end if      
       end if 
    End Sub

Protected Sub Page_Load(ByVal s As Object, ByVal e As EventArgs)
        If page.IsPostBack then
         dim textlabel as string
            dim sessionvar as string
            dim sessionc

Adding carriage returns between 2 dynamically created controls in an HtmlTableCell


The title pretty much explains it. Here is what i'm trying to do...

 Private Sub LoadGrid_CommentsField(ByVal Row As HtmlTableRow, ByVal BookingNumber As String, ByVal CommentsText As String)
  Dim Txt As TextBox
  Dim Cmd As ClickOnceButton.ClickOnceButton

  Txt = New TextBox
  Txt.ID = "txtComment_" & BookingNumber
  Txt.CssClass = "TFAppControls"
  Txt.TextMode = TextBoxMode.MultiLine
  Txt.MaxLength = 500
  Txt.Width = New Unit(95, UnitType.Percentage)
  Txt.Text = CommentsText

  Row.Cells(cComments).InnerHtml &= "<br/>"

  Cmd = New ClickOnceButton.ClickOnceButton
  Cmd.DisableAfterClick = True
  Cmd.Text = "Save Comments"
  Cmd.ID = "cmdSaveComments_" & BookingNumber
  Cmd.CssClass = "TFAppButtons"
  Cmd.EnableViewState = False
 End Sub

On the line where i try and update the InnerHtml, i get the following error; "Cannot get inner content of  because the contents are not literal."

How to I apply an XAML declared animation to multiple controls dynamically?

Hello, How to I apply an XAML declared animation to multiple controls dynamically? Here is the XAML declared animation: <Window.Resources> <Storyboard x:Key="TextBlock_SB"> <DoubleAnimation Storyboard.TargetName="TextBlock_1" Storyboard.TargetProperty="(TextBlock.Opacity)" From="1.0" To="0.75" Duration="0:0:0.5" AutoReverse="True" RepeatBehavior="Forever" /> </Storyboard> Here is the code that starts the animation for TextBlock_1: (this.Resources["TextBlock_SB"] as Storyboard).Begin(); I want to apply the same storyboard/animation to TextBlock_2 and TextBlock_3 and perhaps others.  How do I do that without defining more XAML storyboards? Regards, Robert  

Retrieve Dynamically Created Controls

I am building a webform dynamically but when I go to get the values the placeholder has no controls.  Every control added has an unique ID.  Does anyone know what I am doing wrong (language is C#).      aspx page <asp:UpdatePanel ID="upShoppingCart" runat="server" UpdateMode="Conditional" >                    <ContentTemplate>                        <asp:PlaceHolder ID="phShoppingCart" runat="server" />                        <br /><asp:Button ID="btnUpdateCart" runat="server" Text="Update" OnClick="btnUpdateCart_OnClick" />                    </ContentTemplate>                </asp:UpdatePanel>   .cs page         private void CreateShoppingCart()     &nb

Dynamically created controls not accessible after post back.

Dear Friends, pls give the solution. code given below.. dynamically HtmlInputCheckBox created and add in PlaceHolder(panel). I can't get the created control values after post back..Dynamic Control Creationprivate void GetPhotos() { HtmlImage img; HtmlInputCheckBox ic; panel.Controls.Clear(); DataTable dtPhotos = DLayer.Qry_WithDataTable("ADM_GET_HotelPhotos"); foreach(DataRow drPhotos in dtPhotos.Rows) { if ( File.Exists(Server.MapPath("../Photos/Hotel/" + drPhotos["FileName"].ToString()))) { ic = new HtmlInputCheckBox(); ic.Value = drPhotos[0].ToString(); if (drPhotos["PStatus"].ToString() == "1") ic.Checked = true; else ic.Checked = false; panel.Controls.Add(ic); img = new HtmlImage(); img.Src = "~/Photos/Hotel/" + drPhotos["FileName"].ToString(); img.Alt = drPhotos[1].ToString(); img.Attributes.Add("title", drPhotos["PhotoCaption"].ToString()); panel.Controls.Add(img); } } }Get checkbox values foreach (Control ctbl in panel.Controls)        {            if (ctbl is HtmlI

Resize dynamically created controls on Canvas



This is my first thread on this forum and i'm a beginner on WPF.

After google-ing for long time, it seems I can't find a solution for my problem.

I'm working on WPF form. The form contains a canvas and I create Labels on the Canvas dynamically at run-time.

First I had a problem to move the control on the canvas, but eventually I solved this problem by using a class implemented by Josh smith from

his article on codeproject.com. Now, I can move my lables freely on the Canvas.

But now, I want to resize the labels width or height that are created at run-time.

I changed the cursor of the mouse to (horizontal scroll or Vertical scroll) when it touched when of the edges of the label.

but I can't find how to implement the resizing when the mouse goes down or pressed to stretch the label.

Many tutorials found on the web talks about resizing controls the are previously declared in xaml and I want to implement it at code-behind.

Can please help me.

Thanks for help in advance.

jquery how to loop through dynamically created controls


I'm trying to use the following loop to loop through dynamically created controls on my web form:

                for(x = 0; x <= count; x++) {
                    Stmt += $("#DDLColumns" + x).val();
                    switch($("#DDLConditional" + x).val()) {
                        case "is equal": Stmt += " = ";
                        case "begins with": Stmt += " LIKE '%";
                    Stmt += $(&q

Tricky Insert Logic for dynamically created row in GridView.


Hi, and thanks for peeping the query i have.

I am dynamically generating the Row in GridView and saving the data in database using StringCollection. Instead of using StringCollection i want to pass the data(user entered data) to local variable , eg:

string name = txtFName; and so on. but it wont work for dynamically created rows.

So if you knw how to assign the user provided data in the local variable like above i have show, please help me out. 

The code for inserting the records for dynamic created rows in grid view via StringCollection is below


protected void btnSave_Click(object sender, EventArgs e)


        int rowIndex = 0;

        StringCollection sc = new StringCollection();

        if (ViewState["CurrentTable"] != null)


            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

            if (dtCurrentTable.Rows.Count > 0)


Gridview Paging with Dynamically created Gridview in VB.NET



I have a page that I am creating 5 separate GridViews on, depending on the button the user clicks, a different GridView will show up. On a few of the GridView's there is a need for paging, so in the CodeBehind I did the following

            billingGridView.ID = "BillingGridView"
            billingGridView.DataSource = sdsBilling
            billingGridView.AutoGenerateColumns = False
            billingGridView.AllowPaging = True

            billingGridView.ID = "BillingGridView"
            billingGridView.DataSource = sdsBilling
            billingGridView.AutoGenerateColumns = False

How do I determine the size of a dynamically created set of controls?



How do I determine the size of a dynamically created set of controls?

For example, suppose I have a method that creates a form made up of many TextBlocks, TextBoxes, etc., all contained within a grid and that grid is returned by the method.  I need to determine the size of that grid without adding it to any other controls.

    Grid myForm = myMethodThatReturnsAGrid();

    // Here is where I want to find out the size (height and width) of the grid myForm.

The reason I need the size, mainly the height is to determine if it will fit in what is left of the page of a FixedDocument for a report, and if not, to move it to the next page.




Regards, Robert -- Note: I work on various aspects of one or more programs, working on what is most important at the time. Some questions I ask are on aspects of the program that are not important right now or I'm using a workaround for now. Eventually they'll be high priority again and I'll get back to those answers received and respond accordingly. Those that are high priority get responses very soon. Thanks for your input, it is appreciated.

Gridview SelectedIndexChanged on a dynamically created gridview


my html page is basically a panel

Programmatically i've created the entire page adding controls to the panel. I have a dynamically created Accordion and within each accordion pane i have a dynamic gridview based on the properties for the accordion pane. Each row within the GridView i have a Button with the CommandName of Select, with this i want to open a new window and go to a new URL with the properties in a BoundField. On postback i want to be able to return to the Accordion.SelectedIndex. 

The problem is i can't seem to use a findControl to capture the index of either the GridView or Accordion. Below is my code:

AjaxControlToolkit.Accordion accordion = new AjaxControlToolkit.Accordion();
        accordion.ID = "Accordion2";
        accordion.HeaderCssClass = "accordionHeader";
        accordion.ContentCssClass = "accordionContent";
        accordion.HeaderSelectedCssClass = "accordionHeaderSelected";
        accordion.FramesPerSecond = 100;
        accordion.TransitionDuration = 100;
        accordion.FadeTransitions = true;
        accordion.EnableViewState = true;
        if (Session["myAccordion.SelectedIndex"] != null)
            accordion.SelectedIndex = (int)Session["myAccordion.SelectedIndex"];


Accessing the different controls inside a GridView control

how we can access a particular control which resides inside a GridView control. In this article I will show you how you can access different controls inside a GridView control. We will see how we can access a TextBox control, a DropDownList control and a ListBox control. If you are working with ASP.NET 1.X then you might want to check out my article Accessing Different Controls Inside a DataGrid.

Dynamically Create Controls in ASP.NET by Using Visual C# .NET

This article demonstrates how to dynamically create a control for an .aspx page. The sample project does the following:
Creates two TextBox controls.
Verifies that the contents (TextBox.text) and the attributes of the TextBox are saved across posts to the server.
Illustrates handling events that are posted by a dynamically-created control

Dynamically Create Controls in ASP.NET with Visual Basic .NET

This step-by-step article describes how to dynamically create controls for an ASPX Web page.

The sample project does the following:
It creates two TextBox controls.
It verifies that the TextBox contents (TextBox.text) and attributes are saved across posts to the server.
It describes how events that are posted by a dynamically created control are handled.

How to bind GridView and DropDownList controls using DataTable object

In .net framework 2.0, you can load a DataTable in memory by consuming a data source using a DataReader. In this version you will find the flexibility in accessing the DataReader means write access code once and use again and again using DataReader. To see the functionality of DataTable consider an example that is created using VS2005.

ASP.NET: Selectively Enable Form Validation When Using ASP.NET Web Controls


Sometimes the extra controls that come with Visual Studio .NET can be a bit inflexible or they just don't provide enough functionality or flexibility for all situations. The ASP.NET form validation controls, while powerful and easy to use, require that the entire page be valid before it's submitted back to the server. Through the use of the new object-oriented features of Visual Basic .NET, it is possible to extend their functionality to overcome this limitation. This article tells you how and helps you decide when it's a good idea to keep validation on the client and when you'd be better off disabling it.

James M. Venglarik II

MSDN Magazine April 2002

Custom Grid View Header - Grid view Row Created event vs Gridview row databound events ?


Hi Gurus ,

It happened to add an extra Gridveiw Header in row_databound event , It did worked fine on !Postback but disappered on Page.Postback . Quick google search guided me to move the event to Row_Created event and every thing is okay .

Can any expert post some pointers , differnces between grid row_created vs row_databount with some sample table data created dynamically  behaviour of both the events in !Postback and page.Postback .

Thanks a tonne in Advance and  any inputs will be valued and appreciated .

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

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