read the texts of run-time added textboxes - c#

I have an application where the user can add any number of tabpages depending on what he/she needs. These tabpages have identical controls (textboxes and labels).
The controls on each tabpages are named like this: (on tabpage1 the controls are named: txtServer1, txtPort1, txtUser1, txtDbName1. if the user clicks the 'add another connection button' the application creates a second tabpage and the controls will be named: txtServer2, txtPort2, txtUser2, txtDbName2) and so on...
for example if the user have multiple tabpages to set-up:
the user clicks the 'add another connection' and the another tabpage with identical controls has been created and the user fills it up with appropriate data:
same thing goes here:
here's the code for dynamically added tabpage with controls:
//when 'add another connection' button is clicked
private void btnAddConnection_Click(object sender, EventArgs e)
{
string tabTitle = "Connection " + (tabControl1.TabCount + 1).ToString();
TabPage tabPage = new TabPage(tabTitle);
tabControl1.TabPages.Add(tabPage);
}
//when another tabpage has been added to tabcontrol
private void tabControl1_ControlAdded(object sender, ControlEventArgs e)
{
//control instances
TextBox txtServer = new TextBox();
TextBox txtPort = new TextBox();
TextBox txtUser = new TextBox();
TextBox txtDbName = new TextBox();
Label lblServer = new Label();
Label lblPort = new Label();
Label lblUser = new Label();
Label lblDbName = new Label();
tabControl1.SelectedTab = tabControl1.TabPages[tabControl1.TabCount - 1]; //select the newly addded tabpage
tabControl1.SelectedTab.BackColor = tabPage1.BackColor; //tabpage background color
//lblServer Properties
lblServer.Location = lblServer1.Location;
lblServer.Text = lblServer1.Text;
lblServer.ForeColor = lblServer1.ForeColor;
lblServer.Name = "lblServer" + tabControl1.TabCount.ToString();
//lblPort Properties
lblPort.Location = lblPort1.Location;
lblPort.Text = lblPort1.Text;
lblPort.ForeColor = lblPort1.ForeColor;
lblPort.Name = "lblPort" + tabControl1.TabCount.ToString();
//lblUser Properties
lblUser.Location = lblUser1.Location;
lblUser.Text = lblUser1.Text;
lblUser.ForeColor = lblUser1.ForeColor;
lblUser.Name = "lblUser" + tabControl1.TabCount.ToString();
//lblDbName Properties
lblDbName.Location = lblDbName1.Location;
lblDbName.Text = lblDbName1.Text;
lblDbName.ForeColor = lblDbName1.ForeColor;
lblDbName.Name = "lblDbName" + tabControl1.TabCount.ToString();
//txtserver properties
txtServer.Location = txtServer1.Location;
txtServer.Width = txtServer1.Width;
txtServer.Height = txtServer1.Height;
txtServer.Font = txtServer1.Font;
txtServer.Name = "txtServer" + tabControl1.TabCount.ToString();
//txtport properties
txtPort.Location = txtPort1.Location;
txtPort.Width = txtPort1.Width;
txtPort.Height = txtPort1.Height;
txtPort.Font = txtPort1.Font;
txtPort.Name = "txtPort" + tabControl1.TabCount.ToString();
//txtuser properties
txtUser.Location = txtUser1.Location;
txtUser.Width = txtUser1.Width;
txtUser.Height = txtUser1.Height;
txtUser.Font = txtUser1.Font;
txtUser.Name = "txtUser" + tabControl1.TabCount.ToString();
//txtdbname properties
txtDbName.Location = txtDbName1.Location;
txtDbName.Width = txtDbName1.Width;
txtDbName.Height = txtDbName1.Height;
txtDbName.Font = txtDbName1.Font;
txtDbName.Name = "txtUser" + tabControl1.TabCount.ToString();
//add controls to tabpage
tabControl1.SelectedTab.Controls.Add(lblServer);
tabControl1.SelectedTab.Controls.Add(lblPort);
tabControl1.SelectedTab.Controls.Add(lblUser);
tabControl1.SelectedTab.Controls.Add(lblDbName);
tabControl1.SelectedTab.Controls.Add(txtServer);
tabControl1.SelectedTab.Controls.Add(txtPort);
tabControl1.SelectedTab.Controls.Add(txtUser);
tabControl1.SelectedTab.Controls.Add(txtDbName);
}
When the user clicks the save button, I want the application to read each text in the textboxes (except for that url text) so that I can save it to a configuration file.
all I can think of is this
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string connection;
for (int i = 1; i <= tabControl1.TabCount; i++ )
{
connection = "server=" + txtServer[i].Text + ";port=" txtPort[i].Text + ";user=" + txtUser[i].Text + ";dbname=" + txtDbName[i];
//save to config file code goes here...
}
}
and I know this is not correct.
any solution for this? thanks :)

