Use loop to clear. textBox[i].Clear(). Is this possible? - c#

I am just looking to know this to try and clean up my code, and also for future reference.
I have a number of textBoxes.
tbPart1.Clear();
tbPart2.Clear();
tbPart3.Clear();
tbPart4.Clear();
tbPart5.Clear();
tbPart6.Clear();
tbPart7.Clear();
Is there any way I could use a loop to replace the numbers?
I tried this, but have no idea how i could run the string.
for (int i = 1; i == 7; i++)
{
string p = "tbPart" + i.ToString() + ".Clear";
}

Inside of the form's code (i.e. in a button click event handler), you can enumerate through all of the TextBox controls on the form and perform a specific action on them:
this.Controls.OfType<TextBox>().ToList().ForEach(x => x.Clear());
If you need to only clear some of the TextBox controls, you can provide a sort of filter like so:
this.Controls.OfType<TextBox>()
// Add a condition to clear only some of the text boxes - i.e. those named "tbPart..."
.Where(x=>x.Name.StartsWith("tbPart"))
.ToList().ForEach(x => x.Clear());

No, you cannot do it that way. But you can define an array or list where you put the controls and then clear them. For example:
List<TextBox> textboxes = new List<TextBox>();
textboxes.Add(tbPart1);
textboxes.Add(tbPart2);
textboxes.Add(tbPart3);
...
Then when you want to clear them
foreach (var tb in textboxes)
tb.Clear();

TextBox[] boxes = new [] {
tbPart1,
tbPart2,
tbPart3,
tbPart4,
tbPart5,
tbPart6,
tbPart7
};
for (int i = 0; i < boxes.Length; i++)
{
boxes[i].Clear();
}

i think you should use an array of textbox then you can do a loop depends the count of numbers of textboxes.

foreach(Control ctrl in this.Controls)
{
if(ctrl.GetType() == typeof(TextBox))
{
ctrl.Text = String.Empty;
}
}

Answer number one by using Control name inside panel1
private void button2_Click(object sender, EventArgs e)
{
string currentCtrlName;
for (int i = 0; i < panel1.Controls.Count; i++)
{
currentCtrlName = "textBox" + (i+1).ToString();
panel1.Controls[currentCtrlName].Text = "";
}
}
==================
Answer number one by using Control index as a child inside panel1
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < panel1.Controls.Count; i++)
{
panel1.Controls[i].Text = "";
}
}
==================

Related

Storing string values in array then displaying the array values

I’m a student working on a class project to store string values into an array[10] using a “Store” button. Then the “Display” button will display the string values in the array[10] in a list box. Extra credit if we display the position too.
Currently when I click the “Store” button I do see the message the value was stored. But when I click the “Display” button the list box shows 10 “0”. Every time I make it only makes it worse so I’m not sure what I’m missing and overlooking.
My global variables
string[] results = new string[10];
string value;
I’m using the for loop to take the string value in the “ResultLabel” to store them in the array[10] until all spaces are take, total of 10 values. The “StoreLabel” displays the message that the value was stored.
protected void StoreButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < results.Length; i++)
{
results[i] = ResultLabel.Text.ToString();
}
StoreLabel.Text = "Results have been stored";
}
Then I believe I’m taking the values from the results[10] array and displaying those values in the list box.
protected void DisplayButton_Click(object sender, EventArgs e)
{
DisplayListBox.Items.Clear();
for (int i = 0; i < results.Length; i++)
{
DisplayListBox.Items.Add(results[i].ToString());
}
}
You can append the index to string.
private void StoreButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < results.Length; i++)
{
results[i] = ResultLabel.Text.ToString();
}
StoreLabel.Text = "Results have been stored";
}
private void DisplayButton_Click(object sender, EventArgs e)
{
DisplayListBox.Items.Clear();
for (int i = 0; i < results.Length; i++)
{
DisplayListBox.Items.Add($"{results[i].ToString()} - {i}");
}
}
I understand your project requires you to use an array and to limit it to 10 items. Those requirements might be simplified if we let the ListBox do all the hard work. I'd like to offer an easy way to get strings into the ListBox with the idea that you can then adapt this strategy to meet your project requirements.
The ListBox is simple to work with if we tell it to use our list as the source of the items it displays. Then all we have to do is add an item to this list and tell the ListBox to Refresh() its contents.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBoxDisplay.DataSource = Values;
}
// Here is our list of strings
BindingList<string> Values = new BindingList<string>();
private void buttonStore_Click(Object sender, EventArgs e)
{
// We look at the value in the textbox and add it to list...
Values.Add((Values.Count + 1).ToString() + " - " + textBoxValueToAdd.Text);
// …and tell the ListBox to update itself from the list
listBoxDisplay.Refresh();
}
}

