Use variable as part of textbox name in C# - c#

I am developing a program wth 30 text boxes and 30 check boxes next to them. I want people to check names and then press the send button. The program then saves the names in a txt file with a true or false statement next to them, it then uploads the file to a ftp server for me analize.
The problem I am facing is that I don't want to write code for every text and check box to load and save it's value on the txt file.
If I name the text boxes something like tbox1;tbox2;tbox3 etc. How would use a loop to say write the value of tbox i + ; + cbox i on line i of thing.txt or vice versa?
Please any help would be grately apreciated because this will save me a lot of unnesacery code writing!

You should create a List<TextBox>, and populate it with your textboxes in the constructor.
You can then loop through the list and process the textboxes.

for (int i = 0; i <= count; i++)
{
TextBox textbox = (TextBox)Controls.Find(string.Format("tbox{0}", i),false).FirstOrDefault();
CheckBox checkbox = (CheckBox)Controls.Find(string.Format("cbox{0}", i),false).FirstOrDefault();
string s = textbox.Text + (checkbox.Checked ? "true" : "false");
}

You can loop over all the controls on your form and retrieve the values from them based on their type/name.

Loop through controls in your form/control and investigate name:
foreach (Control control in f.Controls)
{
if (control is TextBox)
{
//Investigate and do your thing
}
}

Assuming this is ASP.NET, you could use something like this:
StringBuilder sb = new StringBuilder();
for(int i = 1; i < 30; i++){
TextBox tb = FindControl("TextBox" + i);
Checkbox cb = FindControl("CheckBox" + i);
sb.AppendFormat("TextBox{0}={1}; {2}", i, tb.Text, cb.Checked);
}
string result = sb.ToString();
// Now write 'result' to your text file.

Related

Grid full of textboxes, c#, XAML

for start i have to say, when i'm not so good in english, so i'm sorry for my faults and grammar.
I have easy timetable created from lot of text boxes, that are in group grid. I have one buttom, that serving to add some text into textboxes. User will add some text into texbox, will click on button (Create) and will create the complete timetable, what he need.
And there is a problem. I could save all of input manually in method SaveState like this: e.PageState["something"] = gui_Something.Text; , but i have 3 grids where is 40 textboxes... I need some way to save it all in one method, or something like that. It looks like field, but it is not. In field i can do something like:
int[] field = new int[5];
int some = 0;
for (int i = 0; i < field.Length; i++)
{
field[i] = some;
e.PageState["Something" + i] = gui_poznamky.Text;
}
but my grid full of textboxes is not field xD
Can someone help me please? I'm beginner, i started with programing short time ago, so sometimes i need some help.
Thank for all answers and again i'm sorry for my english (:
You could try something like this to iterate though all the controls in the grid, and then do some fancy work to find where each textboxs' data should be saved to...
foreach (Control childCtrl in MainGrid.Children)
{
if (childCtrl is TextBox)
{
TextBox Txtbox = (TextBox)childCtrl;
Console.WriteLine("Found Textbox: " + Txtbox.Name);
}
}

Looping textbox IDs for retrieving text from textboxes in C#

I have 50 text boxes starting from TextBox1 till TextBox50. I want to retrieve values from all these 50 text boxes. I tried looping but it failed. I want some code like TextBox(i).Text where i varies from 1 to 50.
The loop should produce the following result.
Response.Write(TextBox1.Text);
Response.Write(TextBox2.Text);
son on till
Response.Write(TextBox50.Text);
How can I achieve this?
You can use FindControl which takes a string as parameter, pass it "TextBox" + i like:
TextBox tb = this.FindControl("TextBox" + i) as TextBox;
if (tb != null)
{
Response.Write(tb.Text);
}
You can loop thought them simply as following :
string value=""; // store each textbox value in this variable
foreach (Control x in this.Controls) // loop through the controls in the form
{
if (x is TextBox) // if the program found a textbox in the form
{
value = (x as TextBox).Text; // set the value of the textbox number x to the string value
listBox1.Items.Add(value); // here is a listbox to show the resule
}
}

Check Label in email and delete specific ones

