This code works fine for first two times,i.e ,when i click on "Add more solution" it creates a new row and controls respectively but when i click on "Add more solution" for the third time and "add step" button respective to that,,it creates problem.
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < TotalNumberAdded; i++)
{
AddControls((i + 1), plcSolution);
}
for (int i = 0; i < TotalNumberSolAdded; i++)
{
AddMoreControls((i + 1), plcAddMoreSolution, 1);
Button b = (Button)plcAddMoreSolution.FindControl("btn" + (i+1));
for (int j = 0; j < TotalNumberSolStepAdded; j++)
{
AddMoreStepControls((j + 1), plcAddMoreSolution);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
TotalNumberAdded++;
AddControls(TotalNumberAdded, plcSolution);
}
private void AddControls(int controlNumber, PlaceHolder plc)
{
TextBox txtBoxSolution = new TextBox();
Label lblSolution = new Label();
txtBoxSolution.ID = "txtBoxSolution" + controlNumber;
txtBoxSolution.TextMode = TextBoxMode.MultiLine;
txtBoxSolution.Width = 470;
txtBoxSolution.Height = 50;
lblSolution.ID = "lblSolution" + controlNumber;
lblSolution.Text = "Step " + (controlNumber + 1) + ": ";
lblSolution.Width = 200;
plc.Controls.Add(lblSolution);
plc.Controls.Add(txtBoxSolution);
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void btnAlternate_Click(object sender, EventArgs e)
{
lblSol.Text = "Solution 1";
string str = (string)ViewState["btnId"];
if (str != null)
{
btn = (Button)plcAddMoreSolution.FindControl(str);
btn.Visible = false;
}
btnAdd.Visible = false;
TotalNumberSolAdded++;
AddMoreControls(TotalNumberSolAdded, plcAddMoreSolution,1);
}
protected int TotalNumberSolAdded
{
get { return (int)(ViewState["TotalNumberSolAdded"] ?? 0); }
set { ViewState["TotalNumberSolAdded"] = value; }
}
private void AddMoreControls(int controlNumber, PlaceHolder plc,int n)
{
TextBox txtBoxMoreSolution = new TextBox();
Label lblMoreSolution = new Label();
btn = new Button();
btn.Text = "add step";
btn.ID = "btn" + controlNumber;
btn.Click += new EventHandler(btn_Click);
ViewState["btnId"] = btn.ID;
Label lbl = new Label();
lbl.Text = "soltuion" + (controlNumber + 1);
lbl.ID = "moreSolution" + (controlNumber + 1);
lbl.Font.Size = 20;
lbl.Font.Underline = true;
txtBoxMoreSolution.ID = "txtBoxMoreSolution" + controlNumber;
txtBoxMoreSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreSolution.Width = 470;
txtBoxMoreSolution.Height = 50;
lblMoreSolution.ID = "lblMoreSolution" + controlNumber;
lblMoreSolution.Text = "Step " + n + ": ";
lblMoreSolution.Width = 200;
plc.Controls.Add(lbl);
plc.Controls.Add(lblMoreSolution);
plc.Controls.Add(txtBoxMoreSolution);
plc.Controls.Add(btn);
}
private void btn_Click(object sender, EventArgs e)
{
TotalNumberSolStepAdded++;
AddMoreStepControls(TotalNumberSolStepAdded, plcAddMoreSolution);
}
protected int TotalNumberSolStepAdded
{
get { return (int)(ViewState["TotalNumberSolStepAdded"] ?? 0); }
set { ViewState["TotalNumberSolStepAdded"] = value; }
}
private void AddMoreStepControls(int controlNumber, PlaceHolder plc)
{
TextBox txtBoxMoreStepSolution = new TextBox();
Label lblMoreStepSolution = new Label();
txtBoxMoreStepSolution.ID = "txtBoxMoreStepSolution" + controlNumber;
txtBoxMoreStepSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreStepSolution.Width = 470;
txtBoxMoreStepSolution.Height = 50;
lblMoreStepSolution.ID = "lblMoreStepSolution" + controlNumber;
lblMoreStepSolution.Text = "Step " + (controlNumber +1) + ": ";
lblMoreStepSolution.Width = 200;
plc.Controls.Add(lblMoreStepSolution);
plc.Controls.Add(txtBoxMoreStepSolution);
}
this code will help you.. it works fine...
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < TotalNumberAdded; i++)
{
AddControls(i + 1);
}
for (int i = 0; i < TotalNumberSolAdded; i++)
{
AddMoreControls((i + 1), 1);
DataTable dt = (DataTable)ViewState["t"];
if (dt != null)
{
if ((TotalNumberSolAdded - dt.Rows.Count == 1) && (counter1 == dt.Rows.Count))
{
break;
}
if (i != 0)
{
for (int k = 0; k <= i; k++)
{
int a1 = int.Parse(dt.Rows[k][0].ToString());
b = a1 + b;
}
start = b - int.Parse(dt.Rows[i][0].ToString());
}
else
{
b = int.Parse(dt.Rows[i][0].ToString());
start = 0;
}
for (int j = start; j < b; j++)
{
counter++;
AddMoreStepControls((j + 1), counter);
}
b = 0;
counter = 0;
counter1++;
}
}
}
private void AddControls(int controlNumber)
{
TextBox txtBoxSolution = new TextBox();
Label lblSolution = new Label();
txtBoxSolution.ID = "txtBoxSolution" + controlNumber;
txtBoxSolution.TextMode = TextBoxMode.MultiLine;
txtBoxSolution.Width = 470;
txtBoxSolution.Height = 50;
lblSolution.ID = "lblSolution" + controlNumber;
lblSolution.Text = "Step " + (controlNumber + 1) + ": ";
lblSolution.Width = 200;
plcSolution.Controls.Add(lblSolution);
plcSolution.Controls.Add(txtBoxSolution);
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void btnAlternate_Click(object sender, EventArgs e)
{
Number = 0;
lblSol.Text = "Solution 1";
string str = (string)ViewState["btnId"];
if (str != null)
{
btn = (Button)plcAddMoreSolution.FindControl(str);
btn.Visible = false;
}
btnAdd.Visible = false;
TotalNumberSolAdded++;
AddMoreControls(TotalNumberSolAdded, 1);
}
protected int TotalNumberSolAdded
{
get { return (int)(ViewState["TotalNumberSolAdded"] ?? 0); }
set { ViewState["TotalNumberSolAdded"] = value; }
}
private void AddMoreControls(int controlNumber, int n)
{
TextBox txtBoxMoreSolution = new TextBox();
Label lblMoreSolution = new Label();
btn = new Button();
btn.Text = "add step";
btn.ID = "btn" + controlNumber;
btn.Click += new EventHandler(btn_Click);
ViewState["btnId"] = btn.ID;
Label lbl = new Label();
lbl.Text = "Soltuion" + (controlNumber + 1);
lbl.ID = "moreSolution" + (controlNumber + 1);
lbl.Font.Size = 20;
lbl.Font.Underline = true;
lbl.Font.Bold = true;
txtBoxMoreSolution.ID = "txtBoxMoreSolution" + controlNumber;
txtBoxMoreSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreSolution.Width = 470;
txtBoxMoreSolution.Height = 50;
lblMoreSolution.ID = "lblMoreSolution" + controlNumber;
lblMoreSolution.Text = "Step " + n + ": ";
lblMoreSolution.Width = 200;
plcAddMoreSolution.Controls.Add(lbl);
plcAddMoreSolution.Controls.Add(lblMoreSolution);
plcAddMoreSolution.Controls.Add(txtBoxMoreSolution);
plcAddMoreSolution.Controls.Add(btn);
}
private void btn_Click(object sender, EventArgs e)
{
TotalNumberSolStepAdded++;
Number++;
string str = (string)ViewState["btnId"];
if (str != null)
{
string resultString = Regex.Match(str, #"\d+").Value;
a = int.Parse(resultString);
table = (DataTable)ViewState["t"];
if (table == null)
{
DataTable table1 = new DataTable();
table1.Columns.Add("count", typeof(int));
dr = table1.NewRow();
table1.Rows.Add(dr);
table1.Rows[a - 1]["count"] = Number;
table1.AcceptChanges();
ViewState["t"] = table1;
}
else
{
if (a != table.Rows.Count)
{
dr = table.NewRow();
table.Rows.Add(dr);
}
table.Rows[a - 1]["count"] = Number;
table.AcceptChanges();
ViewState["t"] = table;
}
}
AddMoreStepControls(TotalNumberSolStepAdded, Number);
}
protected int TotalNumberSolStepAdded
{
get { return (int)(ViewState["TotalNumberSolStepAdded"] ?? 0); }
set { ViewState["TotalNumberSolStepAdded"] = value; }
}
protected int Number
{
get { return (int)(ViewState["Number"] ?? 0); }
set { ViewState["Number"] = value; }
}
private void AddMoreStepControls(int controlNumber, int counter)
{
TextBox txtBoxMoreStepSolution = new TextBox();
Label lblMoreStepSolution = new Label();
txtBoxMoreStepSolution.ID = "txtBoxMoreStepSolution" + controlNumber;
txtBoxMoreStepSolution.TextMode = TextBoxMode.MultiLine;
txtBoxMoreStepSolution.Width = 470;
txtBoxMoreStepSolution.Height = 50;
lblMoreStepSolution.ID = "lblMoreStepSolution" + controlNumber;
lblMoreStepSolution.Text = "Step " + (counter + 1) + ": ";
lblMoreStepSolution.Width = 200;
plcAddMoreSolution.Controls.Add(lblMoreStepSolution);
plcAddMoreSolution.Controls.Add(txtBoxMoreStepSolution);
}
Related
This is what I have...
private void blablabla()
{
for (int i=1; i<count+1; i++)
{
int item_number = panelBoats.Controls.Count;
CheckBox chb = new CheckBox();
chb.Name = "CheckBoxBoat" + i.ToString();
chb.Text = "Boat " + i.ToString();
chb.Location = new Point(10, item_number * 15);
panelBoats.Controls.Add(chb);
}
}
This is what I wish would work...
private void plotMarker(PaintEventArgs e)
{
if(CheckBoxBoat0.Checked)
{
MessageBox.Show('Yehaaa');
}
}
Well what you can do is have a list of checkbox in your class
List<CheckBox> myCheckBoxList = new List<CheckBox>();
And when you create a checkbox you add it to the list
private void blablabla()
{
for (int i = 1; i < count + 1; i++)
{
int item_number = panelBoats.Controls.Count;
CheckBox chb = new CheckBox();
chb.Name = "CheckBoxBoat" + i.ToString();
chb.Text = "Boat " + i.ToString();
chb.Location = new Point(10, item_number * 15);
panelBoats.Controls.Add(chb);
//Add the checkBox to the list
myCheckBoxList.add(chb);
}
}
And then you can access it by using the list
private void plotMarker(PaintEventArgs e)
{
if (myCheckBoxList[0].Checked)
{
MessageBox.Schow('Yehaaa');
}
}
I have dynamically created buttons, eg 1,2,3,4,5,6,7,8; if I select 2,3,4, then I can't select 6 and skip 4. Or you can say, if I select 2,3,4,5,6 then if want to deselect 4 then I have to deselect 5 and 6 first.
private void GetControls()
{
count++;
for (int i = 10; i < 12; i++)
{
for (int j = 0; j < 60; j += 15)
{
Button btn = new Button();
btn.Text = i + "-" + j;
btn.ID = i + "." + j;
btn.Command += new CommandEventHandler(this.btn_Click);
// btn.Click += btn_Click;
flag = true;
btn.CommandName = i + "-" + j;
if (count==1)
{
PlaceHolder1.Controls.Add(btn);
List<string> createdControls = Session["Controls"] != null ? Session["Controls"] as List<string> : new List<string>();
if (!createdControls.Contains(btn.ID)) createdControls.Add(btn.ID);
Session["Controls"] = createdControls;
}
}
}
}
private void btn_Click(object sender, CommandEventArgs e)
{
count++;
//ResetButton();
Button btn = sender as Button;
string ID = (sender as Button).ID;
string text = (sender as Button).Text;
ResetButton(Convert.ToDouble(ID));
Label1.Text = " Congrates! Your meeting time has been sheduled between " + ID;
} //}
private void ResetButton(double selectedButtonID)
{
List<string> createdControls = Session["Controls"] != null ? Session["Controls"] as List<string> : new List<string>();
TimeSpan timespan = TimeSpan.FromHours(selectedButtonID);
string currentSelectedTime = timespan.ToString("h\\:mm");
foreach (string buttonID in createdControls)
{
if (!string.IsNullOrEmpty(buttonID))
{
int comparisonResult = timespan.CompareTo(TimeSpan.FromHours(Convert.ToDouble(buttonID)));
Button button = Page.FindControl(buttonID) as Button;
if (button != null && comparisonResult >= 0 )
{
if (button.BackColor == Color.Yellow)
{
button.BackColor = System.Drawing.Color.GhostWhite;
}
else if (button.BackColor == Color.GhostWhite)
{
button.BackColor = System.Drawing.Color.GhostWhite;
}
else
{
button.BackColor = System.Drawing.Color.Yellow;
}
I have write code as following :
protected void Page_Load(object sender, EventArgs e)
{
Literal lt;
Label lb;
//Get ContentPlaceHolder
ContentPlaceHolder content = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
pnlStartDate = new Panel();
pnlStartDate.ID = "pnlStartDate";
// pnlStartDate.BorderWidth = 1;
pnlStartDate.Width = 100;
grvWorkOrder.Rows[rowIndex].Cells[13].Controls.Add(pnlStartDate);
lt = new Literal();
lt.Text = "<br />";
grvWorkOrder.Rows[rowIndex].Cells[13].Controls.Add(lt);
//Button To add TextBoxes
Button btnAddTxt = new Button();
btnAddTxt.ID = "btnAddTxt";
btnAddTxt.Text = "Add TextBox";
btnAddTxt.CausesValidation = false;
btnAddTxt.Click += new System.EventHandler(btnAddTextbox_Click);
grvWorkOrder.Rows[rowIndex].Cells[10].Controls.Add(btnAddTxt);
if (IsPostBack)
{
RecreateDateControls("txtStartDateDynamic", "TextBox", "img1StartDateDynamic", "ImageButton", "ceStartDateDynamic", "CalendarExtender");
}
rowIndex++;
}
}
}
}
protected void btnAddTextbox_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.ID == "btnAddTxt")
{
Literal lt = new Literal();
lt.Text = "<br />";
int cntStartDate = FindOccurence("txtStartDateDynamic");
TextBox txt4 = new TextBox();
txt4.ID = "txtStartDateDynamic-" + Convert.ToString(cntStartDate + 1);
txt4.Width = 90;
pnlStartDate.Controls.Add(txt4);
int cntImgStartDate = FindOccurence("img1StartDateDynamic");
ImageButton img1StartDateDynamic = new ImageButton();
img1StartDateDynamic.ID = "img1StartDateDynamic-" + Convert.ToString(cntImgStartDate + 1);
img1StartDateDynamic.ImageUrl = "Images/calender.jpg";
img1StartDateDynamic.Width = 25;
img1StartDateDynamic.CausesValidation = false;
pnlStartDate.Controls.Add(img1StartDateDynamic);
int cntCeStartDate = FindOccurence("ceStartDateDynamic");
CalendarExtender ceStartDateDynamic = new CalendarExtender();
ceStartDateDynamic.ID = "ceStartDateDynamic-" + Convert.ToString(cntCeStartDate + 1);
ceStartDateDynamic.Enabled = true;
ceStartDateDynamic.TargetControlID = "txtStartDateDynamic-" + Convert.ToString(cntCeStartDate + 1);
ceStartDateDynamic.PopupButtonID = "img1StartDateDynamic-" + Convert.ToString(cntCeStartDate + 1);
ceStartDateDynamic.Format = "yyyy/MM/dd";
pnlStartDate.Controls.Add(ceStartDateDynamic);
pnlStartDate.Controls.Add(lt);
}
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateDateControls(string ctrlPrefix1, string ctrlType1, string ctrlPrefix2, string ctrlType2, string ctrlPrefix3, string ctrlType3)
{
string[] ctrls1 = Request.Form.ToString().Split('&');
string[] ctrls2 = Request.Form.ToString().Split('&');
string[] ctrls3 = Request.Form.ToString().Split('&');
int cnt1 = FindOccurence(ctrlPrefix1);
int cnt2 = FindOccurence(ctrlPrefix2);
int cnt3 = FindOccurence(ctrlPrefix3);
if (cnt1 > 0 && cnt2 > 0 && cnt3 > 0)
{
Literal lt;
for (int k = 1; k <= cnt1; k++)
{
for (int i = 0; i < ctrls1.Length ; i++)
{
if (ctrls1[i].Contains(ctrlPrefix1 + "-" + k.ToString()))
{
string ctrlName1 = ctrls1[i].Split('=')[0];
string ctrlValue1 = ctrls1[i].Split('=')[1];
if (ctrls1[i].Contains(ctrlPrefix2 + "-" + k.ToString()))
{
string ctrlName2 = ctrls1[i].Split('=')[0];
if (ctrls1[i].Contains(ctrlPrefix3 + "-" + k.ToString()))
{
string ctrlName3 = ctrls1[i].Split('=')[0];
if (ctrlType1 == "TextBox" && ctrlPrefix1 == "txtStartDateDynamic" && ctrlType2 == "ImageButton" && ctrlPrefix2 == "img1StartDateDynamic" && ctrlType3 == "CalendarExtender" && ctrlPrefix3 == "ceStartDateDynamic")
{
TextBox txt4 = new TextBox();
txt4.ID = ctrlName1;
txt4.Text = ctrlValue1;
txt4.Width = 90;
pnlStartDate.Controls.Add(txt4);
ImageButton img1StartDateDynamic = new ImageButton();
img1StartDateDynamic.ID = ctrlName2;
img1StartDateDynamic.ImageUrl = "Images/calender.jpg";
img1StartDateDynamic.Width = 25;
img1StartDateDynamic.CausesValidation = false;
pnlStartDate.Controls.Add(img1StartDateDynamic);
CalendarExtender ceStartDateDynamic = new CalendarExtender();
ceStartDateDynamic.ID = ctrlName3;
ceStartDateDynamic.Enabled = true;
ceStartDateDynamic.TargetControlID = ctrlName1;
ceStartDateDynamic.PopupButtonID = ctrlName2;
ceStartDateDynamic.Format = "yyyy/MM/dd";
pnlStartDate.Controls.Add(ceStartDateDynamic);
lt = new Literal();
lt.Text = "<br />";
pnlStartDate.Controls.Add(lt);
}
}
}
}
break;
}
}
}
}
But the problem is in RecreateDateControls() function ImageButton Counter cnt2 is zero therefore previous controls are not recreated what should i do for it.
go through the link..
create Dynamic Controls
In the first method I'm creating a matrix of textboxes and in another (Button_click) method. I need to take the values of textboxes from the Button_Click method and then do something with them. I don't know how interact with just created values(the names are also new). But I know that I can't use t[j].
private void vsematrici_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedIndex = vsematrici.SelectedIndex+2;
StackPanel[] v = new StackPanel[selectedIndex];
for (int i = 0; i < selectedIndex; i++)
{
v[i] = new StackPanel();
v[i].Name = "matrixpanel" + i;
v[i].Orientation = Orientation.Horizontal;
TextBox[] t = new TextBox[selectedIndex];
for (int j = 0; j < selectedIndex; j++)
{
t[j] = new TextBox();
t[j].Name = "a" + (i + 1) + (j + 1);
t[j].Text = "a" + (i + 1) + (j + 1);
v[i].Children.Add(t[j]);
Thickness m = t[j].Margin;
m.Left = 1;
m.Bottom = 1;
t[j].Margin = m;
InputScope scope = new InputScope();
InputScopeName name = new InputScopeName();
name.NameValue = InputScopeNameValue.TelephoneNumber;
scope.Names.Add(name);
t[j].InputScope = scope;
}
mainpanel.Children.Add(v[i]);
}
Button button1 = new Button();
button1.Content = "Найти определитель";
button1.Click += Button_Click;
mainpanel.Children.Add(button1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Double sa11v = Convert.ToDouble(t[j].Text);
}
Sorry for my English, I'm from Russia :)
you could create a member variable that is used outside the event in which you have created TextBox Array-
TextBox[] _t = null;
private void vsematrici_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedIndex = vsematrici.SelectedIndex + 2;
StackPanel[] v = new StackPanel[selectedIndex];
for (int i = 0; i < selectedIndex; i++)
{
v[i] = new StackPanel();
v[i].Name = "matrixpanel" + i;
v[i].Orientation = Orientation.Horizontal;
_t = new TextBox[selectedIndex];
for (int j = 0; j < selectedIndex; j++)
{
_t[j] = new TextBox();
_t[j].Name = "a" + (i + 1) + (j + 1);
_t[j].Text = "a" + (i + 1) + (j + 1);
v[i].Children.Add(_t[j]);
Thickness m = t[j].Margin;
m.Left = 1;
m.Bottom = 1;
_t[j].Margin = m;
InputScope scope = new InputScope();
InputScopeName name = new InputScopeName();
name.NameValue = InputScopeNameValue.TelephoneNumber;
scope.Names.Add(name);
_t[j].InputScope = scope;
}
mainpanel.Children.Add(v[i]);
}
Button button1 = new Button();
button1.Content = "Найти определитель";
button1.Click += Button_Click;
mainpanel.Children.Add(button1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (_t != null)
{
//Do your work here
// Double sa11v = Convert.ToDouble(t[j].Text);
}
}
but for a broader aspect, you can use dictionary,
Dictionary<string, TextBox> _dicTextBoxes;
private void vsematrici_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedIndex = vsematrici.SelectedIndex + 2;
StackPanel[] v = new StackPanel[selectedIndex];
for (int i = 0; i < selectedIndex; i++)
{
v[i] = new StackPanel();
v[i].Name = "matrixpanel" + i;
v[i].Orientation = Orientation.Horizontal;
_dicTextBoxes = new Dictionary<string, TextBox>();
for (int j = 0; j < selectedIndex; j++)
{
TextBox txtBox = new TextBox();
txtBox = new TextBox();
txtBox.Name = "a" + (i + 1) + (j + 1);
txtBox.Text = "a" + (i + 1) + (j + 1);
v[i].Children.Add(txtBox);
Thickness m = txtBox.Margin;
m.Left = 1;
m.Bottom = 1;
txtBox.Margin = m;
InputScope scope = new InputScope();
InputScopeName name = new InputScopeName();
name.NameValue = InputScopeNameValue.TelephoneNumber;
scope.Names.Add(name);
txtBox.InputScope = scope;
_dicTextBoxes.Add(txtBox.Name, txtBox);
}
mainpanel.Children.Add(v[i]);
}
Button button1 = new Button();
button1.Content = "Найти определитель";
button1.Click += Button_Click;
mainpanel.Children.Add(button1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (_dicTextBoxes != null)
{
// a23 is the name of textbox, 'a' is prefixe, '2' is the 2nd stackpanel you have added
// '3' is the 3rd textbox you have added in stackpanel
if (_dicTextBoxes.ContainsKey("a23"))
{
//Do your work here
Double sa11v = Convert.ToDouble(_dicTextBoxes["a23"].Text);
}
}
}
Loop through the Children of mainpanel and check each control if it is a TextBox. Something like:
foreach (UIElement ctrl in mainpanel.Children)
{
if (ctrl.GetType() == typeof(TextBox))
{
TextBox oneOfYourTextBoxes = ((TextBox)ctrl);
// do your thing
}
}
You cannot change an arrays size after you created it. Hence your size is known only at runtime after firing your event you cannot set its size within the declaration.
class MyClass
{
Textbox[] myTextBoxes;
private void vsematrici_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// ...
myTextBoxes = new TextBoxes[selectedIndex];
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int myIndex = // your selected item here
if (this.myTextBoxes != null && myIndex < this.myTextBoxes.Length)
{
Console.WriteLine(this.myTextBoxes[myIndex].Text);
}
}
}
This will also work:
button1.Click += (sender, args) => DoSomethingToTextboxes(_t);
I am creating an dynamic controls I have an drop down with options “Textbox, checkbox, dropdown, label” when user selects any of these options from the drop down controls gets created
Let me say I create control like these from selecting the option from the dropdown.
1: text box
2: drop down
3: text box:
4: dropdown
However in the page output its shown like this:
1: textbox
2: textbox
3: dropdown
4: dropdown
This is not the right order based on the selected order above.
Issue here is the design is not quite right.
When I am recreating the controls I recreate controls accoring to their types: TextBoxes, then DropDowns
Pls find attched code any suggestion how to solve this would be helpful.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Dynamiccontrol.aspx.cs" Inherits="Dynamic_controls.Dynamiccontrol" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlcontrols" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlDynamic_SelectedIndexChanged">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>Textbox</asp:ListItem>
<asp:ListItem>Dropdown</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
In.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Dynamic_controls
{
public partial class Dynamiccontrol : System.Web.UI.Page
{
Panel pnlTextBox;
protected void Page_PreInit(object sender, EventArgs e)
{
//Create a Dynamic Panel
pnlTextBox = new Panel();
pnlTextBox.ID = "pnlTextBox";
pnlTextBox.BorderWidth = 1;
pnlTextBox.Width = 800;
pnlTextBox.Height = 800;
this.form1.Controls.Add(pnlTextBox);
RecreateTxtControls("txtDynamic", "TextBox");
RecreateDDLControls("ddlDynamic", "DropDownList");
RecreateChkControls("chkDynamic", "CheckBox");
}
protected void Page_Load(object sender, EventArgs e)
{
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private int FindOccurenceCheckbox(string substr)
{
string reqstr = Request.Form.ToString();
substr = "chkDynamic";
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private int FindOccurenceLabel(string substr)
{
string reqstr = Request.Form.ToString();
substr = "lblDynamic";
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateTxtControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "TextBox")
{
CreateTextBox(ctrlID);
}
break;
}
}
}
}
}
private void RecreateDDLControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "DropDownList")
{
CreateDropDownList(ctrlID);
}
break;
}
}
}
}
}
private void RecreateChkControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
// ctrlPrefix = "chkDynamic";
int cnt = FindOccurenceCheckbox(ctrlPrefix);
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "CheckBox")
{
CreateCheckbox(ctrlID);
}
break;
}
}
}
}
}
private void ReqFieldValidator(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
// ctrlPrefix = "chkDynamic";
int cnt = FindOccurenceCheckbox(ctrlPrefix);
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "RequiredFieldValidator")
{
CreateCheckbox(ctrlID);
}
break;
}
}
}
}
}
private void ReqLabel(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurenceCheckbox(ctrlPrefix);
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "Label")
{
CreateLabel(ctrlID);
}
break;
}
}
}
}
}
private void CreateLabel(string ID)
{
Label lbl = new Label();
lbl.ID = ID;
lbl.Text = "text";
pnlTextBox.Controls.Add(lbl);
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBox.Controls.Add(lt);
}
private void CreateTextBox(string ID)
{
//CreateLabel(ID);
TextBox txt = new TextBox();
txt.ID = ID;
pnlTextBox.Controls.Add(txt);
// txt.AutoPostBack = true;
// txt.TextChanged += new EventHandler(OnTextChanged);
RequiredFieldValidator req = new RequiredFieldValidator();
req.ControlToValidate = txt.ID;
req.EnableViewState = false;
pnlTextBox.Controls.Add(txt);
Literal lt = new Literal();
lt.Text = "<br />";
}
private void CreateCheckbox(string ID)
{
CheckBox chk = new CheckBox();
chk.ID = ID;
chk.Checked = true;
chk.CheckedChanged += new EventHandler(chk_CheckedChanged);
chk.AutoPostBack = true;
chk.EnableViewState = false;
pnlTextBox.Controls.Add(chk);
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBox.Controls.Add(lt);
}
void chk_CheckedChanged(object sender, EventArgs e)
{
try
{
}
catch (Exception ex)
{
}
}
private void CreateDropDownList(string ID)
{
DropDownList ddl = new DropDownList();
ddl.ID = ID;
ddl.Items.Add(new ListItem("--Select--", ""));
ddl.Items.Add(new ListItem("One", "1"));
ddl.Items.Add(new ListItem("Two", "2"));
ddl.Items.Add(new ListItem("Three", "3"));
// ddl.AutoPostBack = true;
ddl.EnableViewState = false;
// ddl.SelectedIndexChanged += new EventHandler(OnSelectedIndexChanged);
pnlTextBox.Controls.Add(ddl);
//int cnt2 = FindOccurence("CheckBox");
//CreateCheckbox("CheckBox-" + Convert.ToString(cnt2 + 1));
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBox.Controls.Add(lt);
}
private void CreateRequiredFieldValidator(string ID)
{
RequiredFieldValidator req = new RequiredFieldValidator();
req.ID = ID;
// ddl.AutoPostBack = true;
// ddl.SelectedIndexChanged += new EventHandler(OnSelectedIndexChanged);
pnlTextBox.Controls.Add(req);
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBox.Controls.Add(lt);
}
protected void OnTextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
string ID = txt.ID;
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "<script type = 'text/javascript'>alert('" + ID + " fired OnTextChanged event');</script>");
//Place the functionality here
}
protected void ddlDynamic_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlcontrols.SelectedValue == "Textbox")
{
int cnt = FindOccurence("txtDynamic");
CreateTextBox("txtDynamic-" + Convert.ToString(cnt + 1));
int cntChk = FindOccurenceCheckbox("CheckBoxdll");
CreateCheckbox("chkDynamic-" + Convert.ToString(cntChk + 1));
}
if (ddlcontrols.SelectedValue == "Dropdown")
{
int cnt = FindOccurence("ddlDynamic");
CreateDropDownList("ddlDynamic-" + Convert.ToString(cnt + 1));
int cntChk = FindOccurenceCheckbox("chkDynamic");
CreateCheckbox("chkDynamic-" + Convert.ToString(cntChk + 1));
}
}
}
}
I'm not sure what your question is. Your code is clearly creating all controls of one type at once, so that is what I would expect to see in your page output.
If you want to interleave controls then you need to change your algorithm to process controls one by one instead of by type.