.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

Loop through dynamically created DropDownLists

Posted By:      Posted Date: September 28, 2010    Points: 0   Category :ASP.Net

A short background about this project: I'm creating an image gallery where images are uploaded and sorted into a category and then a subcategory, eg. "Vehicles" and "Cars". Every subcategory has a variety of tags to further categorize the picture, eg. color and make in the cars subcategory.

These tags (named "Criterias") are listed as DropDownLists through the following piece of code:

public void GetCriterias(int subcategoryID)
    DataSet ds = igHelper.GetSubategoryCriterias(subcategoryID, 1);

    if (ds.Tables[0].Rows.Count > 0)
        int ddCount = 0;
        DropDownList[] ddCriterias = new DropDownList[ds.Tables[0].Rows.Count];

        foreach (DataRow row in ds.Tables[0].Rows)
            int criteriaID = Convert.ToInt32(row["CriteriaID"].ToString());

            DataSet dsCriteria = igHelper.GetCriteriaValues(criteriaID, 1);

            ddCriterias[ddCount] = new DropDownList();
            ddCriterias[ddCount].DataSource = dsCriteria;
            ddCriterias[ddCount].DataTextField = "Translation";
            ddCriterias[ddCount].DataValueField = "ValueID";
            ddCriterias[ddCount].Items.Insert(0, (new ListItem(ds.Tables[0].Rows[ddCount]["Translation"].ToString() + "...

View Complete Post

More Related Resource Links

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

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."

Issues with dynamically created TabContainer (Hide/Show TabPanel)


I have a web page that contains an UpdatePanel. In that panel, there is a TabContainer control that has 5 TabPanels, only the first one "Tab 1" will be displayed during initial page load. There is an Add button in "Tab 1", whenever it gets clicked, I will add (show) the next TabPanel (Tab 2, Tab 3, etc., all the way to Tab 5). "Tab 2" thru "Tab 5" contains a Close button that will close (hide) the current tab when clicked.

I'm doing all of these from code behind (dynamically create controls in Page_Init event and re-generate them during postback, track each TabPanel's content in a session variable, etc.), and everything seems to work just fine IF after adding several TabPanels, I remove  them in order (i.e. remove Tab 5 first, then Tab 4, Tab 3, etc.). It will NOT work whenever I try to remove a tab in the middle, then I will get all kinds of strange results.

I've attached the sample codes here for reviewing and testing. Any help is greatly appreciated.


==================== demo.aspx page ====================

<%@ Page

how to apply validation controls on Gridview which is created dynamically

 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"

Dynamically Created Charts

Using SSRS 2008. Is it possible to create a chart dynamically based on data passed in the query and then used in maybe expressions. Example would be if ClientID=1 then create a bar chart for 12 months, column colors would be green, if ClientID=2 then create a quarterly bar chart, column colors would be blue, if ClientID=3 create a 13 month chart (if possible) to show regular 12 months and a 13th month as a YTD column, column colors would be black. Any ideas or help is greatly appreciated

play storyboard with dynamically created image

this is my storyboard:   <Storyboard x:Key="expandStoryboard"> <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" To="2" Duration="0:0:0.2" /> <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" To="2" Duration="0:0:0.2" /> </Storyboard> <!-- This storyboard will make the image revert to its original size --> <Storyboard x:Key="shrinkStoryboard"> <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" To="1" Duration="0:0:0.2" /> <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" To="1" Duration="0:0:0.2" /> </Storyboard>   and i created image dynamically:   BitmapImage bmp = new BitmapImage(); bmp.BeginInit(); bmp.UriSource = new Uri("file:///" + arrstrFileNames[0].Replace("\\", "/")); bmp.EndInit(); Image img = new Image(); img.Source = bmp; RotateTransform rt = new RotateTransform(); img.LayoutTransform = rt; ScaleTransform st = new ScaleTransform(); st.ScaleX = 1; st.ScaleY = 1; img.LayoutTransform = st; if(first==true) img.ContextMenu = mnu; first = false; assignEv

Edit CSS path on file that is dynamically created by ASP.NET

Hi,I'm not very familiar with .NET so bear with me. The website is question is built in ASP.NET and is using Themes.The external CSS link is outputted on the .master page dynamically by ASP.NET (so I've been told), apparently it generates this code from any CSS file located in /App_Themes/The problem is I need the link to the CSS to begin with a "/" so it points to the root directory.Currently the syntax is: <link href="App_Themes/file/file.css" type="text/css" rel="stylesheet" />And I need it to be <link href="/App_Themes/file/file.css" type="text/css" rel="stylesheet" />Is there anyway I can achieve this?Much thanks,Nick

AsyncPostback problem with Dynamically created Buttons

Hi guys, I'm creating a table which contains some string and a delete button. What I want to do is to remove the row with ajax postback whenever i click the related delete button. The very first asyncpostback works without any problem. After first asyncpostback i have to click two times to a delete button in order to delete one row. I have traced it with debug, when I click delete button for the first time, it does not enter the event method of the button. However at the second time it triggers the event of the button. Here is the code below.page cs file: protected void Page_Load(object sender , EventArgs e) { if (!isLoggedIn()) { Response.Redirect("default.apsx", true); } else { PopulateAddresses(AddressZone.Controls); } } protected void PopulateAddresses(ControlCollection controls) { base.user.GetUserAddresses(); Literal table = new Literal(); Literal tableEnd = new Literal(); table.Text = "<table cellpadding=\"0\" cellspacing=\"0\"><tr><td style=\"width:130px;line-height:inherit\"><b>Bölge</b></td><td style=\"width:90px;line-height:inherit\"><b>Adres basligi</b></td&

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 button control click event not firing first time?

HI im creating a button control in page int and im assing a click event for the button control. here the click event is not firing for the first time.can anyone help me with this? here is my code. Button btn = new Button(); btn.ID = "btn"; btn.Click += new EventHandler(btn_Click); Panel1.Controls.Add(btn); Panel1.Controls.Add(new LiteralControl(""));

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

Dynamically created calendar does not store selected value

While using the first approach to get the selected date value in calendar control with Request.Form, it does not return any value.
Then i used a viewstate bag to store the Label in MyProperty, and assign this, _cldr.MyProperty = _Cldr.SelectedDate.ToShortDateString();
and finally get with calLabel.Text = calLabel.MyProperty.ToString();

it produce error with 'object instance not found..etc'.
private int CalendarCounter
                object o = ViewState["CalendarCounter"];
                if (o == null)
                    return 0;
                return (int)o;
            set { ViewState["CalendarCounter"] = value; }

        public class MyCalendar : Label
            public string MyProperty
                get { return ViewState["MyProperty"] == null ? String.Empty : ViewState["MyProperty"] as String; }
                set { ViewState["MyProperty"] = value; }


 if (Page.IsPostBack)

for (int i = 1; i <= CalendarCounter; i++)
                    Label lblctrl2 = new Label();
                    //It's very

How to Authenticate User on External Site Using IFrame (Dynamically created in SharePoint WebPart)



I've a situation,

- External Site : This site has its own user store (user/password) to log-in to.

- SharePoint WebPart : This webpart will get some readonly data from External Site but for performing any CURD operation on the External Site the user has to Log-in to External Site using IFrame Mechanism (This login form has to be of External site, and UserName/Passwordd should be posted to login-form of External site) sharepoint shouldn't be collecting any user/password credentials. (how can we do this?)

How user gets authenticated in External Site:

1. user Provides username/password.

2. Once authenticated to User Store it set an Authentication Cookie in use browser, thus uses this cookie with every request to perform any CURD operation.

I've to have the similar functionality in SharePoint Webpart. using IFRAME.

Hope i covered all the points in my explaination, if you can provide any blog/code which is dealing with similar kind of approach.



Akhilesh Nirapure

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.

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

How to use dynamically created texbox and labels during insert


With the help of other members i was able to add a table dynamically to my form.(http://forums.asp.net/t/1607009.aspx)

Now i need to grab the values and insert into the database. Below is the code used to create the table when a selection is made from a dropdown. My insert expects 3 parameters, ID, CamID, CamName

The ID will be from a field in the form, the CamID needs to be the "j" value below and the Camname to be the txtcam value.

What exactly can i do or what do i search on for help with this?



            for (int i = 1; i <= Convert.ToInt32(ddlNumCam.SelectedValue); i = i + 3)
                HtmlTableRow row = new HtmlTableRow();
                for (int j = i; j < i + 3 && j <= Convert.ToInt32(ddlNumCam.SelectedValue); j++)
                    HtmlTableCell cell1 = new HtmlTableCell();
                    HtmlTableCell cell2 = new HtmlTableCell();
                    cell1.Controls.Add(new TextBox() { ID = "txtCam" + j });
                    cell1.Width = "315px";
                    cell2.Controls.Add(new Label() { ID = "lblCam" + j, Text = " Camera # " + j + "  " });
                    cell2.Width = "115px&

Create a year dropdownlist that with dynamically created year values


Using vb.net/asp.net 2005

I have a Year dropdownlist that I want to have the listItems created dynamically with these conditions:

1.  the oldest year selection will be "2009"

2.  all years including "2009" and the current year will be included in the listitems.

It's obvious now (at this date) that 2009 and 2010 will be the 2 current listitems, however I want this dropdownlist to automatically add all subsequent years in coming years so that there will not be the need to add a new year listitem each year.



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