Variable IDs in C# - c#

When programming a Windows Forms application I found myself having to create a variable amount of text fields according to the number of inputs.
I decided to name these name1, name2, name3, ..., nameN.
Now I want to be able to save the user's input to a text file. To do this I need to get the text from the text boxes into separate variables to be able to write this to the text file.
This would result in a for loop like this:
for(i=0; i < totalnames; i++)
{
string varname= "name" + i;
}
But this way I cannot get the value from the text boxes. How can I get the separate values from the text boxes to write them to the text file?
Thank you,

When you create the form controls, keep references to them in a list:
// probably at the class level...
List<TextBox> myTextBoxes = new List<TextBox>();
// then when you create them...
myTextBoxes.Add(name1);
// etc.
Then later, when you need to reference them, use the list:
foreach (var textBox in myTextBoxes)
{
// get the value from the text box and use it in your output
}

You can create a List of string List and add your name in it. Then use StreamWriter to add the name in your file:
List<string> myListOfNames = new List<string>();
int totalnames = 10;
for (int i = 0; i < totalnames; i++)
{
myListOfNames.Add("name" + i);
}
using (StreamWriter writer = new StreamWriter("C:\\MyTextFile.txt", true))
{
foreach (string name in myListOfNames)
{
writer.WriteLine(name);
}
}

Here is my two pennies worth, because the OP originally said Windows Form Application - I would have a Save button, which when fired, the code behind will grab all the Textboxes and save to the file. You can add your own filtering for textboxes yourself if you want.
Firstly here is the code behind for the button event:
private void saveToFile_Click(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter("C:\\k\\saveToFile.txt", true))
{
if (this.Controls.Count > 0)
{
var textBoxes = this.Controls.OfType<TextBox>();
foreach (TextBox textbox in textBoxes)
{
writer.WriteLine(textbox.Name + "=" + textbox.Text);
}
}
}
}
A simple forn to prove the point, each TextBox has a name of name1 etc.
Also here is an example output of the file:
Improvements
Filtering on the Textboxes - you may only want to do this for some textboxes for a particular name.
Loading the file. I have added the textbox name to the file, so theorically you could load the data back into the textboxes.

Related

AutoComplete textBox from a certain position of each line of a .txt file

