Change text in multiple textboxes? - c#

How would I go about making a for loop that changes the text in more than 1 textbox?
for (int i; i < 5; i++)
{
textbox(i).text = "something"
}
But I don't know how to get the I to represent the number after the textbox, does anyone know how to?

Store the textboxes in an Array and then loop over the array
for (int i; i < 5; i++)
{
textboxArray[i].text = "something"
}

You could use Controls.Find:
var txts = this.Controls.Find("textbox" + i, true); // true for recursive search
foreach(TextBox txt in txts)
txt.Text = "something";
or - if the TextBoxes are in the same container control(like the Form or a Panel)- with LINQ:
var txts = this.Controls.OfType<TextBox>().Where(txt => txt.Name == "textbox" + i);
foreach(TextBox txt in txts)
txt.Text = "something";
Actually you don't need the loop variable, you could also use String.StartsWith to get all:
var txts = this.Controls.OfType<TextBox>().Where(txt => txt.Name.StartsWith("textbox"));
foreach(TextBox txt in txts)
txt.Text = "something";

if you dont want to alter every textbox on your form just simply add them to a List:
List<TextBox> TextBoxes = new List<TextBox>();
TextBoxes.Add(This.TextBox1);
TextBoxes.Add(This.TextBox3):
then as others have suggested you could either linq or regular foreach the textboxes in the list
TextBoxes.Foreach(Textbox => TextBox.Text = "something");
or
foreach (TextBox r in TextBoxes)
{
r.Text = "something;
}

Related

How can i take the values from texboxes by the name of it

I want the following code to give me the exact number of S values from the textboxes named : Box1_1 , Box1_2 , Box1_3, Box1_4, Box1_5 ...
But when i try to see the value it's always blank. What can i do ?
for (int i = 1; i <= 7; i++){
for (int j = 1; j <= 10; j++){
string box = "Box" + i.ToString() + "_" + j.ToString();
TextBox nameBox = new TextBox();
nameBox.Name = box;
if(string.Compare(nameBox.Text, "S")==0){
numberS++;
}
}
}
This is a cheeky little one-liner using Linq (split over multiple lines for clarity):
var textBoxes = this.Controls
.OfType<TextBox>() // controls that are TexteBoxes
.Where(t => t.Name.StartsWith("Box") && t.Text.StartsWith("S"))
.ToList();
int numberS = textBoxes.Count();
We get all TextBox controls using OfType<TextBox>()
This assumes the name of the TextBoxes you're interested in start with "Box". The corresponding Linq is Where(t => t.Name.StartsWith("Box")).
It looks like you're only interested in the TextBoxes that have a value that starts with "S". The corresponding linq is Where(t => t.Text.StartsWith("S")). I have combined these in a single Where.
Then we get the count: .Count()
If you want the count of textboxes that contain S (not just start with S) then use t.Text.Contains("S") in the Where clause instead.
If you want to get the TextBox names (Box1_1, Box1_2, etc) then you can use Select which will take the Name property from each TextBox and return a List<string>
var txtNames = this.Controls
.OfType<TextBox>() // controls that are TexteBoxes
.Where(t => t.Name.StartsWith("Box") && t.Text.StartsWith("S"))
.Select(t => t.Name) // select textbox names
.ToList();
txtNames is a List<string> containing the textbox names which start with S.
First of all, you need a collection of your TextBox'es or scrap them from your window. Example of how to do the second is here.
Here is your code that I modified:
public int CountS()
{
var numberS = 0;
for (int i = 1; i <= 7; i++)
{
for (int j = 1; j <= 10; j++)
{
string box = "Box" + i.ToString() + "_" + j.ToString();
TextBox nameBox
= UIHelper.FindChild<TextBox>(Application.Current.MainWindow, box); //using example linked above
//= textBoxes.First(tbx => tbx.Name == box); //if you got collection of your textboxes
numberS += nameBox.Text.Count(c => c == 'S'); //if you wont also count a small "s" add .ToUpper() before .Count
}
}
return numberS;
}

How to edit a control content in an array inside of a list

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";

How to write to a dynamical number of Textboxes?

