473,231 Members | 2,009 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,231 software developers and data experts.

C# Event Handlers For Dynamically Created DropDownLists

Hello..I have a similar issue as yesterday but the situation has
slightly changed so perhaps someone can shed some more light on the
issue...

Program flow - load file,extract xml text tags from file,then depending
on the number of Xml tags retrieved from the file determines the number
of dropdownlist controls instanciated in the placeholder,the user
selects the required tags from the
dropdownlists (if 5 Xml tags,then 5 dropdownlists each containing 5 xml
tags) and now the btnSave button is selected which extracts the user
selection form the dropdownlists.

Once btnLoadXmlTags_Click function is called,an array is filled with the
xml tags,this function also creates a session variable call
"OkToRecreateControls" which permits Page OnInit to recreate the dynamic
controls for subsequent postbacks,then the
btnLoadXmlTags_Click function calls the CreateDynamicControls which in
turn calls the function AddContentToDynamicControls.

The above works fine and for subsequent postbacks page onInit can call
CreateDynamicControls which will now run since the
"OkToRecreateControls" session variable is now valid.

Problem - when the user selection is extracted form the dropdownlists
using the btnSave function the first dropdownlist works fine,but the
other dorpdownlists
return the values as selected in the first dropdownlist rather then
their own content ...Theo

Code Sample

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Data.SqlClient;
using System.Configuration;

