Puting textboxes into a TextBox[] array - c#

I'm trying to create a loop to avoid copy pasting these lines 30 times.
The names are:
sum1 to sum30
br1txt1 to br30txt1
br1txt2 to br30txt2
//decimal sum30 = decimal.Parse(br30txt1.Text) + decimal.Parse(br30txt2.Text);
//sumTxt30.Text = sum30.ToString();
But the error I'm getting is that the textbox array seems to try to put the value of the textbox not the text box refrenc it self in to the array, how should I fix this?
private void sumX()
{
TextBox[] sumTextboxNames;
sumTextboxNames = new TextBox[29];
for (int i = 1; i < 31; i++)
{
if (sumTextboxNames[0] == null)
{
int y = 0;
foreach (Control c in this.Controls)
{
if (c is TextBox && c.Name.StartsWith("sum"))
{
sumTextboxNames[y] = (TextBox)c;
y++;
}
}
}
else
{
}
string1 = "br" + i + "txt" + 1 + ".Text";
string2 = "br" + i + "txt" + 2 + ".Text";
string3 = "sumTxt" + i + ".Text";
sum = decimal.Parse(string1) + decimal.Parse(string2);
int x = i - 1;
sumTextboxNames[x].Text = sum.ToString();
}
}

The following lines won't work at all:
string1 = "br" + i + "txt" + 1 + ".Text";
string2 = "br" + i + "txt" + 2 + ".Text";
As 1 and 2 are not strings and can not be concatenated to a string. That should give a compiler error right away.
In the following line, you're trying to add up the names of the text boxes as numbers - won't work, the names contain non-number characters.
sum = decimal.Parse(string1) + decimal.Parse(string2);
Anyway, you don't need to use the TextBox array at all. What you could do is:
for (int i = 1; i <= 30; i++)
{
TextBox s = (TextBox)this.Controls[<Name for the S-Textbox>];
TextBox b1 = (TextBox)this.Controls[<Name for the first sum textbox>];
TextBox b2 = (TextBox)this.Controls[<Name for the second sum textbox>];
s.Text = Decimal.Parse(b1.Text) + Decimal.Parse(b2.Text);
}
EDIT
Sorry, quoted wrong line from OP's source code.
EDIT 2
Forgot to cast to TextBox - this is required of course... Thanks for pointing it out, everybody.

Thorsten Dittmar's answers is the way you should go.
However, with respect to this code:
foreach (Control c in this.Controls)
{
if (c is TextBox && c.Name.StartsWith("sum"))
{
sumTextboxNames[y] = (TextBox)c;
y++;
}
}
You should try a solution that uses LINQ.
For example
TextBox [] sumTextBoxes = (from t in this.Controls.Cast<Control>
where t is TextBox
&& t.Name.StartsWith("sum")
select t).Cast<TextBox>().ToArray();

