Good Day Everyone.
I'm creating function in which i dynamically generate textbox depending on the selected value in the dropdown list.
Here's the code.
comboboxNameHolder = ((ComboBox)sender).Name;
string comboboxNoHolder =comboboxNameHolder.Replace("cbFunctionList", "");
comboboxNo = Int32.Parse(comboboxNoHolder);
funcSelected = ((ComboBox)sender).SelectedItem.ToString();
for (int i = 0; i < optionList1.GetLength(0); i++)
{
if (funcSelected == optionList1[i, 0])
{
funcNoOfFields = optionList1[i, 1];
}
}
if (lineFieldController[comboboxNo, 1] == 0)
{
fieldCounter = Int32.Parse(funcNoOfFields);
lineFieldController[comboboxNo, 1] = fieldCounter;
inputField1 = new TextBox[fieldCounter];
for (int i = 0; i < fieldCounter; i++)
{
btnAddField0.Visible = false;
inputField = new TextBox();
inputField.Font = new Font("Microsoft Sans Serif", 11.25f);
inputField.Size = new Size(75, 24);
inputField.Location = new Point(positionController[comboboxNo, 0], positionController[comboboxNo, 1]);
inputField.Name = "txtLine" + comboboxNo.ToString() + "Variable" + i.ToString();
this.Controls.Add(inputField1[i]);
positionController[comboboxNo, 0] += 81;
}
}
Now I want in the same function when the lineFieldController is not equal to zero means that there are already created textbox in that line. When the user chooses another value in the dropdown list the number of fields will change by deleting the existing fields then creating new ones depending on the selected item.
How do I delete the textboxes I created?? I tried calling it by name but it doesn't work.
else
{
for(int i = 0; i < lineFieldController[comboboxNo, 1]; i++)
{
string name = "txtLine" + comboboxNo.ToString() + "Variable" + i.ToString();
TextBox tb = this.Controls.Find(name, true);
}
}
Hoping for your kind response
you can put all controls that you have created put them to the list and hold reference on controls were created at runtime.
like
public class Form1
{
List<Control> createdList = new List<Control>(); // class field
void combobox_SelectedIndexChanged()
{
// removing controls were created before
foreach (var created in createdList)
{
this.Controls.Remove(created);
created.Dispose();
}
createdList.Clear(); // all created controls from previous index changed should be removed here
// add each control you are creating to the createList additionally
inputField1 = new TextBox[fieldCounter];
for (int i = 0; i < fieldCounter; i++)
{
btnAddField0.Visible = false;
inputField = new TextBox();
createdList.Add(inputField); //store reference
/// skipping init code
this.Controls.Add(inputField1[i]);
positionController[comboboxNo, 0] += 81;
}
}
}
another option is to add panel on the form as a placeholder for all controls are being created. You have to change this.Controls.Add(inputField1[i]); to the panelCreated.Controls.Add(inputField1[i]);
Then you can grab all controls from the panel and remove them without name search like below
foreach (Control created in panelCreated.Controls)
created.Dispose();
panelCreated.Controls.Clear();
Related
From the below code, I dynamically create a list of buttons based on client names provided by a TCP connection from the clientNames[i] list.
private void updateClientListUI()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.updateClientListUI));
}
else
{
//Debug.WriteLine(clientNames[0]);
int basex = subPanelClient.Location.X;
int basey = subPanelClient.Location.Y;
for (int i = 0; i < clientNames.Count; i++)
{
Button b = new Button();
b.Left = basex;
b.Top = basey;
b.Size = new Size(25, 25); // <== add this line
b.Dock = DockStyle.Top;
b.ForeColor= Color.Gainsboro;
b.FlatStyle= FlatStyle.Flat;
b.FlatAppearance.BorderSize = 0;
b.Padding= new Padding(35, 0, 0, 0);
b.TextAlign = ContentAlignment.MiddleLeft;
basey += 25;
b.Name = clientNames[i];
b.Text = clientNames[i];
subPanelClient.Controls.Add(b);
buttonsAdded.Insert(i, b);
}
}
}
What I am trying to figure out, is how to delete a button (i). What I attempted is the following:
private void removingButtons(int i)
{
if (buttonsAdded.Count > 0)
{
Button buttonToRemove = buttonsAdded[i];
subPanelClient.Controls.Remove(buttonToRemove);
buttonsAdded.Remove(buttonToRemove);
}
}
Or if anyone would know how to update the current list of buttons from updateClientListUI() to the current latest list from clientNames[i] instead of a list being added onto another list.
The issue that Im getting is that obviously every time there is a connection or disconnection the list just keeps getting added instead of refreshing to the current list.
One way to do it would be to clear the old buttons on each update.
foreach (Button b in buttonsAdded)
{
subPanelClient.Controls.Add(b);
}
buttonsAdded.Clear();
for (int i = 0; i < clientNames.Count; i++)
{
Button b = new Button();
...
...
If the subPanelClient only contains those buttons, you could just use
subPanelClient.Controls.Clear();
Last remark: Your removingButtonk function seems to use this.Controls.Remove instead of subPanelClient.Controls.Remove.
I got the following:
List<TextBox[]> ListMonths = new List<TextBox[]>();
I use it for store the same textboxes for each month, I fill it like this
for (int i = 0; i <= 11; i++)
{
......
TextBox[] TBaux = new TextBox[18];
for (int o = 0; o <= 17; o++)
{
TBaux[o] = (TextBox)element.FindName("TB" + o + i);
}
ListMonths.Add(TBaux);
}
So that way I got the textboxes for each month in ListMonths.
How can I modify the Text property of one of the textbox (for instance textbox[2]) that is stored in one of the month lists (for instance ListMonths[1])?
ListMonths[1][2].Text = "blabla";
Which is the same as doing:
TextBox[] textBoxes = ListMonths[1];
TextBox textBox = textBoxes[2];
textBox.Text = "blabla";
I have a bunch of code that dynamicly creates some controls. It looks in a folder and lists the filenames in it. For each file in the folder it creates a checklistbox item, listbox item and two checkboxes. This is working great and as intended:
private void getAllFiles(string type)
{
try
{
string listPath = "not_defined";
if (type == "internal_mod")
{
int first_line = 76;
int next_line = 0;
int i = 0;
CheckBox[] chkMod = new CheckBox[100];
CheckBox[] chkTool = new CheckBox[100];
listPath = this.internalModsPath.Text;
string[] filesToList = System.IO.Directory.GetFiles(listPath);
foreach (string file in filesToList)
{
if (!internalModsChkList.Items.Contains(file))
{
internalModsChkList.Items.Add(file, false);
string fileName = Path.GetFileName(file);
internalModNameList.Items.Add(fileName);
//-----------------
// Draw Checkboxes
//-----------------
chkMod[i] = new CheckBox(); chkTool[i] = new CheckBox();
chkMod[i].Name = "modChk" + i.ToString(); chkTool[i].Name = "modChk" + i.ToString();
//chkMod[i].TabIndex = i; //chkTool[i].TabIndex = i;
chkMod[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top); chkTool[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top);
chkMod[i].Checked = true; chkTool[i].Checked = false;
chkMod[i].AutoCheck = true; chkTool[i].AutoCheck = true;
chkMod[i].Bounds = new Rectangle(549, first_line + next_line, 15, 15); chkTool[i].Bounds = new Rectangle(606, first_line + next_line, 15, 15);
groupBox7.Controls.Add(chkMod[i]); groupBox7.Controls.Add(chkTool[i]);
//-----------------
next_line += 15;
i++;
}
}
}
Now my problem is that I also want the user to be able to delete all these thing again based on the checklistbox' checked items.. I have no problems deleting the items in the checklistbox or the items in the listbox, but I want to remove the two checkboxes I create too ..
This is what I got to remove the items in the checklistbox, and the listbox
private void internalModListDel_btn_Click(object sender, EventArgs e)
{
int count = internalModsChkList.Items.Count;
for (int index = count; index > 0; index--)
{
if (internalModsChkList.CheckedItems.Contains(internalModsChkList.Items[index - 1]))
{
internalModsChkList.Items.RemoveAt(index - 1);
internalModNameList.Items.RemoveAt(index - 1);
groupBox7.Controls.Remove(modChk[index - 1]);
}
}
}
As you can see I have also tried to write something to remove the checkbox but it doesn't work and I have no idea how to make it work
Can you assist ?
Try using UserControls.
Use the ListBox controller to show those UserControls,
The user control can be built with those checkboxes, and the labels you want .
Another suggestion is to bind this list to an ObservableCollection which will contain the UserContorols you have created.
This way, it will be much more simlpe to add/remove/change the items inside.
I'm trying to make a small app, for make my job easier creating definitions (new web forms aspx) via WinForms C#.
Now I have this form, where I tell the app how many textboxes I want to create.
After their creation, I want to assign to a string the textboxes values that I wrote.
private void CreateControls()
{
for (int index = 0; index < NumberOfRows; index++)
{
TextBox textBox = new TextBox();
textBox.Name = "TextBox" + (index + 1).ToString();
textBox.Size = new Size(120, 20);
textBox.Location = new Point(X, Y + 26);
ComboBox comboBox = new ComboBox();
comboBox.Name = "ComboBox" + (index + 1).ToString();
comboBox.Size = new Size(75, 20);
comboBox.Location = new Point(141, Y + 26);
comboBox.DataSource = Enum.GetNames(typeof(DataTypes));
Y += 26;
this.Controls.Add(textBox);
this.Controls.Add(comboBox);
}
}
Now, I don't know how to check if the textboxes are created, and then take their values.
Could anyone refer me something? Thanks :)!
You'll need to, on Page_Load, find those controls and grab their values. Since you gave them meaningful names when you created them, this should do the trick:
for (int index = 0; index < NumberOfRows; index++)
{
TextBox textBox = this.FindControl(
string.Format("TextBox{0}", index)) as TextBox;
if (textBox == null) { continue; } // this means it wasn't found
var text = textBox.Text;
// work with the text
}
However, if the ComboBox class you're using isn't a third-party one and it's not an ASP.NET application, the code would work for a Windows Forms application as well with a minor modification:
for (int index = 0; index < NumberOfRows; index++)
{
// you have to use the Find method of the ControlCollection
TextBox textBox = this.Controls.Find(
string.Format("TextBox{0}", index)) as TextBox;
if (textBox == null) { continue; } // this means it wasn't found
var text = textBox.Text;
// work with the text
}
I tend to agree with the community that it's probably a Windows Forms application because you can't set the Location of a standard ASP.NET control. However, if these are user controls, or third-party ones, that support those properties and render the appropriate CSS then we'd never know.
if(Page.FindControl("IDofControl") != null)
//exists
else
//does no exists
Suppose I have this in page load:
Label lblc = new Label();
for (int i = 1; i <= 10; i++)
{
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
How can I manipulate each of these controls at run time?
I want to:
Set/get their text.
Reference a particular control, in this case Label.
Use an array if you know how many labels you will have,
Label[] lblc = new Label[10];
for (int i = 0; i < 10; i++)
{
lblc[i] = new Label() { Text = (i + 1).ToString() };
this.Controls.Add(lblc[i]);
}
Then you will reference the textbox 1 with lblc[0] and textbox 2 with lblc[1] and so on. Alternatively if you do not know how many labels you will have you can always use something like this.
List<Label> lblc = new List<Label>();
for (int i = 0; i < 10; i++)
{
lblc.Add(new Label() { Text = (i + 1).ToString() });
this.Controls.Add(lblc[i]);
}
You reference it the same way as the array just make sure you declare the List or the array outside your method so you have scope throughout your program.
Suppose you want to do TextBoxes as well as Labels well then to track all your controls you can do it through the same list, take this example where each Label has its own pet TextBox
List<Control> controlList = new List<Control>();
for (int i = 0; i < 10; i++)
{
control.Add(new Label() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
control.Add(new TextBox() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
}
Good luck! Anything else that needs to be added just ask.
Your code creates only one control. Because, label object creation is in outside the loop. you can use like follows,
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Text = i.ToString();
lblc.Name = "Test" + i.ToString(); //Name used to differentiate the control from others.
this.Controls.Add(lblc);
}
//To Enumerate added controls
foreach(Label lbl in this.Controls.OfType<Label>())
{
.....
.....
}
Better to set the Name and then use that to distinguese between the controls
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Name = "lbl_"+i.ToString();
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
when:
public void SetTextOnControlName(string name, string newText)
{
var ctrl = Controls.First(c => c.Name == name);
ctrl.Text = newTExt;
}
Usage:
SetTextOnControlName("lbl_2", "yeah :D new text is awsome");