This is the simplest way you can try this just use below function to get text from control in tabpage
public string getValue(string controlName, TabPage selectedTab)
{
if (selectedTab.Controls.ContainsKey(controlName)){
TextBox selectedtb = (TextBox)selectedTab.Controls[controlName];
return selectedtb.Text;
}
else
return null;
}
and in your save code use it like below
string connection;
int i = 1;
TabControl.TabPageCollection pages = tabControl1.TabPages;
foreach (TabPage page in pages)
{
connection = "server=" + getValue("txtServer"+i,page) + ";port=" +getValue("txtPort"+i,page) + ";user=" + getValue("txtUser"+i,page) + ";dbname=" + getValue("txtDbName"+i,page);
i++;
//save to config file code goes here...
}

txtServer[i].Text it's true but You have not defined an array.
You can do it like this
//global
List<TextBox> txtServerList= new List<TextBox>();
private void tabControl1_ControlAdded(object sender, ControlEventArgs e)
{
txtServer.Location = txtServer1.Location;
txtServer.Width = txtServer1.Width;
txtServer.Height = txtServer1.Height;
txtServer.Font = txtServer.Font;
txtServer.Name = "txtServer" + tabControl1.TabCount.ToString();
txtServerList.Add(txtServer)
.
.
.
}
Finally
for (int i = 1; i <= tabControl1.TabCount; i++ )
{
connection=txtServerList.get(i).Text + ......
}

You could just loop over the controls and find the matching name, something like this:
foreach(var page in tabControl1.TabPages){
var server = ProcessControls(page.Controls, "txtServer");
//... continue with the others
}
private TextBox ProcessControls(Control ctrlContainer, string name)
{
foreach (Control ctrl in ctrlContainer.Controls)
{
if (ctrl.GetType() == typeof(TextBox))
{
if(ctrl.Name.StartsWith(name))
return (TextBox)ctrl;
}
}
}

You can use an ArrayList to store and access all dynamically added controls. Set a name for each dynamically added controls. It can be based on the size of ArrayList.
I will not show the exact systax of c#.
first
declare an ArrayList or List(Type Safe)
List<Button> buttons = new List<Button>();
We just created a storage for our buttons that will be added at runtime.
void your_event (some parameters) {
Button temp = new Button("Hello");
temp.Name="button_name";
YourMainPanel.Controls.add(temp);
//after creating your button add it to the parent container. of any control where you want this button to be added.
//you can also set the coordinates of the button if you like
//after creating the button we need to add it to our List so that we can
//access it later, since the value of the 'temp' will change after this
//event was invoked in the future.
buttons.add(temp);
}
There are several ways to get the items in List<T>. One is by using index.
void someMethod(some parameters) {
Button button = buttons.ElementAt(index);
}

Related

Retrieve value from dynamic dropdownlist in placeholder C#

I have dynamic drop down lists that are created based on what's selected in the list box.. When clicking confirm this is when the drop down lists are created. Clicking save is where I attempt to retrieve the values. However I am unable to retrieve that values that are in the drop down lists.
Code:
protected void btnConfirm_Click(object sender, EventArgs e)
{
int ID = 0;
foreach (string value in values)
{
MyStaticValues.alEdit.Add(value);
CreateEditForm(value, ID);
ID += 1;
}
if (values.count != 0)
{
btnSave.Visible = true;
btnConfirm.Enabled = false;
}
}//End of btnConfirm_Click
protected void CreateEditForm(string Value, int ID)
{//Creates an edit form for the value inserted.
string name = value;
//This part adds a header
phEditInventory.Controls.Add(new LiteralControl("<h2>" + name + "</h2>"));
phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));
//Create a label
Label lblName = new Label();
lblName.Text = "Name";
lblName.ID = "lblName" + ID;
lblName.CssClass = "control-label";
//Create a Drop Down List
DropDownList ddlName = new DropDownList();
ddlName.ID = "ddlName" + ID;
ddlName.CssClass = "form-control";
//Set default N/A Values For Drop Down List
ddlName.Items.Add(new ListItem("N/A", Convert.ToString("0")));
//The Rest of the Values are populated with the database
//Adds the controls to the placeholder
phEditInventory.Controls.Add(lblName);
phEditInventory.Controls.Add(ddlName);
phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));
} //End of CreateEditForm
protected void btnSave_Click(object sender, EventArgs e)
{
string name = "";
try
{
for (int i = 0; i < MyStaticValues.alEdit.Count; i++)
{
string nameID = "ddlName" + i.ToString();
DropDownList ddlName = (DropDownList)phEditInventory.FindControl(nameID);
name = ddlName.SelectedValue.ToString();
}
}
catch (Exception ex)
{
}
phEditInventory.Visible = false;
btnSave.Visible = false;
MyStaticValues.alEdit.Clear();
}//End of btnSave_Click Function
Your problem is that the dynamically created dropdown lists are not maintained on postback. When you click the Save button, a postback occurs, and the page is re-rendered without the dynamically created dropdowns. This link may help.
Maintain the state of dynamically added user control on postback?