namespace AspXmlDbMapper_v2
{

public class wfrmMain4_BackUp : System.Web.UI.Page
{

protected System.Web.UI.Page Me;
protected System.Web.UI.WebControls.PlaceHolder plhDbContent;
protected System.Web.UI.WebControls.PlaceHolder plhXmlContent;
protected System.Web.UI.HtmlControls.HtmlInputFile fileDb;
protected System.Web.UI.HtmlControls.HtmlInputFile fileXml;

protected System.Web.UI.WebControls.Button btnLoadDb;
protected System.Web.UI.WebControls.Button btnLoadDbAttributes;
protected System.Web.UI.WebControls.Button btnLoadXml;
protected System.Web.UI.WebControls.Button btnLoadXmlTags;
protected System.Web.UI.WebControls.Button btnSave;
protected System.Web.UI.HtmlControls.HtmlGenericControl span1;
protected System.Web.UI.HtmlControls.HtmlGenericControl span2;
protected System.Web.UI.WebControls.DropDownList ddlXmlTagList;
protected System.Web.UI.LiteralControl literal;

protected System.Web.UI.LiteralControl[] aryLieralCtrls;
protected System.Web.UI.WebControls.DropDownList[] aryDdlCtrls;

private string xmlFileDestination = "";
private ArrayList aryTxtNodes = new ArrayList();
private ArrayList aryEleNodes = new ArrayList();
protected System.Web.UI.WebControls.DropDownList ddlXmlTagList1;
private ArrayList aryAtrbNodes = new ArrayList();

private void Page_Load(object sender, System.EventArgs e)
{

}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
CreateDynamicControls();
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.btnLoadXml.Click += new System.EventHandler(this.btnLoadXml_Click);
this.btnLoadXmlTags.Click += new
System.EventHandler(this.btnLoadXmlTags_Click);
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void btnLoadDb_Click(object sender, System.EventArgs e)
{
if (fileDb.PostedFile != null )
{
string dbFilePath = "C:\\TempXml";
string fileName = Path.GetFileName(fileDb.Value);
string dbFileDestination = Path.Combine(dbFilePath,fileName);

try
{
fileDb.PostedFile.SaveAs(dbFileDestination);
span1.InnerHtml = "File uploaded successfully to <b>" +
dbFileDestination + "</b>";

}
catch (Exception exc)
{
span1.InnerHtml = "Error saving file <b>" + dbFileDestination +
"</b><br>"+ exc.ToString();

}
}
}

private void btnLoadXml_Click(object sender, System.EventArgs e)
{
string fileDestination = "C:\\TempXml";
string fileName = Path.GetFileName(fileXml.Value);
string fileExtentsion = Path.GetExtension(fileXml.Value);

xmlFileDestination = Path.Combine(fileDestination,fileName);
Session["xmlFilePath"] = xmlFileDestination;

if (fileXml.PostedFile != null )
{
//error check...file has .xml extentsion
if (fileExtentsion.ToString().Equals(".xml"))
{
try
{
fileXml.PostedFile.SaveAs(xmlFileDestination);
span2.InnerHtml = "File uploaded successfully to <b>" +
xmlFileDestination + "</b>";
Session["xmlFileLoadedOk"] = true;
fileXml.Dispose();
}
catch (Exception exc)
{
span2.InnerHtml = "Error saving file <b>" + xmlFileDestination +
"</b><br>"+ exc.ToString();
}
}
else
{
MsgBox("Error...loaded incorrect file type \\n\\nCorrect file type is
\" filename.xml \"");
}
}
}

private void btnLoadXmlTags_Click(object sender, System.EventArgs e)
{
int elementCount=0, attributeCount=0, textCount=0;

try
{
string fileDestination = (string)Session["xmlFilePath"];
StreamReader streamreader = new StreamReader (fileDestination);
XmlTextReader xmlReader = new XmlTextReader (streamreader);

while (xmlReader.Read())
{
string myNode = "";

switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
elementCount++;
myNode = xmlReader.Name;
aryEleNodes.Add(myNode);
if (xmlReader.HasAttributes)
{
attributeCount++;
myNode = xmlReader.Value;
aryAtrbNodes.Add(myNode);
}
break;
case XmlNodeType.Text:
//assign last element name tag and current text value to string
myNode = "<" + aryEleNodes[aryEleNodes.Count-1].ToString() + ">" +
xmlReader.Value;
aryTxtNodes.Add(myNode);
textCount++;
break;
}
}
streamreader.Close();
xmlReader.Close();
string strObj = "true";
Session["OkToRecreateControls"] = strObj;
Session["tempArray"] = aryTxtNodes;
CreateDynamicControls();
}
catch(Exception exc)
{
span2.InnerHtml = "Error...loading xml tags </b><br>"+ exc.ToString();
}
}

public void CreateDynamicControls()
{
string strOkToRecreateControls =
(string)Session["OkToRecreateControls"];
plhXmlContent.EnableViewState = true;

if (strOkToRecreateControls != null)
{
ArrayList aryNodes = (ArrayList)Session["tempArray"];

for (int createControl=0; createControl < aryNodes.Count;
createControl++)
{
literal = new LiteralControl();
literal.ID = "ltrId" + (createControl + 1).ToString();
plhXmlContent.Controls.Add(literal);

ddlXmlTagList = new DropDownList();
ddlXmlTagList.ID = "ddlId" + (createControl + 1).ToString();
ddlXmlTagList.AutoPostBack = true;
ddlXmlTagList.EnableViewState = true;
ddlXmlTagList.SelectedIndexChanged += new
EventHandler(ddlXmlTagList_SelectedIndexChanged);
plhXmlContent.Controls.Add(ddlXmlTagList);
}

string strObj = "true";
Session["OkToAddContent"] = strObj;
Session["OkToRecreateControls"] = strOkToRecreateControls;
AddContentToDynamicControls();
}
}

public void AddContentToDynamicControls()
{
string strOkToAddContent = (string)Session["OkToAddContent"];

if (strOkToAddContent != null)
{
ArrayList aryNodes = (ArrayList)Session["tempArray"];

for (int addContent = 0; addContent < aryNodes.Count; addContent++)
{
string ltrName = "ltrId" + (addContent + 1).ToString();
string ddlName = "ddlId" + (addContent + 1).ToString();

LiteralControl ltl =
(LiteralControl)this.FindControl("plhXmlContent"). FindControl(ltrName);
DropDownList ddl =
(DropDownList)this.FindControl("plhXmlContent").Fi ndControl(ddlName);

ltl.Text = "<p><strong>Xml Tag " + (addContent + 1) + ":</b>";

for(int addItem = 0;addItem < aryNodes.Count;addItem++)
{
ddl.Items.Add(aryNodes[addItem].ToString());
}

ddl.SelectedIndex = addContent;
}
}
}

private void btnSave_Click(object sender, System.EventArgs e)
{
MsgBox(ReadDropDownList(this,e));
}

public void MsgBox(string strMsg)
{
string alertScript;

alertScript = "<script language=JavaScript> alert('" + strMsg +"');
</script" +">";

if (!IsClientScriptBlockRegistered("alert"))
this.RegisterClientScriptBlock("alert", alertScript);
}

public string ReadDropDownList(object sender, System.EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
if ( ddl != null )
{
if ( ddl.SelectedIndex >= 0 )
{
string strSelection = "Selected Control Id : " + ddl.ID.ToString();
strSelection+= "\\nSelected Text : " + ddl.SelectedItem.Text.ToString();

}
}
return strSelection;
}
}
}

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #1
0 2091

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Donald Xie | last post by:
Hi, I noticed an interesting effect when working with controls that are dynamically loaded. For instance, on a web form with a PlaceHolder control named ImageHolder, I dynamically add an image...
5
by: Sosh | last post by:
Hi, I can't seem to find much information on this. Please could someone explain to me how to wire up events (selectedIndexChanged) to a bunch of dynamically created controls (Dropdownlists),...
9
by: Marcelo Cabrera | last post by:
Hi, I have a user control that in turn creates a bunch of webcontrols dynamically and handles the events these webcontrols raise. It used to work fine on ASP .Net 1.1 but when compiled on 2.0 it...
0
by: Silver Oak | last post by:
I have a DataGrid in which one of the columns is TemplateColumn that was created dynamically using iTemplate. I would like to have multi-row editing capability on the DataGrid. I'm trying to...
1
by: kaczmar2 | last post by:
I have an ASP.NET page where controls are created dynamically, and I have an issue where one event handler creates another set of controls, and then adds event handlers to those controls. The...
2
by: John Kotuby | last post by:
Hi guys, I am converting a rather complicated database driven Web application from classic ASP to ASP.NET 2.0 using VB 2005 as the programming language. The original ASP application works quite...
1
by: Dica | last post by:
i've got a script that loops through a dataset and creates dynamic web controls and event handlers: while (oDr.Read()){ RadioButton oRb = new RadioButton(); oRb.ID = oDr.ToString();...
3
by: =?Utf-8?B?ZWFndWlsYXI=?= | last post by:
Hi, I am trying to dynamically generate a menu, based on entries on a text or xml file. The text file contains the "tree" after which the menu will need to be created. Something like the...
0
by: \(O\)enone | last post by:
I'm working on some code which dynamically adds WinForms controls to a form. It's all working well but I'm having to manually call AddHandler repeatedly for each event I am using each time I add...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.