HtmlAnchor[] anchorToConvert = new HtmlAnchor[]{
clickHere,
leavePage};
Button[] buttonToConvert = new Button[]{
login,
register};
i = 0;
for (i = 0; i < anchorToConvert.Length; i++)
{
DataRow[] result = ds.Tables[0].Select("htmlControl LIKE '" + anchorToConvert[i].ID.ToString() + "'");
if (result.Length > 0)
{
anchorToConvert[i].InnerHtml = result[0]["phrase"].ToString();
}
}
i = 0;
for (i = 0; i < buttonToConvert.Length; i++)
{
DataRow[] result = ds.Tables[0].Select("htmlControl LIKE '" + buttonToConvert[i].ID.ToString() + "'");
if (result.Length > 0)
{
buttonToConvert[i].Text = result[0]["phrase"].ToString();
}
}
I have two arrays of html elements i need to loop through, and use the elements id attribute to select content from a database. Rather than having to create two arrays and loop through them individually, is there someway i can make a more generic array that can contain both buttons and anchors?
You could use a list and check the type of the control in the list when you're looping through:
List<Control> ctrl = new List<Control>();
HtmlAnchor anchor = new HtmlAnchor();
anchor.ID = "myAnchor";
ctrl.Add(anchor);
Button btn = new Button();
btn.ID = "MyBtn";
ctrl.Add(btn);
foreach (Control c in ctrl.ToList())
{
if (c is Button)
{
// Do Something
}
}
Both HtmlAnchor and Button inherit from Web.UI.Control (though not directly).
If that is the type of the array, both of these types (HtmlAnchor and Button) can be assign to the array.
Related
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();
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";
So I have this kind of code (I'm assigning values to XAML elements
), which begs for a "for" loop.
Day1d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(1));
Day2d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(2));
Day3d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(3));
Day4d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(4));
Day1t.Text = "°" + (myWeatherForecast.forecastlist[1].temp).ToString();
Day2t.Text = "°" + (myWeatherForecast.forecastlist[2].temp).ToString();
Day3t.Text = "°" + (myWeatherForecast.forecastlist[3].temp).ToString();
Day4t.Text = "°" + (myWeatherForecast.forecastlist[4].temp).ToString();
But all my attempts to include "i" in variable name failed miserably. Is there a way to achieve this?
You can create a loop where you iterate over the instances:
int counter = 1; // are you sure it shouldn't start at 0?
foreach (TextBox tb in new TextBox[] { Day1d, Day2d, Day3d, Day4d })
{
tb.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(counter));
counter++;
}
counter = 1;
foreach (TextBox tb in new TextBox[] { Day1t, Day2t, Day3t, Day4t })
{
tb.Text = "°" + (myWeatherForecast.forecastlist[counter].temp).ToString();
counter++;
}
You can't compose the name of the variable using another variable. The way to do this would be to create a List and then iterate over that List
var textBoxes1 = new List<TextBox> { Day1d, Day2d, Day3d, Day4d }
var textBoxes2 = new List<TextBox> { Day1t, Day2t, Day3t, Day4t }
foreach (var textbox in textBoxes1)
{
var index = textBoxes1.IndexOf(textBox) + 1;
textbox.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(index));
}
foreach (var textbox in textBoxes2)
{
var index = textBoxes2.IndexOf(textBox) + 1;
textbox.Text = "°" + (myWeatherForecast.forecastlist[index].temp).ToString();
}
NOTE: You can solve this in different ways:
using arrays instead of lists
keeping your own counter, instead of doing IndexOf
using a for loop, instead of a foreach
Which one is better is mostly based on opinion (although my method is not the fastest, but it doesn't matter if you only have 4 items)
You can use FindName assuming you are using WPF.
Try:
for (int i = 1; i < 5; i++)
{
((TextBox)this.FindName("Day" + i + "d")).Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(i));
((TextBox)this.FindName("Day" + i + "t")).Text = "°" + (myWeatherForecast.forecastlist[i].temp).ToString();
}
string[] board = new string[9];
for (var i = 0; i < 9; i++)
{
board[i] = (textBox1.Text);
}
I'm trying to make a loop which puts the text of textboxes in the array, but I can't figure out how to put the i variable in the 'textBox.Text' statement. I've tried this:
board[i] = ("textBox" + i + ".Text");
But this returns 'textBox1.Text'. How do I make the textbox.Text statement 'compatible' with the for loop?
You didn't tell us what API are you using as #Jeppe Stig Nielsen commented.
Asp.net? WPF? Windows Forms?
In Asp.net you can use FindControl method
string[] board = new string[9];
for (var i = 0; i < 9; i++)
{
board[i] = ((TextBox)FindControl("textBox" + i)).Text
}
In WPF you can use FindName method:
string[] board = new string[9];
for (var i = 0; i < 9; i++)
{
board[i] = ((TextBox)this.FindName("textBox" + i)).Text;
}
Use more meaningful control names if you want to maintain your code sometime. The business logic should not be dependent on control names.
However, if you want to get an array of all textboxes in a container control like the form you could also use LINQ:
string[] board = this.Controls.OfType<TextBox>()
.Where(txt => txt.Name.StartsWith("textBox"))
.Select(txt => txt.Text)
.ToArray();
If you only want to take textboxes from 1-9:
var txtNames = Enumerable.Range(1, 9).Select(i => "textBox" + i);
string[] board = this.Controls.OfType<TextBox>()
.Where(txt => txtNames.Contains(txt.Name))
.Select(txt => txt.Text)
.ToArray();
Try this ,
string[] arr= new String[3];
for (int i = 0; i <= 2; i++)
{
TextBox testTextBox = (TextBox)this.Controls["textBox" + i.ToString()];
arr[i] = testTextBox.Text;
}
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.