Thanks to Thorsten this is what I ended up with:
string string1;
string string2;
string string3;
private void sumX()
{
for (int i = 1; i < 31; i++)
{
string1 = "br" + i + "txt" + '1';
string2 = "br" + i + "txt" + '2';
string3 = "sumTxt" + i;
TextBox s = (TextBox)this.Controls[string3];
TextBox b1 = (TextBox)this.Controls[string1];
TextBox b2 = (TextBox)this.Controls[string2];
decimal sum = Decimal.Parse(b1.Text) + Decimal.Parse(b2.Text);
s.Text = sum.ToString();
}

Related

Break loop once expected line is found

string path = "xx\\xx.txt";
string[] memo = System.IO.File.ReadAllLines(path);
int totalLines = textBox2.Lines.Length;
string lastLine = textBox2.Lines[totalLines - 1];
for (int i = 0; i < 5; i++)
{
string a = memo[i];
if (a.Contains(lastLine))
{
textBox2.Text = (textBox2.Text + Environment.NewLine + memo[i + 1]);
}
}
Check the notepad from lines 0 to 4
if (a.Contains(lastLine))
{
textBox2.Text = (textBox2.Text + Environment.NewLine + memo[i + 1]);
}
I want to make above code run only once.
However, because there is a memo[i+1] variable i.
Under the influence of the for statement that repeats 5 times, the text 5 times is input.
How can I fix it?
Simply add a break statement
if (a.Contains(lastLine))
{
textBox2.Text = (textBox2.Text + Environment.NewLine + memo[i + 1]);
break;
}

C# Write each array element to different textbox on form

Hi all hoping for some direction. I have a text file that I am reading into a C# Form as a simple string array. I want to take each element and put them into their own text box on the form. I know I can do it as
textBox1.Text = myArray[0];
textBox2.Text = myArray[1];
and so forth but I was hoping for some sort of for or foreach statement to iterate through the array and textboxes.
For reference the form has 50 boxes on it and the array will always have 50 elements.
Thanks in advance!
Update, I appreciate both comments it got me pointed in the right direction. I was really struggling to think through it. What I ended up coming up with is:
//Read Data
string[] lines = File.ReadAllLines(Globals.savePath);
//Write Data To Form
for (int i = 1; i <= 20; i++)
{
TextBox textBox = (TextBox)groupBox1.Controls["textBox" + i];
textBox.Text = lines[i-1];
}
for (int i = 21; i <= 40; i++)
{
TextBox textBox = (TextBox)groupBox2.Controls["textBox" + i];
textBox.Text = lines[i - 1];
}
for (int i = 41; i <= 60; i++)
{
TextBox textBox = (TextBox)groupBox3.Controls["textBox" + i];
textBox.Text = lines[i - 1];
}
for (int i = 61; i <= 80; i++)
{
TextBox textBox = (TextBox)groupBox4.Controls["textBox" + i];
textBox.Text = lines[i - 1];
}
I am sure there is a cleaner way to do this. But this worked for me and was much better then doing the whole
textbox1.Text = myArray[0]
Plus it had the added benefit of translating over when to the next part where I was editing text boxes and than writing back to the text file.
string[] lines = new string [81];
for (int i = 1; i <= 20; i++)
{
TextBox textBox = (TextBox)groupBox1.Controls["textBox" + i];
lines[i - 1] = textBox.Text;
}
for (int i = 21; i <= 40; i++)
{
TextBox textBox = (TextBox)groupBox2.Controls["textBox" + i];
lines[i - 1] = textBox.Text;
}
for (int i = 41; i <= 60; i++)
{
TextBox textBox = (TextBox)groupBox3.Controls["textBox" + i];
lines[i - 1] = textBox.Text;
}
for (int i = 61; i <= 80; i++)
{
TextBox textBox = (TextBox)groupBox4.Controls["textBox" + i];
lines[i - 1] = textBox.Text;
}
lines[81] = "End";
File.Delete(Globals.savePath);
File.WriteAllLines(Globals.savePath, lines);
Once again Thank You to those that commented!
This is my first attempt at an answer, so fingers crossed this is helpful. I would store the textboxes in a list, then when you loop through your array, just do something like the following:
var maxItems = myArray.Length;
for(int loop = 0; loop < maxItems; loop++)
{
textBoxItemList[loop].Text = myArray[loop];
}
This could be tweaked to determine the loop size using the smallest array size, so you didn't go out of bounds. The maxItems is there just as an example of where you would set this up.
Hope that helps.

C# 2 dimensional array output to textbox

Trying to get a simple 2 dimensional array to display to a text box. Output should look like this:
Student Class House
Jack Math Oxford
Bender Chem Trent
All previous attempts have failed and I am not sure how to output the code.
String[,] text = {
{ "Student", "Class", "House" },
{ "Jack", "Math", "Oxford" },
{ "Bender", "Chem", "Trent" } };
//string textString;
for (int i = 0; i < text.GetUpperBound(0); i++)
{
string first = text[i, 0];
string middle = text[i, 1];
string last = text[i, 2];
TextBox1.Text = first;
TextBox1.Text = middle;
TextBox1.Text = last;
}
You need to concatenate the text onto your strings and pass the strings to the texbox only once, after you're all done. You'll want to add in line breaks to have the data go over several lines as well.
Something like this (untested):
String[,] text = {
{ "Student", "Class", "House" },
{ "Jack", "Math", "Oxford" },
{ "Bender", "Chem", "Trent" } };
string output = '';
//string textString;
for (int i = 0; i < text.GetUpperBound(0); i++)
{
output += text[i, 0] + text[i, 1] + text[i, 2] + Environment.NewLine;
}
TextBox1.Text = output;
At the moment you're just adding things to the textbox and then overwriting them on the next loop.
so i think you problem that you are using textbox try textarea.
the reason is that textbox only take only line but textare you can have multiple lines and you are overwriting the text of the textbox every time by doing this TextBox1.Text = first;
TextBox1.Text = middle;
TextBox1.Text = last;
so try this better
TextBox1.Text += first + " " + middle+" " + last;
If both dimensions are dynamic, you can use a second loop nested it in the one you have. Each loop will be going through one dimension:
for (int i = 0; i < text.GetLength(0); i++)
{
for (int j = 0; j < text.GetLength(1); j++)
{
TextBox1Text += text[i, j] + "\t";
}
TextBox1.Text += "\r\n";
}
Note: I used tab \t to separate the columns and new line \r\n to separate the rows. However, this format will not be visible in a textbox, you'll need to use a textarea. Here is a demo.

Adding new characters to beginning and end of each line in textbox

I have a textbox with multiline enabled, and want to add a string at the beginning and end of
each line, so every line would be changed to
a + line + b
Now I know it has to do with a foreach loop, but don't know how to write it out.
Well, the Lines property is probably the one you want. Three options:
string[] lines = textBox.Lines;
for (int i = 0; i < lines.Length; i++)
{
lines[i] = a + lines[i] + b;
}
textBox.Lines = lines;
Or:
textBox.Lines = Array.ConvertAll(textBox.Lines, line => a + line + b);
Or:
textBox.Lines = textBox.Lines
.Select(line => a + line + b)
.ToArray();
You can use a replace on the entire text:
text = a + text.Replace(Environment.NewLine, b + Environment.NewLine + a) + b;
Since you mentioned foreach, here's another way.
var newLines = new List<string>(textBox1.Lines.Length);
foreach (string line in textBox1.Lines)
newLines.Add(a + line + b);
textBox1.Lines = newLines.ToArray();
Here is what i use to add the characters a and b to the beginning and the end to a string that contains a bunch of lines :
public string Script;
string[] lines = Script.Split(new[] { '\r', '\n' });
for (int i = 0; i < lines.Length; i++)
{
lines[i] = a + lines[i] + b;
if (!lines[i].Equals("\"\"+"))
{
Console.WriteLine(lines[i]);
Result += lines[i]+"\n";
}
}

cannot display a list ?kam

I want to dispaly a list on a button click.I have added a list box in .xaml file and want to add 10 text boxes in list.The following code shows errors.
private void listbutton_C(object sender, RoutedEventArgs e)
{
String str = "thumb_";
TextBox[] name = new TextBox[20];
for (int i = 1; i < 11; i++)
{
if (i == 10)
{
strPath = str + "0" + i + ".jpg";
}
else
{
strPath = str + "00" + i + ".jpg";
}
name[i].Text = strPath;
listBox1.Items.Add(name[i]);
}
ContentPanel2.Visibility = Visibility.Collapsed;
listBox1.Visibility = Visibility.Visible;
}
name[i].text=strpath show nullreferenceExceptions .Can somebody explain what is the problem?
I think you need to instantiate every textbox, you have only created the array.
for (int i = 1; i < 11; i++)
{
name[i] = new TextBox(); // insert this line
if (i == 10)
{
strPath = str + "0" + i + ".jpg";
}
else
{
strPath = str + "00" + i + ".jpg";
}
name[i].Text = strPath;
listBox1.Items.Add(name[i]);
}

Categories