How to assign dynamically created objects to a string? - c#

I have a form with this code assigned to a button:
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.Visible = true;
tbxActualCant.Width = 44;
tbxActualCant.MaxLength = 4;
this.Controls.Add(tbxActualCant);
iVertical = iVertical + 35;
}
And this code creates textboxes dynamically, one for every "button click", so I can have an "add" button to call it and the user can write a list of things that is not limited.
The question is: How can I assign these "textboxes.Text" to a string? They haven't got a name :S
something like:
string sAllBoxes = tbx1.Text + tbx2.Text + "..." + tbxN.Text;
Thanks!!

If your tbxCantServ is defined as local to a method, then you have to assign a Name to your TextBoxes like:
int counter = 0;
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);
iVertical = iVertical + 35;
}
And later in some other method if you want to get the joined text then you can do:
string sAllBoxes = string.Join(",", this.Controls.OfType<TextBox>()
.Where(r => r.Name.StartsWith("tbx"))
.Select(r => r.Text));
But if you have tbxCantServ defined at class level then you can do:
string sAllBoxes = string.Join(",", tbxCantServ
.Where(r=> r != null)
.Select(r => r.Text));
In string.Join, you can replace , with an empty string or any string depending on your requirement.

You can do it in the same way you created them.
Try this:
string sAllBoxes="";
foreach (TextBox tbxActualCant in tbxCantServ)
{
sAllBoxes+=tbxActualCant.Text;
}
OR
Using a StringBuilder:
StringBuilder textBuilder = new StringBuilder();
foreach (TextBox tbxActualCant in tbxCantServ)
{
textBuilder.Append(tbxActualCant.Text);
}
string allText = textBuilder.ToString();

If you have access to your textbox array, you can easily do this:
string sAllBoxes = string.Join(" ", tbxCantServ.Select(x => x.Text));
If you don't then use Control collection of your Form, and give name to your textboxes so you can access them using this.Controls[txtBoxName].
If you just want to concatanate your texts without a separator, you can also use string.Concat method:
string sAllBoxes = string.Concat(tbxCantServ.Select(x => x.Text));

Related

Array in a textbox C#

I'm new in C#, and I'm trying to show an array in a textbox using window forms.
The problem is that when I give the command txtTela.Text = tela.ToString();, the program compiles successfully, but the result in the textbox is "System.String[]", and not the string that I'd like to show.
Image of what is printed in the textbox: https://snag.gy/L34bfM.jpg
public String[] comboPalavra;
public String []tela = new String[1];
public Form1()
{
InitializeComponent();
comboPalavra = embaralhaPalavra.CarregaPalavra();//Recebe uma palavra e uma dica
//MessageBox.Show(comboPalavra[0]);
foreach(char element in comboPalavra[0])
{
this.tela[0] = tela + "#";
}
txtTela.Text = tela.ToString();
txtDica.Text = comboPalavra[1].ToString();
}
You need to convert your string array into single string. You can do this by string.Join().
textBox.Text = string.Join(separator, stringArray);
or
textBox.Text = string.Join(separator, stringArray.Select(x => x.ToString()));
Or with linq expression (using System.Linq):
textBox.Text =stringArray.Aggregate((x, y) => x + separator + y);
You defined 'tela' as an array of String and applied the .ToString()-method directly to that array-object, which is why it ended in: System.String[]
public String []tela = new String[1];
txtTela.Text = tela.ToString();
To print a specific element, you need to define which element you want to print:
txtTela.Text = tela[0];

How to make string list to "string array"

This is what I want to convernt: {"apple", "banana"} to "["apple", "banana"]"
I have tried convert string list to string array first, then convert string array to string, but did not work.
var testing = new List<string> {"apple", "banana"};
var arrayTesting = testing.ToArray();
var result = arrayTesting.ToString();
You can use string.Join(String, String[]) method like below to get a , separated string values (like csv format)
var stringifiedResult = string.Join(",", result);
You can try this, should work;
var testing = new List<string> { "apple", "banana" };
var arrayTesting = testing.ToArray<string>();
var result = string.Join(",", arrayTesting);
You can also use StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\"[");
for (int i = 0; i < arrayTesting.Length; i++)
{
string item = arrayTesting[i];
sb.Append("\"");
sb.Append(item);
if (i == arrayTesting.Length - 1)
{
sb.Append("\"]");
}
else
sb.Append("\",");
}
Console.WriteLine(sb);
Instead of converting it to an array, you could use a linq operator on the list to write all the values into a string.
string temp = "";
testing.ForEach(x => temp += x + ", ");
This will leave you with a single string with each value in the list separated by a comma.

Making empty textbox

When I want to clear the following array:
userInfo[0] = txtPassword.Text;
userInfo[1] = txtVoornaam.Text;
userInfo[2] = txtAchternaam.Text;
userInfo[3] = txtWoonplaats.Text;
userInfo[4] = txtPostcode.Text;
userInfo[5] = txtTelnr.Text;
I'm doing the following:
for (int i = 0; i < 5; i++)
{
userInfo[i] = "";
}
That obviously doesn't work and when I try this:
foreach (string item in userInfo)
{
item = "";
}
Also does not work. How can I do this without saying:
userinfo[0] = txtPassword;
If you want to treat them array-like, you need to add them to an array, or rather and much better a List<TextBox>. Do it once and you can loop over it for any or your needs..
Do it once..:
List<TextBox> boxes = new List<TextBox>()
{ txtPassword, txtVoornaam, txtAchternaam, txtWoonplaats, txtPostcode, txtTelnr};
Now you can pull out the values into a string array
string[] myTexts = boxes.Select(x => x.Text).ToArray();
..or a List :
List<string> myTexts = boxes.Select(x => x.Text).ToList();
or you can clear them all:
foreach (TextBox tb in boxes) tb.Text = "";
If you need to you can access the List elements by variable:
boxes.Find(x => x == textBox2).Text = "12345";
..or by Name:
boxes.Find(x => x.Name == "txtVoornaam").Text = "Jens";
(All checks omitted..)