Saving User Input in a Dynamically Created Form

I'm trying to get the values that a user inputs in a textbox in a dynamically generated form. Another method loads and parses an XML file and creates an object that has specific getters and setters for the settings that it finds in the file (Server, Port, Title, etc.).
The dynamic form is created using labels and textboxes like this. It was designed only to display the information from the XML file, and I am trying to implement a system that allows users to edit the information before saving it again to the file. I'm doing alright with the methods to save and edit the XML file, but I'm lost for how to associate the input in any given textbox with the associated label representing the key in the XML file to change.
Below is the current form implementation where the labels and textboxes are created as part of a foreach loop. I tried creating textbox.Leave eventHandler to track when the user has finished changing a value, but I can't figure out how to know what label it is associated with.
var sortedSettings = new SortedDictionary<string, string>(theSettings.Settings);
int numSettings = sortedSettings.Count;
TextBox[] txt = new TextBox[numSettings];
Label[] label = new Label[numSettings];
int labelSpacing = this.labelSecond.Top - this.labelTop.Bottom;
int textSpacing = this.textBoxSecond.Top - this.textBoxTop.Bottom;
int line = 0;
foreach (KeyValuePair<string, string> key in sortedSettings)
{
label[line] = new Label();
label[line].Text = key.Key;
label[line].Left = this.labelTop.Left;
label[line].Height = this.labelTop.Height;
label[line].Width = this.labelTop.Width;
txt[line] = new TextBox();
txt[line].Text = key.Value;
txt[line].Left = this.textBoxTop.Left;
txt[line].Height = this.textBoxTop.Height;
txt[line].Width = this.textBoxTop.Width;
txt[line].ReadOnly = false;
// Attach and initialize EventHandler for template textbox on Leave
txt[line].Leave += new System.EventHandler(txt_Leave);
if (line > 0)
{
label[line].Top = label[line - 1].Bottom + labelSpacing;
txt[line].Top = txt[line - 1].Bottom + textSpacing;
}
else
{
label[line].Top = this.labelTop.Top;
txt[line].Top = this.textBoxTop.Top;
}
this.Controls.Add(label[line]);
this.Controls.Add(txt[line]);
line++;
}
private void txt_Leave(object sender, EventArgs e)
{
String enteredVal = sender;
FormUtilities.FindAndCenterMsgBox(this.Bounds, true, "EventChecker");
MessageBox.Show("The current value of LABEL is " + enteredVal, "EventChecker");
}
One option is to use TextBox.Tag property.
Example (in foreach loop):
txt[line] = new TextBox();
txt[line].Text = key.Value;
txt[line].Tag = label[line];
To get label associated with TextBox:
TextBox t = txt[0];
Label l = t.Tag as Label;
//Here is how you identify textbox which generated the event.
private void txt_Leave(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
//..
}

Link button to display grid view asp.net dynamically

