Use generated string as names of textBoxes? - c#

I'm trying to put the contents of a ton of textBoxes into a database and to make the code shorter i'm trying to use generated strings as names of the textboxes, but how can i apply this?
for (int i = 0; i <= 9; i++)
{
for (int i2 = 0; i2 <= 7; i2++)
{
string tbName = "textBox" + i.ToString() + i2.ToString();
[buttonName].Text="someting";
}
}
If this would work i could reduce my repetitive code a lot. How can i use the contents of a string as the name of a textBox?

You can use FindControl method to get the instance of the textbox and then use it :
TextBox txtBox = FindControl(tbName) as TextBox;
if(txtBox !=null)
txtBox.Text="someting";
But if the textBoxes are nested in the other controls, then you will need to recursively look in to every control to find the needed text box control explained at following:
https://msdn.microsoft.com/en-us/library/y81z8326.aspx

Related

I have multiple text boxes (tbVarName1, tbVarName2, ... tbVarName[n]) and I want to increment them in a for loop to assign the text to something

I have a multiple text boxes that I want to assign their string content to a variable however I'm not sure how to increment the text boxes. They are named, tbVarName1, tbVarname2, et cetera. Below is the for loop I have, right now I just have tbVarName1 hard coded in.
I have researched some of what other people have done and have only found tips for doing it in VB.
for(seriesIndex = 1; seriesIndex <= 4; seriesIndex++)
{
dataChart.Series["Variable " + seriesIndex].LegendText = tbVarName1.Text
}
At the end of this I would like the the legends to be updated to what's in the text boxes
Another way to do it is using the Controls collection from the Form (assuming that all TextBoxes are direct children of the form)
var ctrl = this.Controls.OfType<TextBox>();
for(seriesIndex = 1; seriesIndex <= 4; seriesIndex++)
{
TextBox t = ctrl.FirstOrDefault(c => c.Name == "tbVarName" + i);
if(t != null) dataChart.Series["Variable " + seriesIndex].LegendText = t.Text;
}
This will not require an array but you could end with a bigger loop if you have many controls of type textbox and it is not worth the effort if the TextBox are children of different containers (panels, groupboxes)
There are various ways to do this, one way is to add the controls into an array, for example:
var controls = new [] { tbVarName1, tbVarName2, tbVarName3 };
And now you can access them by index:
for(seriesIndex = 1; seriesIndex <= 4; seriesIndex++)
{
dataChart.Series["Variable " + seriesIndex].LegendText = controls[seriesIndex - 1].Text;
// ^^^^^^^^^^^^^^^^^^^^^^^^^
// Like this
// Note: arrays start at zero
}

Putting labels in an array using for loop in Visual Studio C#

I want to put labels in an array on form load but instead of coding them one by one, I want to use a for loop but I don't know how this works in C#.
My Code:
Dates[0] = this.labelrect0;
Dates[1] = this.labelrect1;
Dates[2] = this.labelrect2;
Dates[3] = this.labelrect3;
What I want to do:
for(int n = 0; int > array.Count; c++)
{
Dates[n] = this.labelrect+n; //how do i concatenate n to labelrect?
}
if Dates is an Label[] you can try this:
for(int n = 0; n < array.Count; n++)
{
Dates[n] =(Label) Controls.Find("labelrect"+n, true)[0];
}
You can use Controls property. If you have a Container control which contains these labels, then you can get the collection of controls contained within the control with <ContainerID>.Controls.
I normally will put the Index of the Label in the Tag Property then I would then iterate through the Control Collection using the Tag to assign the Control to the proper Index. Something like this.
for (int i = 0; i < Controls.Count; i++)
{
if(Controls[i] is Label)
Dates[int.Parse(Controls[i].Tag.ToString())] = (Label)Controls[i];
}

Populating consecutive Textboxes and Labels w.r.t the Index of the value in a collection

I have, in a form, consecutive textboxes and labels named tb1,tb2,tb3... and label1,label2,label3....
I have a dictionary holding number of Key value pairs.
How to populate the labels and textboxes corresponding to the value pairs in the dictionary?
Eg: dic.Key[1] -> label1 and dic.value[1] to tb1... like that.
I don't get any idea to try this.
In the other answer it is suggested to create a collection of labels and textboxes. My concern with that approach is that a developer may forget to do that or the order may get changed.
Every control has the Name property which stores that control's name. This property is set by Visual Studio. In your code, if you are not playing (read changing) with the Name property of controls, you can use the below code to achieve what you wanted to.
for(int i = 0; i < dic.Count; i++)
{
// As Control.Find returns an array of controls whose name match the specified string,
// in this example I had picked the first control
// you can make it more robust by checking
// - the number of controls returned,
// - the type of control, etc
TextBox txt = (TextBox) this.Controls.Find("tb" + (i + 1).ToString(), true)[0];
Label lbl = (Label) this.Controls.Find("label" + (i + 1).ToString(), true)[0];
txt.Text = dic[i].Value;
lbl.Text = dic[i].Key;
}
Your best bet would simply be to initialize a List (or two) in your form's constructor, putting all your labels and text boxes inside, so you can check them while looping through your dictionary.
private List<Label> labels = new List<Label>();
private List<TextBox> textBoxes = new List<TextBox>();
public MyForm()
{
labels.Add(myLabel1);
labels.Add(myLabel2);
labels.Add(myLabel3);
textBoxes.Add(myTB1);
textBoxes.Add(myTB2);
textBoxes.Add(myTB3);
}
private void addValuesFromDictionary(Dictionary<string, string> dic)
{
for (int i = 0; i < dic.Count; i++)
{
labels[i].Text = dic[i].Key;
textBoxes[i].Text = dic[i].Value;
}
}