print the contents of a list <> in a textbox

good morning, I'm having trouble with the following. I'm reading the contents of a file (. txt) in a folder, but what I want now is to print the contents of the files into a textbox, but I'm having problems with that.
what I have to code this is.
FolderBrowserDialog Lectura = new FolderBrowserDialog();
DialogResult response = Lectura.ShowDialog();
if (response == DialogResult.OK)
{
string[] files = Directory.GetFiles(Lectura.SelectedPath);
ListBox archivosListBox = new ListBox();
archivosListBox.Items.AddRange(files);
int tamanoLista = archivosListBox.Items.Count;
List <string[]> Miarchivo = new List<string[]>();
foreach (string archivos in archivosListBox.Items)
{
Miarchivo.Add(System.IO.File.ReadAllLines(archivos));
}
string[] leerArchivo;
int j =Miarchivo.Count;
for (int i = 0; i<tamanoLista; i++)
{
leerArchivo = Miarchivo[i];
for (int k = 0; k < Miarchivo[i].Count(); k++)
{
//textBox1.Text += leerArchivo[k] ;
}
}
}
You need to place a newline character after each entry in your TextBox. Change your code to following:
for (int k = 0; k < Miarchivo[i].Count(); k++)
{
textBox1.Text += leerArchivo[k] + Environment.NewLine;
}
More reading: Environment.NewLine Property (MSDN).
Use ReadAllText instead of ReadAllLines and replace entire loop with string join:
List<string> Miarchivo = new List<string>();
foreach (string archivos in archivosListBox.Items)
Miarchivo.Add(File.ReadAllText(archivos));
textBox1.Text = String.Join(Environment.NewLine, Miarchivo);
Another (probably better solution) is usage of TextBox.Lines property and getting files content with LINQ:
textBox1.Lines = archivosListBox.Items
.Cast<string>()
.SelectMany(archivos => File.ReadLines(archivos))
.ToArray();
You'd rather update textBox1.Text once in order to avoid constant repainting:
if (response == DialogResult.OK)
{
string[] files = Directory.GetFiles(Lectura.SelectedPath);
ListBox archivosListBox = new ListBox();
archivosListBox.Items.AddRange(files);
int tamanoLista = archivosListBox.Items.Count;
List <string[]> Miarchivo = new List<string[]>();
foreach (string archivos in archivosListBox.Items)
{
Miarchivo.Add(System.IO.File.ReadAllLines(archivos));
}
// Output into textBox1
StringBuilder sb = new StringBuilder();
foreach(String[] leerArchivo in Miarchivo)
foreach(String item in leerArchivo) {
if (sb.Length > 0)
sb.AppendLine(); // <- Or other deriver, e.g. sb.Append(';');
sb.Append(item);
}
// Pay attention: textBox1 has been updated once only
textBox1.Text = sb.ToString();
}
Based on your comments it sounds like you just need a line break at the end of each line:
textBox1.Text += leerArchivo[k] + Environment.NewLine ;

append ". " after selected item values of checkbox list

I have a check box list item with List items in it. When i save the form selected values should be save to database .
See my logic.
string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
It is working great but because of the "," which is i am putting between two values they are separated with each other, but at last item also it will append the "," . Is there any way to remove last "," or insert "." at last ","
Is there any logic for doing this?
Join all selected items, using string.Join and LINQ:
Type = string.Join(",",
chbCourse.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Text));
Since string.Join only adds the separator between items, it won't add an extra comma to the end.
(Also, calling ToString() on a ListItem displays the class type; you have to use the Text property.)
void Main()
{
var a="1,2,3,";
a=a.TrimEnd(new [] {','});
Console.WriteLine (a); //1,2,3
}
Do it like this for selected items:
string Type = string.Join(",", CheckBoxList1.Items.Cast<ListItem>().Where(a=>a.Selected).Select(a => a.Text));
if (!string.IsNullOrEmpty(Type)) // To add '.' at end
Type = Type + ".";
The easiest way is to use String.Join:
string Type = String.Join(",", chbCourse.Items);
If "." is also required
string Type = String.Concat(String.Join(",", chbCourse.Items),".");
If I'd wanted to put dot (".") on the last character, then I would do:
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
if (i == chbCourse.Items.Count - 1) Type += chbCourse.Items[i].ToString() + ".";
else
Type += chbCourse.Items[i].ToString() + ",";
}
}
string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
if(Type != null)
Type = Type.TrimEnd(',');
Try not to use Class Names as variable names.
How about
string Type = null;
type = String.Join(",",
chbCourse.Items.Where(Function(x) x => x.Selected)
.Select(Function(y) y => y.ToString()).ToArray);

Categories