I have this code that is suppose to check each label for the word "closed", and after its done checking it will remove all the text that is in the labels and place everything thats NOT labeled "closed" into the TO section of an email. I dont know what im doing wrong but it doesnt work. Any suggestions?
foreach (Control c in Controls)
{
if (c is Label)
{
// Grab label
Label lbl = c as Label;
if (lbl.Text.Contains("closed"))
{
lbl.Text.Replace("closed", "");
}
}
}
Apparently you forgot to assign the modified text value, because Replace() method returns replaced text as return value:
lbl.Text = lbl.Text.Replace("closed", "");
But there might be more problems with your code, it's not very clear how is your problem related to emails.
Initially take your input (i.e. label list in a List)
List<string> TotalLabels = GetAllLabels();
for (int i = 0; i < TotalLabels.Count; i++)
{
if (TotalLabels[i].Contains("closed"))
{
TotalLabels.RemoveAt(i);
i--;
}
}
Now you have a final list which you wanted removing "closed".

Append int to end of string or textbox name in a For Loop C#

I have a C# application in which there are several textboxes with the same name except for a number on the end which starts at 1 and goes to 19. I was hoping to use a for loop to dynamically add values to these text boxes by using an arraylist. There will be situations where there will not be 19 items in the arrayList so some text boxes will be unfilled. Here is my sample code for what I am trying to do. Is this possible to do?
for (int count = 0; count < dogList.Count; count++)
{
regUKCNumTextBox[count+1].Text=(dogList[count].Attributes["id"].Value.ToString());
}
So you've got a collection of text boxes that are to be filled out top-to-bottom? Then yes, a collection of TextBox seems appropriate.
If you stick your TextBox references in an array or a List<TextBox> -- I wouldn't use an ArrayList as it's considered deprecated in favor of List<T> -- then yes, you can do that:
TextBox[] regUKCNumTextBox = new []
{
yourTextBoxA,
yourTextBoxB,
...
};
Then yes your logic is possible, you can also query the control by it's name, though that would be heavier at runtime - so it's a tradeoff. Yes, in this solution you must set up a collection to hold your text box references, but it will be more performant.
Try this:
(By the way I am assuming you use WinForms)
for (int count = 0; count < dogList.Count; count++)
{
object foundTextBox = this.Controls.Find("nameofTextBoxes" + [count+1]);
if (foundTextBox != null)
{
if (foundTextBox is TextBox)
{
((TextBox)foundTextBox).Text=(dogList[count].Attributes["id"].Value.ToString());
}
}
}
With this code you are trying to find a Control form your Forms Controls collection. Then you have to make sure the control is of the TextBox type. When it is; cast it to a TextBox and do what you want with it. In this case; assign a value to the Text property.
It would be more efficient to keep a collection of your TextBoxes like in the solution offered by James Michael Hare
Yikes; something doesn't seem quite right with the overall design there; but looking past that, here's a quick stab at some pseudo code that might work:
for (int count = 0; count < dogList.Count; count++)
{
var stringName = string.Format("myTextBoxName{0}", count);
var ctrl = FindControl(stringName);
if(ctrl == null) continue;
ctrl.Text = dogList[count];
}

Programatically reference ascending variable names (var1, var2, ... )

I'm currently coding a project that can take up to 200 entries of a specific product, as determined by user input. Basically, my GUI loads, and I use jQuery to dynamically build the entries whenever there is a change to the amount field. When using jQuery, I simply give each of them ids in the form of variable1, variable2, ...., variableX (where X is the amount of entries indicated). Small snippet of code to clarify:
for(var i = 1;i <= amount_selected; i++) {
$('table_name tr:last').after('<tr><td><input type="text" id="variable' + i + '"></td></tr>');
}
Now when I try to move to the back end, I'm trying to reference these variable names by putting them in a list. I went ahead and put them in a list of HtmlInputText, to call the Variable names from the list itself. (This would save having to call all (up to 200) methods manually, which is really not an option).
So what I did (in C#) was:
List<HtmlInputText> listvar = new List<HtmlInputText>();
for(int i = 1; i <= amount_selected; i++) {
string j = "variable" + Convert.ToString(i);
HtmlInputText x = j;
listvar.Add((x));
samplemethod(listvar[i]);
}
But it's not working at all. Does anyone have any ideas as to how this would be done, without doing so manually? I know my logic might be completely off, but hopefully this illustrates at least what I'm attempting to do.
I'm assuming these inputs are in a form? If you're submitting then you can access the text boxes from the Request object:
List<string> results = new List<string>();
for (int i = 1; i <= amount_selected; i++)
{
string s = String.Format("{0}", Request.Form["variable" + Convert.ToString(i)]);
results.Add(s);
}
you could do $("#variable" + Convert.ToString(i)).val()

Categories