What is windows form c# writeline equivalent

I have created an order form that includes a 16 length string array. Depending on the customer selection, I need the info from the array to appear in a text box e.g order summary. I can't figure it out. Here is sample code from one radio button and one check box. If these were selected how do I get the selection to display in a box? Please note I already have the "cost" part of it working correctly.
//Handle CPU Box Radio Btn
if (rdInteli3.Checked)
{
cost += 100.00;
item [0] = "Intel i3";
}
//Handle Hard Drive Check Box
if (ckHardDrive1Tb.Checked)
{
cost += 200.00;
item[11] = "1 TB Hard Drive";
}
I've tried this. Didn't work.
for (int i = 0; i < 16; i++)
{
txtSummary.Text = item[i];
}
Thanks
You'll have a multi-line TextBox control. You can append text to the control by calling its AppendText method. You code would look like this:
txtSummary.Clear();
for (int i = 0; i < 16; i++)
{
txtSummary.AppendText(item[i]);
}
You may wish to include new lines each time you add an item. In that case change the code like so:
txtSummary.AppendText(item[i]);
txtSummary.AppendText(Environment.NewLine);
or perhaps:
txtSummary.AppendText(item[i] + Environment.NewLine);
An alternative form is to use concatenation on the Text property:
txtSummary.Clear();
for (int i = 0; i < 16; i++)
{
txtSummary.Text += item[i] + Environment.NewLine;
}
And yet another option would be to build the text outside the control, for instance using a StringBuilder instance, and then assigning it all to the Text property in one go.
I guess that you want to use MessageBox:
MessageBox.Show("Hello World");
What is windows form c# writeline equivalent
Its the same Console.WriteLine but since there is no console you will see the output in Output window.
I need the info from the array to appear in a text box
You need to build a string , better if you use StringBuilder. Append your data there and then assign the result to your TextBox.Text property.
If your data is in array item then , its better if you use string.Join like:
txtSummary.Text = string.Join(Environment.NewLine, item);
If you want to use StringBuilder then you can do:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < item.Length; i++)
{
sb.Append(item[i]);
}
txtSummary.Text = sb.ToString();
Using string builder, how do I had space between the selection and
maybe a comma?
You can do:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < item.Length; i++)
{
sb.Append(item[i]);
sb.Append(" ,");
}
txtSummary.Text = sb.ToString().Trim(',',' ');
Or better
txtSummary.Text = string.Join(" ,", item);
You can use StringBuilder or String.Format to build a complete string that you want to show to the user. String.Format uses similar semantics as WriteLine.
Then assign this string to a MessageBox, a label or a textfield on your form or whereever you want it.
You can use that:
using System.Diagnostics;
Debud.WriteLine("This is test string");
You can check the result at the Output Window

Get value from multiple TextBox elements

I have a few different TextBox elements named as followed "e0", "e1", "e2", "e3". I know how many there are and I just want to be able to loop through them and grab their values rather than typing each one out manually.
I'm assuming I'll be doing something like this, I just don't know how to access the element.
for(int i= 0; i < 4; ++i) {
string name = "e" + i;
// How do I use my newly formed textbox name to access the textbox
// element in winforms?
}
I would advise against this approach since it's prone to errors. What if you want to rename them, what if you'll forget about this and add other controls with name e...?
Instead i would collect them in a container control like Panel.
Then you can use LINQ to find the relevant TextBoxes:
var myTextBoxes = myPanel.Controls.OfType<TextBox>();
Enumerable.OfType will filter and cast the controls accordingly. If you want to filter them more, you could use Enumerable.Where, for example:
var myTextBoxes = myPanel.Controls
.OfType<TextBox>()
.Where(txt => txt.Name.ToLower().StartsWith("e"));
Now you can iterate those TextBoxes, for example:
foreach(TextBox txt in myTextBoxes)
{
String text = txt.Text;
// do something amazing
}
Edit:
The TextBoxes are on multiple TabPages. Also, the names are a little
more logical ...
This approach works also when the controls are on multiple tabpages, for example:
var myTextBoxes = from tp in tabControl1.TabPages.Cast<TabPage>()
from panel in tp.Controls.OfType<Panel>()
where panel.Name.StartsWith("TextBoxGroup")
from txt in panel.Controls.OfType<TextBox>()
where txt.Name.StartsWith("e")
select txt;
(note that i've added another condition that the panels names' must start with TextBoxGroup, just to show that you can also combine the conditions)
Of course the way to detect the relevant controls can be changed as desired(f.e. with RegularExpression).
You can use parent of your controls like this(Assuming you have placed all controls in the form, so I have used this)
for(int i= 0; i < 4; ++i) {
string name = "e" + i;
TextBox txtBox=this.Controls[name] as TextBox;
Console.Writeline(txtBox.Text);
}
Try this :
this.Controls.Find()
for(int i= 0; i < 4; ++i) {
string name = "e" + i;
TextBox txtBox = this.Controls.Find(name) as TextBox;
}
Or this :
this.Controls["name"]
for(int i= 0; i < 4; ++i) {
string name = "e" + i;
TextBox txtBox = this.Controls[name] as TextBox;
}

Categories

Resources