Get value of dynamically created textbox

I'm in a bit of a pickle at the moment, I've created a bit of code that creates 4 textboxes and adds them to a table layout at run time (code below) but I'm struggling with getting text from it, I tried getting the value from it as you would string s = TxtBox1.Text.ToString(); but it just gets a null reference, then I tried txt.Text.ToString();and this just gets the text from the last text box that was created.
private void button2_Click(object sender, EventArgs e)
{
int counter;
for (counter = 1; counter <= 4; counter++)
{
// Output counter every fifth iteration
if (counter % 1 == 0)
{
AddNewTextBox();
}
}
}
public void AddNewTextBox()
{
txt = new TextBox();
tableLayoutPanel1.Controls.Add(txt);
txt.Name = "TxtBox" + this.cLeft.ToString();
txt.Text = "TextBox " + this.cLeft.ToString();
cLeft = cLeft + 1;
}
I've looked all over for the answers to this and as of yet found nothing if anybody has any ideas I would be grateful.
Thanks
this code picks textbox1 from tableLayoutPanel1, cast it from Control to TextBox and takes Text property:
string s = ((TextBox)tableLayoutPanel1.Controls["TxtBox1"]).Text;
if you need them all, then iterate over textboxes:
string[] t = new string[4];
for(int i=0; i<4; i++)
t[i] = ((TextBox)tableLayoutPanel1.Controls["TxtBox"+(i+1).ToString()]).Text;
You can try
var asTexts = tableLayoutPanel1.Controls
.OfType<TextBox>()
.Where(control => control.Name.StartsWith("TxtBox"))
.Select(control => control.Text);
That will enumerate the Text value for all child controls of tableLayoutPanel1 where their type is TextBox and their name starts with "TxtBox".
You can optionally relax the filters removing the OfType line (that excludes any non TextBox control) or the Where line (that allow only the control which name matches your example).
Ensure to have
Using System.Linq;
at the beginning of the file.
Regards,
Daniele.
public void AddNewTextBox()
{
txt = new TextBox();
tableLayoutPanel1.Controls.Add(txt);
txt.Name = "TxtBox" + this.cLeft.ToString();
txt.Text = "TextBox " + this.cLeft.ToString();
cLeft = cLeft + 1;
txt.KeyPress += txt_KeyPress;
}
private void txt_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//the sender is now the textbox, so that you can access it
System.Windows.Forms.TextBox textbox = sender as System.Windows.Forms.TextBox;
var textOfTextBox = textbox.Text;
doSomethingWithTextFromTextBox(textOfTextBox);
}

Array values into list box

I have the following code.
I am trying to insert values into a listbox, and then be able to resort the values by alphabetical order and re display them in the same listbox. For some reason code doesn't work (no errors - just when i push the button the listbox clears)
protected void sortButton_Click(object sender, ImageClickEventArgs e)
{
string[] movieArray = new string [cartListBox.Items.Count];
for (int i = 0; i < cartListBox.Items.Count; i++)
{
movieArray[i] = cartListBox.Items[i].ToString();
}
Array.Sort(movieArray);
cartListBox.Items.Clear();
for (int i = 0; i < cartListBox.Items.Count; i++)
{
cartListBox.Items.Add(movieArray[i].ToString());
}
}
I think problem is in last loop.
Do that like follows:
cartListBox.Items.Clear();
for (int i = 0; i < movieArray.Length; i++)
{
cartListBox.Items.Add(movieArray[i].ToString());
}
When you are clearing cartListBox.Items.Clear();, it should not be taken for loop counter like, for (int i = 0; i < cartListBox.Items.Count; i++)
cartListBox.Items.Count was creating problem.
You can avoid all that looping, and your bug, by doing this in a more modern way:
var items = cartListBox.Items
.Select(item => item.ToString())
.OrderBy(x => x);
cartListBox.Items.Clear();
cartListBox.Items.AddRange(items);
cartListBox.Items.Count // is 0 length
you are doing in the previous step:
cartListBox.Items.Clear();
To add movieArray to listbox use AddRange
carListBox.Items.AddRange(movieArray);
To sort just set sorted =true
carListBox.Sorted=true;
Complete code is below
carListBox.Items.AddRange(movieArray);
carListBox.Sorted=true;