I have a form (Windows Forms) with dynamically created textboxes:
TextBox[] tbxCantServ = new TextBox[1];
int i;
for (i = 0; i < tbxCantServ.Length; i++)
{
tbxCantServ[i] = new TextBox();
}
foreach (TextBox tbxActualCant in tbxCantServ)
{
tbxActualCant.Location = new Point(iHorizontal, iVertical);
tbxActualCant.Name = "tbx" + counter++;
tbxActualCant.Visible = true;
tbxActualCant.Width = 44;
tbxActualCant.MaxLength = 4;
this.Controls.Add(tbxActualCant);
}
Now I want to fill them with data, how could I do that?
If I created some textboxes dynamically with the names:
"tbxActualServ.Name = "txt" + counter;"
How can I write in them? How can I access to them?
For example, if I have created tbx1, tbx2 and tbx3, I would have a "for" that fills tbx1.Text with "1", tbx2.Text with "2", and tbx3.Text with "3".
something like
"for from i=0 to counter {
tbx[i] = i
}"
of like:
this.Controls.OfType<TextBox>().Where(r => r.Name == "tbx" + counter).¿¿Write??(r => r.Text = i).ToString();
Thanks!
You could do something like this:
this.Controls.OfType<TextBox>().ToList<TextBox>().ForEach(tb => tb.Text = "bla bla");
Evening,
Guessing from your tags that this is a web forms project.. Im going to have to make some other assumptions.
I am guessing that you are creating your text boxes in code, something like
TextBox tb1 = new TextBox();
form1.Controls.Add(tb1);
TextBox tb2 = new TextBox();
form1.Controls.Add(tb2);
If this is the case then I believe that you could do something like this:
for (int i = 0; i < 2; i++)
{
TextBox tb1 = page.findControl("tb" + i.ToString());
tb1.Text = "This is number " + i.ToString();
}
There is another alternative, you could keep a collection of the controls as you create them, you could then iterate over the collection.
To be honest, without more details about your code it will be difficult to give a full answer, I think that this answers what you are looking for, if not update your question with more details and more of the code (the code where you are dynamically creating the controls would be useful)
While it's possible to access controls by their names (the way you do it depends on the technology - are you using WinForms, WPF, Web Forms, ...?), using an array of controls is a much better solution. Here's some pseudo-C#:
MyControl[] controls = new MyControl[length];
for(int n = 0; n < controls.Length; n++)
{
controls[n] = new MyControl(...);
}
// ...
for(int n = 0; n < controls.Length; n++)
{
DoSomethingWith( controls[n] );
}

Populate text boxes from List Values

I have a list that is created from a LINQ to XML query. The list can contain 1, 2, 3 or 4 values. I have four text boxes on the form that should be populated based on the values in the List, but I can't figure out how to do this because the number of elements in the list will vary. Would it be better to dynamically create the textboxes based on the number of values in the list? How could I go about this?
It seems like this would be a fairly common task, but I have not been able to find a solution. Any help would be greatly appreciated.
Creating dynamically, or just populating an existing 4, it doesn't matter. Choose which one is best for your UI requirements. (maybe even a DGV as has been suggested already)
First you need something to contain the controls, lets say you have a panel called MyPanel which will hold only these textboxes and nothing else...
Here's the load dynamically approach:
MyPanel.Controls.Clear();
int count = 1;
foreach(var item in listOfValues)
{
TextBox tb = new TextBox();
tb.Name = "MyTextbox" + i;
tb.Text = item.ToString();//or whatever property you have for the value
tb.Location = new Point(0, 0 + (25 * (i - 1)));
MyPanel.Controls.Add(tb);
}
Here is the fill existing approach, assuming you have 4 TextBoxes called "TextBox1" for example:
int count = 1;
foreach(var item in listOfValues)
{
TextBox tb = MyPanel.Controls.Find("TextBox" + i) as TextBox;
tb.Text = item.ToString();//or whatever property you have for the value
}
NOTE: You need to be sure that listOfItems does not contain more items than you have textboxes for, otherwise you will get an exception
lets say you have a List
List<int> testList = new List<int>(){1,2,3};
foreach(int i in testList)
{
TextBox test = new TextBox();
test1.Name = "textBox"+i;
youcOntrl.Controls.Add(test1);
}
You can also give them their location and size etc.
Sounds like you want to create a foreach loop and iterate round the linq query creating a new text box on each one and adding it to your form. It'd help to see what you've got so far. I've put an example below using a list instead of a linq query but what comes after it is the same
private void Form1_Load(object sender, EventArgs e)
{
var newList= new List<string> {"box1", "box2", "box3"};
foreach (var boxName in newList)
{
TextBox newTextBox = new TextBox();
newTextBox.Text = boxName;
this.Controls.Add(newTextBox);
}
}
You can create 4 text boxes in the forms designer and set their Visible property to be false as default (from the properties pane).
Then, you can switch on the count property of your list as follows:
switch (els.Count)
{
case 1:
textBox1.Text = els[1].Value;
textBox1.Visible = true;
break;
case 2:
textBox1.Text = els[1].Value;
textBox1.Visible = true;
textBox2.Text = els[2].Value;
textBox2.Visible = true;
break;
case 3:
textBox1.Text = els[1].Value;
textBox1.Visible = true;
textBox2.Text = els[2].Value;
textBox2.Visible = true;
textBox3.Text = els[3].Value;
textBox3.Visible = true;
break;
case 4:
textBox1.Text = els[1].Value;
textBox1.Visible = true;
textBox2.Text = els[2].Value;
textBox2.Visible = true;
textBox3.Text = els[3].Value;
textBox3.Visible = true;
textBox4.Text = els[4].Value;
textBox4.Visible = true;
break;
default:
break;
}
If your list is IEnumerable, then you must first call the ToList() method on it to get a List<XElement> as IEnumerable type does not have a Count property.
If it is four or less then you don't have to create dynamically the textboxes. You could probably disable the textbox(es) that could not be populated. And specially if you name your textbox sequentially like TextBox1, TextBox2 etc then you could probably code like:
for (int i = 1; i <= 4; i++)
{
if (i <= list.Count)
{
this.Controls["TextBox"+i.ToString()].Text = list[i-1];
this.Controls["TextBox"+i.ToString()].Enabled = True;
}
else
{
this.Controls["TextBox"+i.ToString()].Enabled = False;
}
}
So, if you have 2 Items in your List for example then List.Count is 2 and therefore Textbox1 and 2 would be populated and TextBox3 and 4 will be disabled.

