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];
Related
This code works fine on wpf.
In my code list1 will work but if convert a string to a list of char and change again to string it showing error of : can't convert from char[] to string [].
need suggestion.
here's the code :
string x = "hello";
List<char> list = x.ToList<char>();
//error
string combindedString = string.Join(",", list.ToArray());
string xz = string.Join("", list);
//---
//okay....
List<string> list1 = new List<string>()
{
"Red",
"Blue",
"Green"
};
string output = string.Join("", list1.ToArray());
in wpf:
Well I suspect the source of your issue still lies with using the older .Net Framework that is default with Unity, 3.5 I believe. You have some options, to work around the problem though:
You can target an update framework, I believe Unity supports up to 4.6.1 in experimental mode.
You can work around converting a char[] to string.
Or just use the string constructor:
A simple example:
[Test]
public void StringTest()
{
string x = "hello";
List<char> list = x.ToList<char>();
string newStr = new string(list.ToArray());
Assert.IsTrue(newStr == x);
}
This can easily be achieved with a loop.
string x = "hello"
List<char> list = x.ToList<char>();
string originalword = "";
foreach (var letter in list)
{
originalword += letter.ToString();
}
// original word is equal to hello
private void LineUpNumbers ()
{
Array.Sort(lineArray[currentSelectedLine]); // Sorts the array in ascending order.
string numberBox = "Line" + (currentSelectedLine + 1).ToString() + "NumberBox";
string nb;
Image[] CircleColours = new Image[6] {Properties.Resources.BlueCircle, Properties.Resources.RedCircle , Properties.Resources.OrangeCircle , Properties.Resources.PurpleCircle , Properties.Resources.GreenCircle , Properties.Resources.YellowCircle};
Random r = new Random();
CircleColours = CircleColours.OrderBy(x => r.Next()).ToArray();
for (int i = 0; i <6; i++) // Populates NumberBoxes with the numbers from the array
{
nb = numberBox + (i + 1);
Line1.Controls[nb].Text = lineArray[currentSelectedLine][i].ToString();
Line1.Controls[nb].BackgroundImage = CircleColours[i];
}
}
Hi,
In the above snippet I'd like to change Line1 to be a string variable, but I'm not sure on the correct syntax for doing so. Could anyone help with a solution for this? This is C#
Line1 is the GrouBox name.
I'd like to be able to change Line1 to a string. Like this:
string groupBoxName = "Line1";
groupBoxName.buttonName.BackgroundImage = CircleColours[i];
The code doesn't work though
You can use the Controls array of the Form this.Controls like this...
string groupBoxName = "Line1";
Control groupBox = this.Controls[groupBoxName];
groupBox.Controls[nb].BackgroundImage = CircleColours[i];
...just like the way you are getting the NumberBox dynamically from the Controls array of the GroupBox.
Trying for wrap each string in array but it doesn't works, means foreach loop, please explain why
string s = "keepsakes,table runners,outdoor accessories";
List<string> keys = s.Split(',').ToList();
keys.ForEach(x => x = String.Concat("%", x, "%"));
s = String.Join(",", keys);
Console.WriteLine(s);
need to get "%keepsakes%,%table runners%,%outdoor accessories%"
UPD:
Thanks a lot for suggestions(it's a same way)
but some one can answer why this is works and not works under:
object
public class MyItems
{
public string Item { get; set; }
}
and func
string s = "keepsakes,table runners,outdoor accessories";
List<MyItems> keys = s.Split(',').ToList().Select(x => new MyItems(){ Item = x }).ToList();
keys.ForEach(x => x.Item = String.Concat("%", x.Item, "%"));
s = String.Join(",", keys.Select(x => x.Item).ToList());
Console.WriteLine(s);
You are not modifying the list within the ForEach, you are just creating strings that are assigned to the local variable x but then thrown away. You could use a for-loop:
for(int i = 0; i < keys.Count; i++)
{
keys[i] = String.Concat("%", keys[i], "%");
}
For what it's worth, here the shorter LINQ version which also circumvents the core issue:
s = string.Join(",", s.Split(',').Select(str => "%" + str + "%"));
You can use Join and Select and Format
string s = "keepsakes,table runners,outdoor accessories";
var output = string.Join(",", s.Split(',').Select(x => string.Format("%{0}%", x)));
you can do easier: replace each comma with %,%
string s = "keepsakes,table runners,outdoor accessories";
string s2 = "%" + s.Replace("," , "%,%") + "%";
Another approach could be using Regex instead of LINQ:
string s = "keepsakes,table runners,outdoor accessories";
string pattern = "\\,+";
string replacement = "%,";
Regex rgx = new Regex(pattern);
string result = string.Format("%{0}%", rgx.Replace(s, replacement));
Edit:
The reason why it works using a class to assign the string it is because when you use the foreach in your first instance:
keys.ForEach(x => x = String.Concat("%", x, "%"));
x, elements of keys, which is a string, is a reference passed by value to the function ForEach. Take this as an example:
var myString = "I'm a string";
Console.WriteLine(myString);
ChangeValue(myString);
Console.WriteLine(myString);
void ChangeValue(string s)
{
s = "something else";
}
If you run that snippet you'll see that myString won't be changed inside the method ChangeValue because we are trying to replace the reference. The same thing happens for the method ForEach, this is the main reason you cannot change the value of your list within the ForEach.
Instead if you do:
class MyClass{
public string aString;
}
void ChangeValue(MyClass s)
{
s.aString = "something else";
}
var myClass = new MyClass();
myClass.aString = "I'm a string";
Console.WriteLine(myClass.aString);
ChangeValue(myClass);
Console.WriteLine(myClass.aString);
You acknowledge that in the second Console.WriteLine the value of the field aString will be changed to "something else". Here is a good explanation of how reference types are passed by value
Just another approach (without lambdas):
string result = string.Concat("%", s, "%").Replace(",", "%,%");
List<>.ForEach cannot be used to change the contents of the list. You can either create a new list or use a for loop.
keys = keys.Select(x => "%" + x + "%").ToList();
or
for(int i = 0; i < keys.Count; i++)
{
keys[i] = "%" + keys[i] + "%";
}
As others have noted, the lambda passed to List.ForEach does not return a value.
LINQ is lazy, but String.Join will force enumeration:
var res = String.Join(",", input.Split(',').Select(s => "%" + s + "%"));
The ForEach doesn't change your list of string, it will only perform an action using each string. Instead you can do it this way :
string s = "keepsakes,table runners,outdoor accessories";
List<string> keys = s.Split(',').Select(x => String.Concat("%", x, "%")).ToList();
s = String.Join(",", keys);
Console.WriteLine(s);
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));
I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?
Thanks.
By using regex:
public static string FormatTest1(string num)
{
string formatPattern = #"(\d{2})(\d{4})(\d{4})(\d{4})(\d{4})";
return Regex.Replace(num, formatPattern, "$1-$2-$3-$4-$5");
}
// test
string test = FormatTest1("731478718861993983");
// test result: 73-1478-7188-6199-3983
If you're dealing with a long number, you can use a NumberFormatInfo to format it:
First, define your NumberFormatInfo (you may want additional parameters, these are the basic 3):
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = "-";
format.NumberGroupSizes = new[] { 4 };
format.NumberDecimalDigits = 0;
Next, you can use it on your numbers:
long number = 731478718861993983;
string formatted = number.ToString("n", format);
Console.WriteLine(formatted);
After all, .Net has very good globalization support - you're better served using it!
string s = "731478718861993983"
var newString = (string.Format("{0:##-####-####-####-####}", Convert.ToInt64(s));
LINQ-only one-liner:
var str = "731478718861993983";
var result =
new string(
str.ToCharArray().
Reverse(). // So that it will go over string right-to-left
Select((c, i) => new { #char = c, group = i / 4}). // Keep group number
Reverse(). // Restore original order
GroupBy(t => t.group). // Now do the actual grouping
Aggregate("", (s, grouping) => "-" + new string(
grouping.
Select(gr => gr.#char).
ToArray())).
ToArray()).
Trim('-');
This can handle strings of arbitrary lenghs.
Simple (and naive) extension method :
class Program
{
static void Main(string[] args)
{
Console.WriteLine("731478718861993983".InsertChar("-", 4));
}
}
static class Ext
{
public static string InsertChar(this string str, string c, int i)
{
for (int j = str.Length - i; j >= 0; j -= i)
{
str = str.Insert(j, c);
}
return str;
}
}
If you're dealing strictly with a string, you can make a simple Regex.Replace, to capture each group of 4 digits:
string str = "731478718861993983";
str = Regex.Replace(str, "(?!^).{4}", "-$0" ,RegexOptions.RightToLeft);
Console.WriteLine(str);
Note the use of RegexOptions.RightToLeft, to start capturing from the right (so "12345" will be replaced to 1-2345, and not -12345), and the use of (?!^) to avoid adding a dash in the beginning.
You may want to capture only digits - a possible pattern then may be #"\B\d{4}".
string myString = 731478718861993983;
myString.Insert(2,"-");
myString.Insert(7,"-");
myString.Insert(13,"-");
myString.Insert(18,"-");
My first thought is:
String s = "731478718861993983";
s = s.Insert(3,"-");
s = s.Insert(8,"-");
s = s.Insert(13,"-");
s = s.Insert(18,"-");
(don't remember if index is zero-based, in which case you should use my values -1)
but there is probably some easier way to do this...
If the position of "-" is always the same then you can try
string s = "731478718861993983";
s = s.Insert(2, "-");
s = s.Insert(7, "-");
s = s.Insert(12, "-");
s = s.Insert(17, "-");
Here's how I'd do it; it'll only work if you're storing the numbers as something which isn't a string as they're not able to be used with format strings.
string numbers = "731478718861993983";
string formattedNumbers = String.Format("{0:##-####-####-####-####}", long.Parse(numbers));
Edit: amended code, since you said they were held as a string in your your original question