Web Forms :: Creating Multiple UserControls At Runtime?
Mar 1, 2011I want to create several instances of a webcontrol on my web page each time the user clicks an 'add' button.
HTML
[Code]....
c#
[Code]....
I want to create several instances of a webcontrol on my web page each time the user clicks an 'add' button.
HTML
[Code]....
c#
[Code]....
I have a userControl with with two DDLs and two RBLs, and public properties to get/set the values. If I register the UC on a page it works fine....I can set/retrieve the values without a problem.
I need to create multiple UCs based on records I'm pulling from a dB, so I'm trying to instead create the UCs programmatically. I'm testing this by adding a reference to the control ("symptomBasic"), creating a placeholder ("ph1") on a page and then trying to populate it with the UCs in PageInit. (the parent page uses a master page)
Partial Class testUC
Inherits System.Web.UI.Page
Private myUC As ASP.symptomBasic
Protected Sub Page_init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Dim i As Integer
For i = 1 To 3
myUC = CType(LoadControl("~/controls/symptom.ascx"), ASP.symptomBasic)
ph1.Controls.Add(myUC)
Next
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
When I load the page, I get three UCs in a row, and they work properly on postback...i.e. all the values are preserved. Question is, how do I then find the controls on postback when I want to populate them with data or read the values back?
Let's say I know I returned 3 rows from the dB and created 3 UCs during pageInit...how do I then access those controls to read back the values provided by the user? I see that each control has an ID like: "ctl00_ContentPlaceHolder1_ctl01_cName", where each set of controls is "ctl00", "ctl01", etc.
I have a simple user control which contains a textbox and a dropdownlist. I need to add this control multiple times to my page then save the details to my db, validating each control. When they re-enter my page I need to load the user control for each record in the db populated with the data they entered. They can then edit the data, delete the row or add new rows.
I'm trying to find the cleanest most efficient way to accomplish this. I realise I would need to re-add the user controls after each postback re-populating the data. Would the best way be to add each row to an arraylist or list of type object, save it to the viewstate and re-add the controls with data on postback, or is there another method which would suit?
I am generating instances of a UserControl and putting them in an UL. In my UserControl there is a button with an event. I want to ask how I can keep the state of the UserControls I generated so that they remain on the page after a postback and also to catch their events.
For i As Integer = 0 To lstFoo.Count - 1
Dim liFoo As New HtmlGenericControl("li")
Dim ucMyFoo As ucFoo = LoadControl("userControls/ucFoo.ascx")
liFoo.Controls.Add(ucMyFoo)
ucMyFoo.DoSomething()
ulFoo.Controls.Add(liFoo)
Next
I have a requirement whereby one or more image buttons need to be created in a user control at runtime. The number of buttons is determined from a database where a user can add one or more rows that contain an image for each button, so if a user adds 3 images to a table, 3 image buttons are created. Ive used this code but I get an error at runtime
The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
[Code]....
this is the usercontrol aspx
[Code]....
I basically want one or more buttons to render within the div in the usercontrol. Ive only got the code written for one button at the moment while I test the rendering, eventually they will be rendered in a loop of records taken from a database. Whats the best way to do this ?
I need to create aspx pages on the fly or at the runtime.I read that creating a template page and posting content to the page would be a solution, in a few posts in the forum. Can i get information on this method.
View 5 Repliesi am creating some of the control at runtime according database values. problem is that when i click onto the button, if the text box is empty, the required field validator(genrated at runtime) show first time that the text box is empty. but one agin i click on to the button, it doest show any error messege and all of the control which i am genrating at run time are hiding when i see at the page source, no control is find there.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using AjaxControlToolkit;
using click2install.controls;
public partial class FeebackForm_Client : System.Web.UI.Page
{
HtmlGenericControl table = new HtmlGenericControl("table");
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CreateForm();
}
}
public void CreateForm()
{
ds = DBManager.ExecuteDataset("[FeedBack_FeedbackDetail_get]");
for (int i = 1; i < ds.Tables[0].Columns.Count - 1; i = i + 4)
{
//CreateControl(txtAddress.Text.ToString(), txtAddressRun, false, false, txtAddressToolTip.Text, txtAddressWaterMark.Text);
string Name = ds.Tables[0].Rows[0][i].ToString().Replace(" ","");
if (Name != "")
{
TextBox txtControl = new TextBox();
//RequiredTextBox txtControl = new RequiredTextBox();
txtControl.ID = "txt" + Name;
txtControl.CausesValidation = true;
bool RequiredField;
bool ToolTip;
if (ds.Tables[0].Rows[0][i + 3].ToString() == "True")
{
RequiredField = true;
}
else
RequiredField = false;
if (ds.Tables[0].Rows[0][i + 1].ToString() != "")
{
ToolTip = true;
}
else
ToolTip = false;
string TooltipText = ds.Tables[0].Rows[0][i + 1].ToString();
string WaterMarkText = ds.Tables[0].Rows[0][i + 2].ToString();
CreateControl(Name, txtControl, RequiredField, ToolTip, TooltipText, WaterMarkText);
}
}
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td1 = new HtmlGenericControl("td");
HtmlGenericControl td2 = new HtmlGenericControl("td");
HtmlGenericControl td3 = new HtmlGenericControl("td");
HtmlGenericControl td4 = new HtmlGenericControl("td");
Button btnInsertRun = new Button();
btnInsertRun.Text = btnSubmit.Text.ToString();
btnInsertRun.ValidationGroup = "Check";
td2.Controls.Add(btnInsertRun);
tr.Controls.Add(td1);
tr.Controls.Add(td2);
tr.Controls.Add(td3);
tr.Controls.Add(td4);
table.Controls.Add(tr);
pnlPreview.Controls.Add(table);
System.Threading.Thread.Sleep(500);
ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), "Hide();", true);
System.Threading.Thread.Sleep(500);
ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), "ShowAddDisability()", true);
}
public void btnInsertRun_Click(object sender, System.EventArgs e)
{
CreateForm();
//ds = DBManager.ExecuteDataset("[FeedBack_FeedbackDetail_get]");
//TextBox txt1,txt2,txt3,txt4,txt5=new TextBox();
//objBox2 = this.Page.FindControl("objBox2") as TextBox;
string ss = "txt" + ds.Tables[0].Rows[0][1].ToString();
//TextBox objTextBox = (TextBox)PnlControlPanel1.FindControl(strControlName);
TextBox txt1 = new TextBox();
txt1 = (TextBox)this.Page.FindControl("txt" + ds.Tables[0].Rows[0][1].ToString());
//txt1=this.pnlContainer.FindControl("txt"+ds.Tables[0].Rows[0][1].ToString()) as TextBox;
// txt2 = this.pnlContainer.FindControl("txt" + ds.Tables[0].Rows[0][5].ToString()) as TextBox;
// txt3 = this.pnlContainer.FindControl("txt" + ds.Tables[0].Rows[0][9].ToString()) as TextBox;
// txt4 = this.pnlContainer.FindControl("txt" + ds.Tables[0].Rows[0][13].ToString()) as TextBox;
// txt5 = this.pnlContainer.FindControl("txt" + ds.Tables[0].Rows[0][17].ToString()) as TextBox;
string fh = txt1.Text;
//DBManager.ExecuteNonQuery("Feedback_FeedbackInsert", ds.Tables[0].Rows[0][1].ToString(), txt1.Text,ds.Tables[0].Rows[0][5].ToString(), txt2.Text,ds.Tables[0].Rows[0][9].ToString(), txt3.Text,ds.Tables[0].Rows[0][13].ToString(), txt4.Text,ds.Tables[0].Rows[0][17].ToString(),
txt5.Text);
Response.Write("Ho Gya");
}
public void CreateControl(string Name, TextBox ControlID, bool RequiredField, bool Tooltip, string TooltipText, string WaterMarkText)
{
if (WaterMarkText == "")
WaterMarkText = Name;
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td1 = new HtmlGenericControl("td");
HtmlGenericControl td2 = new HtmlGenericControl("td");
HtmlGenericControl td3 = new HtmlGenericControl("td");
HtmlGenericControl td4 = new HtmlGenericControl("td");
td1.InnerText = Name;
ControlID.ValidationGroup = "Check";
//ControlID.ValidatorMessage = Name + " is Required Field";
//ControlID.ValidatorDisplayType = ValidatorDisplay.Dynamic;
//ControlID.ValidatorEnableClientScript = true;
td2.Controls.Add(ControlID);
if (RequiredField == true)
{
//RequiredFieldValidator Valid = new RequiredFieldValidator();
//Valid.ID = "Valid" + Name;
//Valid.ControlToValidate = ControlID.ID.ToString();
//Valid.ErrorMessage = Name + " is Required Field";
//Valid.Text = "*";
//Valid.Display = ValidatorDisplay.Dynamic;
//Valid.EnableViewState = true;
//Valid.SetFocusOnError = true;
//Valid.Enabled = true;
//Valid.EnableClientScript = true;
//Valid.InitialValue = WaterMarkText;
//Valid.ValidationGroup = "Check";
//td3.Controls.Add(Valid);
}
if (Tooltip == true)
{
HtmlGenericControl span = new HtmlGenericControl("span");
//span.Attributes.Add("class", "hotspot");
span.Attributes.Add("onmouseout", "tooltip.hide();");
span.Attributes.Add("onmouseover", "tooltip.show('" + TooltipText + "');");
HtmlImage img = new HtmlImage();
img.Src = "info.png";
span.Controls.Add(img);
td4.Controls.Add(span);
}
//TextBoxWatermarkExtender WaterMark = new TextBoxWatermarkExtender();
//WaterMark.WatermarkText = WaterMarkText;
//WaterMark.EnableClientState = true;
//WaterMark.TargetControlID = ControlID.ID.ToString();
//WaterMark.Enabled = true;
//WaterMark.ID = "WaterMark" + Name;
//td1.Controls.Add(WaterMark);
tr.Controls.Add(td1);
tr.Controls.Add(td2);
tr.Controls.Add(td3);
tr.Controls.Add(td4);
table.Controls.Add(tr);
}
}
after rendring the page...
<div id="pnlContainer">
<table><tbody><tr><td>Email</td><td><input type="text" id="txtEmail" name="txtEmail"></td><td></td><td><span onmouseover="tooltip.show('Email');" onmouseout="tooltip.hide();"><img src="info.png"></span></td></tr><tr><td>FirstName</td><td><input type="text"
id="txtFirstName" name="txtFirstName"></td><td></td><td><span onmouseover="tooltip.show('First Name');" onmouseout="tooltip.hide();"><img src="info.png"></span></td></tr><tr><td>LastName</td><td><input type="text" id="txtLastName" name="txtLastName"></td><td></td><td><span
onmouseover="tooltip.show('Last Name');" onmouseout="tooltip.hide();"><img src="info.png"></span></td></tr><tr><td>City</td><td><input type="text" id="txtCity" name="txtCity"></td><td></td><td><span onmouseover="tooltip.show('City');" onmouseout="tooltip.hide();"><img
src="info.png"></span></td></tr><tr><td>Address</td><td><input type="text" id="txtAddress" name="txtAddress"></td><td></td><td><span onmouseover="tooltip.show('Address');" onmouseout="tooltip.hide();"><img src="info.png"></span></td></tr></tbody></table></div>
but after the click on to the button it shows only the container div..
<div id="pnlContainer"></div>
I want to create buttons and text boxs runtime and assigne to asp table.
When user clicks on button text box should be visible and user will be able to type some text and submit to server. This is nothing but something
like Blog. I am able to create asp table, button and testboxes but could not do visibility and events of buttons.
I'm having problems binding controls at runtime. I've some user controls which need to be bind to the page when one of the dropdownlist selected index changed.
I can able to bind them properly but when if there is any postback event happens I am losing the controls and control values which were created runtime.
How do I avoid binding them again and again.
suppose that i have a gridview and an objectdatasource in my webform
with that i want to include several search criteria
the problem is that i want theme dynamic
for example
i have a dropdownlit with customers list
the first item in the dropdownlist is "All customers" for example
if i select it no "customer select parameter" is created
otherwise i have a "customer select parameter" for the objectdatasource and it's value is the dropdownlist.selectedvalue
1. On OnCreatedUser event, I create a folder for each members, so that they can store their files inside those. The thing is I use User.Provider key as a folder name. Is this a good way to store? Is this OK from security view point. Otherwise I am planning to use the User.Username. Here are the codes inside the OnCreatedUser event.
[Code]....
2. Inside these user folders I want to put web.config at run time [at the time of registration]. So that a member cannot access files of other members at any cost. Do you have any idea on creating web.config file at runtime inside these folders? Else if you can provide me any other options, I am eager to listen that. I don't want to call database frequently. So if there is any easy solution.
I've an ASP.NET MVC web site and I'm using AspNetSqlProvider to configure Secutiry
So, I runned aspnet_regsql command to create and configure aspnetdb database that hold users, roles , etc....
I use the asp.net application web management to create roles, users , etc... Ok
But I would like to create roles at runtime :
- If a new user visit my application, I would like to register it as a user and affect it a role ( Visitors)
- If a seller N visit my application, I would like to create a role ( seller N) to register the vositor as admin of seller N
How can we manager this scenario using my configured database aspnetdb ?
I have a DataTable where the columns are generated programmatically at runtime. I then bind this DataTable to a GridView. What I'm wondering is how I can create the GridView to accommodate this, and if it's not possible, how I can output the DataTable into nicely formatted HTML.
View 3 RepliesNewbie in using AJAX . Programming in C# and using SQL as a database. Here is my scenario. User selects a project and I want to display the subprojects related to that project. Here is the query I use to retrieve subprojects.
"SELECT SubProjectName,StartDate,Description FROM SubProject WHERE ProjectName'"+ddlProjectName.text+"';
Currently I store the results of the query in a Dataset. I want to get the SubProjectName in the Header of the Accordion and StartDate and Description values to the text box for each accordion. ( This is what I need to do in each accordian for each subproject)
<asp:AccordionPane ID="AccordionPane2" runat="server">
<Header>
<a href="" onclick="return false;" class="accordionLink">SubProject 1</a>
</Header>
<Content>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td class="td_left" colspan="2">
<asp:Label ID="Label1" runat="server" Text="Start Date"></asp:Label>
</td>
<td class="td_left" colspan="2">
<asp:TextBox ID="StartDate" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="td_left" colspan="2">
<asp:Label ID="Label2" runat="server" Text="Description"></asp:Label>
</td>
<td class="td_left" colspan="2">
<asp:TextBox ID="txtDecription" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</Content>
</asp:AccordionPane>
How can I do this? Some code example would be great on how to creat the accordinas ,text boxes dynamically and fill the values.
I have a Masterpage that has Treeview. You can select some nodes there. Based on the selection you get some items in the Default.aspx's Placeholder, you get a image and a linkbutton placed in a Panel. Like this :
This code is in the Default.aspx that has the Masterpage.
[Code]....
There seems to be problem when i create the controllers at runtime, when the site does a postback, lets say if i click "Enska" in the treeview i get the results in the image above. Lets say that i then click "The Punk Panther" i get a error.
An error has occurred because a control with id 'ctl00$CPH_Main$ctl05' could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error.
Also, how would i go by making a event handler for the linkbutton at runtime, can i make one event handler that every linkbutton uses or what ? I want the folder and the linkbutton to be clickable and link to the same place, is it simpler to make the whole Panel clickable, if so, how would i get a "OnClick" event on it ?
Sometimes MS provides error message so silly that its hard to understnad and you feel like throwing away all things.
My Web.Config does not contain any entries of MemberShip, Role or Profile.
I want to create a membership provider dynamically through code at runtime. I wrote following code and it receives following error message. I don;t know how come machine.config error appears in my application. how annoying.
Parser Error Message: The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty.
Source Error:
[Code]....
Source File: C:WindowsMicrosoft.NETFrameworkv2.0.50727Configmachine.config Line: 139
Following is the CODE.
[Code]....
I'm trying to make a form that could have one or multiple textboxes. I have a textbox and a button to add additional textboxes.
I have no problem adding a second textbox inside a panel but I want to be able to keep adding more textboxes every time the link button is clicked and later reference those boxes to be saved. I would also like to maintain the value of the textboxes there. They are not saved to the database until all the necesary texboxes have been added.
I added the textbox using:
private void button1_Click(Object sender, System.EventArgs e)
{
TextBox textbox1 = new TextBox();
panel.controls.add(textbox1);
}
that works fine, but when i click the button again it doesn't add an additional textbox which is what i need.
I'm trying to create multiple gridviews for a number of individuals based on a selection from a dropdownlist. The user will select his choice from the dropdownlist and from there a query is run to find the number of gridviews to create. Each gridview will also have its own data to bind. I believe I have most of it, I just can't get the gridview to show up. My thinking is to create the labels, then insert a gridview, bind it, and then repeat the process all over.
[Code]....
I've an item template inside a grid which has a <asp:LinkButton/> inside it. I assign the text for the link button as
<%# Convert.ToString(Eval("Tags"))%>
Tags can have a string with multiple tags in it delimited by space. For eg. "sports", "sports cricket", "sports cricket sachin" are the examples of some possible tags.
I want to create a button for each tag inside the string. How can i create the controls (server control - linkbutton) dynamically during runtime inside the grid item template?
i have a dropdownlist contaning years..now i want to connect my database by dropdown selection.if i select 2013 it will connect 2013 database ,if i select 2014 it connect 2014 so on..
View 1 RepliesI have multiple gridviews on a page. I would like to add these to an excel file and have a worksheet for each gridview.
I found some code on the web to accomplish this. However, when i run it i always get all the gridviews on one worksheet. The code is shown below.
Can somebody tell me how i can send multiple gridviews to an excel file to get a workbook with multiple worksheets?
[Code]....
Brief introduction:I have this ASP.NET Webforms site with the particularity that it doesn't have only 1 database, it has many.Why? Because you can create new "instances" of the site on-the-fly. Every "instance" share the same codebase, but has its own database. These all databases have the same schema (structure) but of course different data. Don't ask 'why don't you put everything in one database and use InstanceId to know which is" because it's a business policy thing.
The application knows which instance is being requested because of the url. There is one extra database to accomplish this (I do know its connection string in design time). This database has only 2 tables and associates urls to 'application instances'. Then, of course, each 'application instance' has its associated connection string.
Current situation: There is nothing being used right now to help us with the job of mantaining every instance database in sync (propagating schema changes to every one). So we are doing it by hand, which of course it's a total mess.
Question: I'd like to use a rails-migration way to handle schema changes, preferably migratordotnet, but could use any other if it's easier to setup.The problem is that migratordotnet needs the connnection string to be declare in the proj.build file and I don't know them until runtime. What it would be REALLY useful is some kind of method running on *Application_Start* that applies the latest migration to every database.How could this be done with migratordotnet or any similar?
Can anybody let me know the activex script for detecting .net runtime and directx runtime or any other way how can I detect this in any machine by from my web page ?
View 1 RepliesI want to create a zip files for multiple file
Ex: Folder One-----------> file1, file2, file3
want to zip 3 files into folder.zip
The way we have to update our site now is to create a copy of the website project locally. Make changes. Then take the dll and any other new files and copy them to the project on the server. Sometimes they want us to work on something they need uploaded right away and other times work on something that needs to be uploaded in the future. So I have to do silly things to give them what they want now and exclude what I am working on for later. What is the best way to resolve this? I just wanna have to upload a piece of the project and certainly not the a whole new dll everytime.
View 1 Replies