Concatenate strings to make Picturebox name

i have lot of pictureboxes named this way: PBr1_1, PBr1_2, ... PBr1_9
I'd like to make loop
for (int i = 0; i < 10; i++)
{
if (Textbox.Text[i].ToString() == "1"){ "PBr1_"+"i".Tag = "cb.png";}
}
so for i=0 => PBr1_0, i=10 => Pbr1_10.
Example i have value in textbox: 0001011101 - then if value in textbox is "1" then i'd like to change picturebox tag.
How to automate this process, using for example loop "for"?
I suppose your controls are on a WinForm (this) and the ones with that name are all pictureboxes.
If so, that's the way ----
for (int i = 0; i < 10; i++)
{
if (Textbox.Text[i].ToString() == "1")
{
Control[] c = this.Controls.Find("PBr1_" + i.ToString(), true);
if(c != null && c.Length > 0) c[0].Tag = "cb.png";
}
}
You can put the picture boxes in to a List<PicutreBox> and iterate over the list.
var pictures = new List<PictureBox>();
pictures.Add(pic1);
pictures.Add(pic2);
//...
for (int i = 0; i < 10; i++)
{
if (Textbox.Text[i].ToString() == "1")
pictures[i].Tag = "cb.png";
}
Dynamic variable names as in your example are not supported.
Create an array (or list) that contain the picture boxes and use those within the for loop.
You can also use reflection but in my opinion it is best not to use that in this case.
If you are using WinForm you can use Control.Find method to locate a control by name
Once you have got the control you can easily change any property

Programmatically Checking DataBound CheckListBox

I have a DataBound "CheckedListBox", I need to check some items on it. I tried with following code...
if (!string.IsNullOrEmpty(search.Languages))
{
string[] langs = search.Languages.Split(',');
for (int i = 0; i < (langs.Length - 1); i++)
{
for (int j = 0; j < clbLang.Items.Count; j++)
{
string lng = clbLang.Items[j] as string;
if (lng.Trim() == langs[i])
{
clbLang.SetItemChecked(j, true);
break;
}
}
}
}
No errors, debuged execution is going through "checking" process, but finally I cannot see anything checked on it.
Then I have added a button and added following code to it. (upon click check all the items)
private void button9_Click(object sender, EventArgs e)
{
for (int i = 0; i < clbLang.Items.Count; i++)
{
clbLang.SetItemChecked(i, true);
}
}
It is "checking" all the items, Please tell me if anyone can see a issue here...?
Finally found out, it is a Bug introduced by MS.
It is well explained here.
The issue is easy to reproduce. Just hide and show a databound
CheckedListBox and you will notice how
the previously checked items get
unchecked.
CheckedListBox SetItemChecked method not working
So we have to find a workaround... I tried follwing way, it is working nice...
At the place where I was calling checking of items I have added following... I am adding what I need to check in Tag of the control.
if (!string.IsNullOrEmpty(search.Languages))
{
clbLang.Tag = search.Languages;
}
Then, following code in that control's "VisibleChanged()" event.
private void clbLang_VisibleChanged(object sender, EventArgs e)
{
string lngs = clbLang.Tag as string;
if (!string.IsNullOrEmpty(lngs))
{
string[] langs = lngs.Split(',');
foreach (string lang in langs)
{
int j = 0;
foreach (DataRowView row in clbLang.Items)
{
if (row != null)
{
string lng = row[1] as string;
if (lng.Trim() == lang)
{
clbLang.SetItemChecked(j, true);
break;
}
}
j++;
}
}
}
}
This works well with me, hope it will benefit you...

Categories