I have to display n grids, n is variable, then I dont know how many grids I'll have.
My problem is, I have to init this grids with Visible false and when click in a button show the grid specific for that button, then how can I link a button to a gridview?
My code that generate the grids:
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view"+i;
grv.Visible = false;
grv.DataSource = dt;
grv.DataBind();
Label lblBlankLines = new Label();
lblBlankLines.Text = "<br /><br />";
Label lblTipo = new Label();
string tipoOcorrencia = lst[0]["DESC_OCORRENCIA"].ToString();
tipoOcorrencia = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(tipoOcorrencia);
int quantidade = lst.Count;
lblTipo.Text = tipoOcorrencia + ": " + quantidade;
LinkButton lkBtn = new LinkButton();
lkBtn.ID = "link_button"+i;
lkBtn.Text = "+";
place_grids.Controls.Add(lblBlankLines);
place_grids.Controls.Add(lkBtn);
place_grids.Controls.Add(lblTipo);
place_grids.Controls.Add(grv);
place_grids.DataBind();
i++;
}
Thanks in advance.
Modify your foreach loop as below.
private void GenerateControls()
{
int i = 0;
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view" + i;
//grv.Visible = false;//Commented as the grid needs be generated on client side, in order to make it visible from JavaScript/jQuery
grv.Attributes.Add("style", "display:none;");
grv.DataSource = dt;
grv.DataBind();
//Adding dynamic link button
LinkButton lnkButton = new LinkButton();
lnkButton.Text = "button " + i;
//lnkButton.Click += new EventHandler(lnkButton_Click);
lnkButton.ID = "lnkButton" + i;
lnkButton.OnClientClick = "ShowGrid('" + grv.ClientID + "');";
Label lblTipo = new Label();
lblTipo.Text = "text " + i;
lblTipo.ID = "lbl" + i;
tempPanel.Controls.Add(lblTipo);
tempPanel.Controls.Add(grv);
tempPanel.Controls.Add(lnkButton);
tempPanel.DataBind();
i++;
}
}
Then you will have to add a link button click event as below, if you want server side event to fire. (Un-comment the line where event handler is assigned to link button.)
protected void lnkButton_Click(Object sender, EventArgs e)
{
LinkButton lnkButton = (LinkButton)sender;
String index = lnkButton.ID.Substring(lnkButton.ID.Length - 1);
GridView grv = (GridView)tempPanel.FindControl("grid_view" + index);
grv.Visible = true;
}
You will need to add all dynamically added controls in the Page_Init event for maintaining their state. Refer below links can be useful.
Dynamically Created Controls losing data after postback
ViewState in Dynamic Control
Call method GenerateControls from Page_Init event as below.
protected void Page_Init(object sender, EventArgs e)
{
GenerateControls();
}
EDIT :
JavaScript function...
function ShowGrid(gridID) {
document.getElementById(gridID).style.display = ''
}
I have kept the server side click event as it is. But I have commented the line where the event handler is assigned to the link button.

Gridview Edit/Update is not working?

Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.

image control with radio buttons