I have a textBox named "textBoxCliente" and I want it to appear suggestions when I writte in there from the .txt file.
The suggestions that I want to appear from the .txt file are in the position 1 "parts[1]", each position are separated with the caracter "|".
My .txt file is this:
1|Rui|Lisboa|rui#hotmail.com|912345324|14/01/2000|89564352|Empresa
2|Henrique|Evora|henrique#hotmail.com|914445324|17/05/2001|55464352|Particular
3|Andre|Agueda|andre#hotmail.com|932415374|12/11/1996|23456743|Particular
4|Pedro|Aveiro|pedro#hotmail.com|965342163|30/03/2002|98645372|Empresa
My code is:
public partial class Vender : UserControl
{
public Vender()
{
InitializeComponent();
}
string dir = (Environment.CurrentDirectory + "/Bd/clientes.txt");
string[] sug = new string[File.ReadAllLines(Environment.CurrentDirectory +
"/Bd/clientes.txt").Count()];
private void textBoxCliente_TextChanged(object sender, EventArgs e)
{
carrSug();
for (int i = 0; i < sug.Length; i++)
{
textBoxCliente.AutoCompleteCustomSource.Add(sug[i]);
}
textBoxCliente.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
}
private void carrSug()
{
string[] lines = File.ReadLines(dir).ToArray();
int nLine = File.ReadAllLines(dir).Count();
for (int j = 0; j <= nLine - 1; j++)
{
string[] parts = lines[j].Split(new char[] { '|' });
sug[j] = parts[1];
}
}
}
What I did was using the "string[] sug" to save the values of the position 1 of each line and then use it to show the suggestions.
As a programmer, get better at reading carefully. Here is the documentation for AutoCompleteCustomSource:
Gets or sets a custom System.Collections.Specialized.StringCollection to use when the System.Windows.Forms.TextBox.AutoCompleteSource property is set to CustomSource.
Emphasis Mine
See the bolded part in the above, make sure you do that:
textBoxCliente.AutoCompleteSource = AutoCompleteSource.CustomSource;
Also, you do not need to do that every time the user types. The event handler textBoxCliente_TextChanged will be called every time the text changes. Instead, put the code in the constructor or in the form's load event.
Some Suggestions
Give your methods meaningful names. For example, carrSug() is not very meaningful. Plus it does not follow the C# coding conventions--it looks like Java. Also, keep the method cohesive. You are doing some parts of the suggestion in the carrSug() and then some of it you are doing in textBoxCliente_TextChanged. Here is a more meaningful method:
private AutoCompleteStringCollection clientSuggestions;
private void LoadClientSuggestions()
{
this.clientSuggestions = new AutoCompleteStringCollection();
string[] suggestionsFromFile = File.ReadLines("YourPath.txt").Select(x => x.Split('|').Skip(1).First()).ToArray();
this.clientSuggestions.AddRange(suggestionsFromFile);
}
The above method uses Ling so make sure to import: using System.Linq;
Here is how to use it (Put this code in your form's constructor or Load method):
this.LoadSuggestions();
this.textBoxCliente.AutoCompleteSource = AutoCompleteSource.CustomSource;
this.textBoxCliente.AutoCompleteCustomSource = this.clientSuggestions;
this.textBoxCliente.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
Why did I put the word Load in the method name? Because, it returns nothing so Load adds meaning.
Also, stop writing the same string multiple times:
"/Bd/clientes.txt"
Make that a constant so if you need to change it, you change it in one place.

Select one string line in a list

I'm trying to simply select one string line out a long list strings that are held on a server and seperated with a pipe character. This string is grabbed by a php script and the string line is a list of all the media and folders I have on my server.
In my code I'm getting this information and returning it with the following code:
using (var client = new WebClient())
{
result = client.DownloadString("http://server.foo.com/images/getDirectoryList.php");
}
textBox1.Text = string.Join(Environment.NewLine, result.Split('|'));
And it looks like this:
But when I try to simply click on one of them, my cursor simply just goes to where I've clicked. Like this, I tried to select md-harrier.jpg and my cursor just ends up at the end of jpg:
What I'm really wanting is pictured below. I click on Koala.jpg and the whole thing is highlighted and I have the ability to store the name of what it is I've just clicked on. TO achieve that screen shot I had to click next to Koala.jpg and then drag my mouse along.
Is there anyway I can achieve what I want to achieve?
The key thing to note about this is that I will have no idea how many files will be on the server, nor what they will be called. My php script is grabbing this information and displaying it in my winform text box using the code I have wrote above.
as Simon said you need a ListBox, a ListBox fits here because it allows you to select a line, and you can register to the event of SelectedIndexChanged and store the name that was selected.
to initiate the values do
using (var client = new WebClient())
{
result = client.DownloadString("http://bender.holovis.com/images/getDirectoryList.php");
}
listBox1.Items.AddRange(result.Split('|'));
listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
and on the selectedItemChanged:
string currVal;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
currVal = (string)listBox1.SelectedItem;
}
As you said you have no reason to use TextBox,then by using ListBox you can achieve that in this way;
using (var client = new WebClient())
{
result = client.DownloadString("http://bender.holovis.com/images/getDirectoryList.php");
}
string[] names=result.Split('|');
foreach(string name in names)
{
if(name!="|"&&name!=" ")
{
listbox.Items.Add(name);
}
}
Additionally,if you would like to store selected item in a variable subscribe to ListBox's SelectionChangedEvent and store the selection index in a variable in this way;
int selection=;
private void ListBox1_SelectionIndexChanged(object sender,EventArgs e)
{
selection=ListBox1.SelectedIndex;
}

How to change checkbox text in checkboxlist? I tried but got error message

I work on windows application. It has one form in application which displays check boxes in check box list, here is the screen shot of form
It's single from of my application which i display in different languages And also my windows application is made in multiple languages Like English, German, Japanese etc..
My problem is that how to display translated text of check box in check box list
Here is my code :
this.checkedListBox1.FormattingEnabled = true;
this.checkedListBox1.Items.AddRange(new object[] {
"Select All",
"Amplitude1",
"Amplitude2",
"Amplitude3",
"Amplitude4",
"Amplitude5",
"Amplitude6",
"Amplitude7"});
this.checkedListBox1.Location = new System.Drawing.Point(96, 55);
this.checkedListBox1.Name = "checkedListBox1";
this.checkedListBox1.Size = new System.Drawing.Size(123, 124);
this.checkedListBox1.TabIndex = 8;
this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.ckbselectall_CheckedChanged);
I made a single file to translate text of form, i put that code below where LCheckBox is my file from where i translate the text of check box in check box list
this.checkedListBox1.FormattingEnabled = true;
this.checkedListBox1.Items.AddRange(new object[] {
LCheckBox.SELECTALL,
LCheckBox.Amplitude1,
LCheckBox.Amplitude2,
LCheckBox.Amplitude3,
LCheckBox.Amplitude4,
LCheckBox.Amplitude5,
LCheckBox.Amplitude6,
LCheckBox.Amplitude7});
this.checkedListBox1.Location = new System.Drawing.Point(96, 55);
this.checkedListBox1.Name = "checkedListBox1";
this.checkedListBox1.Size = new System.Drawing.Size(123, 124);
this.checkedListBox1.TabIndex = 8;
this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.ckbselectall_CheckedChanged);
But it gives me some error message
you can ask for the language at the begining and then create the checkbox list depending on the language. u can use different if cases for each language
In code I just use the items collection to modify the desired item.
So lets say you have a form with a button on it. When the button is clicked
you want to add one to all the items in the list, then the code to do that
would look as found below assuming that the listbox was named "_list" and
the button was named "_button."
private void FillList()
{
_list.BeginUpdate();
_list.Items.Clear();
for(int i =0 ; i <=9; i++)
_list.Items.Add(i);
_list.EndUpdate();
}
private void _button_Click(object sender, System.EventArgs e)
{
_list.BeginUpdate();
ListBox.ObjectCollection items = _list.Items;
int count = items.Count;
for(int i = 0; i < count; i++)
{
int integerListItem = (int)items[i];
integerListItem ++;
// --- Update The Item
items[i] = integerListItem;
}
_list.EndUpdate();
}