Storing Textbox values into Database

I am doing a crossword puzzle and i have 100 text boxes in a panel like this :
Every text box have an id of 00 - 99 since there is 100 of it .
First Row will have an id 00-09 , 2nd row will have an id of 10-19 and so on.
When user types something in some text box will be null and some text box will have values in it. How do I save values from a text box of a certain id to a database? For example the above image, HELP, text box id of 22 will have the value H , id of 23 will have the value of E , id of 24 will have value of L , id of 25 will have value of P.
I don't want to save the null values of the text box , I want to save values of the textboxes which are not null. I also need to take into account their textbox ids so that when I populate them back, I just have to insert them through ID .
I am new to C# , appreciate any help/advise/solutions on this.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
//hw.Write("<table>");
for (int i = 0; i <= 9; i++)
{
//hw.Write("<tr>");
for (int j = 0; j <= 9; j++)
{
TextBox tb = new TextBox();
tb.MaxLength = (1);
tb.Width = Unit.Pixel(40);
tb.Height = Unit.Pixel(40);
tb.ID = i.ToString() + j.ToString(); // giving each textbox a different id 00-99
Panel1.Controls.Add(tb);
}
Literal lc = new Literal();
lc.Text = "<br />";
Panel1.Controls.Add(lc);
}
}
protected void btnShow_Click(object sender, EventArgs e)
{
foreach (Control control in Panel1.Controls)
{
var textBox = control as TextBox;
if (textBox != null)
{
if (string.IsNullOrEmpty(textBox.Text))
{
textBox.Style["visibility"] = "hidden";
}
// textBox.Enabled = false;
textBox.Text = "";
}
}
}
The proper way to do this is to wrap these textboxes inside a Repeater or Datalist controls. You can ready about these controls from here. This way when number of rows increase you will not have to change to your loop or hard-coded values.
As for your question to store values for a given Id, you can define row# and col# in your database and sort on row# and col#, this should work.
The easiest way is to make a 2D array (or List) of your TextBoxes. In where you create your TextBoxes:
List<List<TextBox>> textBoxList = new List<List<TextBox>>();
for (int i = 0; i <= 9; i++)
{
List<TextBox> textBoxRow = new List<TextBox>(); //this could be columns, not sure
for (int j = 0; j <= 9; j++)
{
TextBox tb = new TextBox();
....
textBoxRow.Add(tb);
}
...
textBoxList.Add(textBoxRow);
}
Now you can read/write to those array entries, such as:
string readValue = textBoxList[2][5].Text;
textBoxList[1][7].Text = "asdf";

Categories

Resources