I need a control which can hold an image and two radio buttons, like the one we have when we upload a pictures on fb / orkut.
1. Image
2. Delete radio button.
3. Cover radio button.[Set this image as cover of album]
i have created a user control with these three things.
On my aspx page on click of a button i need to add this user control.
Means, user will select the image using FileUpload and when he clicks on the button this user control should be loaded.
I am able to load the control. Check the following code.
<code>
<pre lang="cs">
protected void btnAddURL_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//ItemList is an array list used to store the filename.
ItemList.Add(FileUpload1.FileName);
showImage();
}
}</pre>
public void showImage()
{
PlaceHolder p = new PlaceHolder();
//Create Thumbnail
FileUpload1.SaveAs(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\" + FileUpload1.FileName);
System.Drawing.Image img1 = System.Drawing.Image.FromFile(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\" + FileUpload1.FileName);
System.Drawing.Image bmp2 = img1.GetThumbnailImage(100, 100, null, IntPtr.Zero);
bmp2.Save(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\thumbnail\L\" + FileUpload1.FileName);
//Load the images selected by user
for (int i = 0; i <= ItemList.Count - 1; i++)
{
Control MyUserControl;
// Load user control dynamically
MyUserControl = LoadControl("MyControl.ascx");
MyUserControl.ID = "MyUserControl" + cnt++;
// Assign URL
Image MyImage = (Image)MyUserControl.FindControl("Image1");
// MyImage.ID = "Image" + cnt;
MyImage.ImageUrl = "~/SaveImage/thumbnail/L/" + ItemList[i].ToString();
// Add control to panel.
p.Controls.Add(MyUserControl);
Panel2.Controls.Add(p);
</code>
Problem :
1> All images come on new line i want them next to each other.
2> How to detect which radio button is clicked as i have more than one images, and all have radio buttons.
3> How to capture click of radio button from aspx page?
4> If there is some other way to achieve this let me know.
Searched on google but could not find a solution for this. :(
Thanks in advance.
[Code After Changes]
in ascx file i have added following code
public event EventHandler rd_ClickDemo;
protected void deleteimage_CheckedChanged(object sender, EventArgs e)
{
rd_ClickDemo(sender, e);
}
protected void setascover_CheckedChanged(object sender, EventArgs e)
{
rd_ClickDemo(sender, e);
}
In aspx file on click of a button i am doing the following.
protected void btnAddURL_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// Add file name to array list
ItemList.Add(FileUpload1.FileName);
//Add The URL in a text box.
txtAddURL.Text = txtAddURL.Text + System.Environment.NewLine + System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);
//Image1.ImageUrl = System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);
//this.Button1_Click(this, e);
showImage();
}
}
public void showImage()
{
PlaceHolder p = new PlaceHolder();
// Create a Thumbnail Image.
FileUpload1.SaveAs(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\" + FileUpload1.FileName);
System.Drawing.Image img1 = System.Drawing.Image.FromFile(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\" + FileUpload1.FileName);
System.Drawing.Image bmp2 = img1.GetThumbnailImage(100, 100, null, IntPtr.Zero);
bmp2.Save(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\thumbnail\L\" + FileUpload1.FileName);
//Load all images from array list.
for (int i = 0; i <= ItemList.Count - 1; i++)
{
// Load user control dynamically
MyUserControl = LoadControl("MyControl.ascx");
MyUserControl.ID = "MyUserControl" + cnt++;
// Find Radio Button
RadioButton rdb1 = (RadioButton)MyUserControl.FindControl("deleteimage");
RadioButton rdb2 = (RadioButton)MyUserControl.FindControl("setascover");
//Attach Group Name.
rdb1.GroupName = "G1" + cnt.ToString();
rdb1.ID = "Rb_ID_D" + cnt.ToString();
rdb1.AutoPostBack = true;
rdb1.CheckedChanged +=new EventHandler(rdb1_CheckedChanged);
//Attach Group Name.
rdb2.GroupName = "G1"+ cnt.ToString();
rdb2.ID = "Rb_ID" + cnt.ToString();
rdb2.AutoPostBack = true;
rdb2.CheckedChanged += new EventHandler(rdb1_CheckedChanged);
//Image MyImage = (Image)MyUserControl.FindControl("Image1");
// MyImage.ID = "Image" + cnt;
//Attach URL to Image.
Image MyImage = (Image)MyUserControl.FindControl("Image1");
MyImage.ImageUrl = "~/SaveImage/thumbnail/L/" + ItemList[i].ToString();
p.Controls.Add(MyUserControl);
Panel2.Controls.Add(p);
}
}
Still i am not able to trigger the radiobutton_CheckedChanged event.
Please Help.
Ok so here is your solution for first problem:
1> All images come on new line i want them next to each other.
Ans: You can do so in CSS of your custom control's div block, just set the float to left like this
style="display:block;float:right;"
2> How to detect which radio button is clicked as i have more than one images, and all have radio buttons.
Ans: You can get the control which host your RadioButton so u can use NamingContainer property of the Radio button to get the hosting control, which in your case must be you custom control.
3> How to capture click of radio button from aspx page?
Ans: Do the following in your code:
first when you loop to add You custom control to your Panel2 attach a groupname and a event handler to the RadioButton. (Assuming you already have your radio buttons in your custom control) and then handle the CheckedChanged Event (i am using anonymous delegate for handling event)
RadioButton rdb1 = (RadioButton)MyUserControl.FindControl("deleteimage");
RadioButton rdb2 = (RadioButton)MyUserControl.FindControl("setascover");
rd1.GrouprdoSelect2.GroupName = "radiobutton" + i.ToString() ;
rd1.ID = "radiobutton" + i.ToString() + i.ToString() + Convert.ToString(1);
rd1.AutoPostBack = true;
rd1.CheckedChanged += (thesender, ev) => {
RadioButton rb = (RadioButton) thesender;
MyUserControl mcl = rb.NamingContainer as MyUserControl;
//Perform your task based on the fact of mcl.ID
}
rd2.GrouprdoSelect2.GroupName = "radiobutton" + i.ToString() ;
rd2.ID = "radiobutton" + i.ToString() + i.ToString() + Convert.ToString(2);
rd2.AutoPostBack = true;
rd2.CheckedChanged += (thesender, ev) => {
RadioButton rb = (RadioButton) thesender;
MyUserControl mcl = rb.NamingContainer as MyUserControl;
//Perform your task based on the fact of mcl.ID
}

Categories