Asp.Net Get Control Values from PlaceHolder

I have defined a placeholder in my page like this;
<asp:PlaceHolder ID="attrPlaceHolder" runat="server"></asp:PlaceHolder>
I am populating this place holder from a database table using query string productId like this;
// obtain the attributes of the product
DataTable attrTable = CatalogAccess.GetProductAttributes(productId);
// temp variables
string prevAttributeName = "";
string attributeName, attributeValue, attributeValueId;
// current DropDown for attribute values
Label attributeNameLabel;
DropDownList attributeValuesDropDown = new DropDownList();
// read the list of attributes
foreach (DataRow r in attrTable.Rows)
{
// get attribute data
attributeName = r["AttributeName"].ToString();
attributeValue = r["AttributeValue"].ToString();
attributeValueId = r["AttributeValueID"].ToString();
// if starting a new attribute (e.g. Color, Size)
if (attributeName != prevAttributeName)
{
prevAttributeName = attributeName;
attributeNameLabel = new Label();
attributeNameLabel.Text = "<li class=\"txt\">" + attributeName + ":</li>";
attributeValuesDropDown = new DropDownList();
attrPlaceHolder.Controls.Add(attributeNameLabel);
attrPlaceHolder.Controls.Add(attributeValuesDropDown);
}
// add a new attribute value to the DropDownList
attributeValuesDropDown.Items.Add(new ListItem(attributeValue, attributeValueId));
}
However, when inside a button click event, when I loop through this place using visual studio debugging, I saw that the visual studio studio debugger first hit the "attrPlaceHolder.Controls" word in my foreach loop, then secondly comes to 'in' keyword (in foreach loop) but it isn't hitting the first two words (i-e 'Control cnt' in my foreach loop. Here it looks;
protected void ButtonBuyNow_Click(object sender, EventArgs e)
{
// Retrieve the selected product options
string options = "";
foreach (Control cnt in attrPlaceHolder.Controls)
{
if (cnt is Label)
{
Label attrLabel = (Label)cnt;
options += attrLabel.Text;
}
if (cnt is DropDownList)
{
DropDownList attrDropDown = (DropDownList)cnt;
options += attrDropDown.Items[attrDropDown.SelectedIndex] + "; ";
}
}
// Add the product to the shopping cart
ShoppingCartAccess.AddItem(productId, options);
}
Basically I need 'options' variable to be populated but it isn't hitting the foreach loop inside, therefore I am not able to get the 'options' variable populated.
This is a serious problem in my application. Please tell me why I can't get the inside the foreach loop.
NOTE:
please note that this isn't the complete code of my entire page. My rest of the code executes correctly.
why I can't get the inside the foreach loop
Because the list is empty.
Why is the list empty? (Would be the next logical question)
Because, at ASP.Net, dynamically created controls must be re-created at Page_Init in order to exist. When you create them at this stage, the page lifecycle will bind the viewstate and will be ready for use.
If you receive a postback (from the button, for example) and don't recreate them, they simply don't exist.

Dynamically create text inputs (ASP.net/C#)

I have an input field on my page where the user will type in the number of text inputs they want to create. The action for the button is:
int num_flds = int.Parse(a_fld.Text);
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
}
Now, I have another button that the user would click after they have filled in all their dynamically-created text boxes. Questions, first of all, am I creating the text boxes dynamically in the correct place? How would I get the values out of the dynamically-created text boxes? (The dynamically-created text boxes are being added to the Panel "answer_inputs".
I recommend reading this and a few other articles about the topic of dynamically created controls. It is not quite as straightforward as you might think. There are some important page lifecycle issues to consider.
When creating web controls dynamically, I find it best to have the controls themselves report in the answers. You can achieve it like this:
Create something in your Page class to store the values:
private readonly Dictionary<TextBox, string> values=new Dictionary<TextBox, string>();
Make a method to act as a callback for the textboxes when their value changes:
void tmp_TextChanged(object sender, EventArgs e)
{
TextBox txt = sender as TextBox;
if(txt!=null)
{
values.Add(txt,txt.Text);
}
}
And then add this method to each textbox as they are added:
int num_flds;
if(!int.TryParse(a_fld.Text,out num_flds))
{
num_flds = 0;
}
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
tmp.TextChanged += tmp_TextChanged;
}
Finally, you iterate through the dictionary on callback to see if it holds any values. Do this in the OnPreRender method for instance.
Edit: There is a problem with this, if the number of text fields are decreased on postback. Some safe way to recreate the previous textfields on postback should be employed.

Categories

Resources