in wpf, how loop output the data in textbox? - c#

The following code can only display the last number:
for (i=0; i<3; i++)
textbox.text({0},i);
But I want to output numbers in textbox like this;
0
1
2
How can I do with it? thx.

Create a StringBuilder, like this more or less (pseudocode):
StringBuilder sb = new StringBuilder();
for (i=0; i<3; i++)
sb.AppendLine(string.Format({0},i));
textbox.Text = sb.ToString();
Just note: if you are using WPF avoid direct access to the control properties and operate on ViewModel instead, if not, you loose notable part of the benefits brought to you with that technology.

Linq way
var result=Enumerable.Range(0,3).Select(i=>i.ToString()).Aggregate((init, next)=> init+ Environment.NewLine+next);
textBox.Text = result;

Related

2D Array Input in same line

How I take 2D array input in same line. in C# Console.ReadLine() allow us to take input one at a time .I want to take input as a row
int [,] arr = new int[m,n];
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
arr[i, j] = int.Parse(Console.ReadLine());
}
}
I want to take input this way
2 2,
10 20,
30 40
Entering a two-dimensional array on the command line is going to be error prone and frustrating for users. But if you MUST do it:
Figure out what symbols will separate values. (Commas, spaces?)
Figure out what symbols will separate array dimensions. (Pipes, perhaps? Whatever you choose, make sure it isn't the same symbol you use for separating values.)
Prompt the user for data and capture it into a string.
Validate the data.
Write a parser that parses your data into a multi-dimensional array.
I'd advise against trying to do this. But I don't dictate your requirements.
var delimiter = ' ';
for(var i = 0; i<n; i++) {
var row = Console.ReadLine();
var _arr = row.Trim().Split(delimiter);
for(var j=0; j<m; j++) {
arr[j, i] = int.Parse(_arr[j].Trim());
}
}
Update:
#mike-hofer, wholeheartedly agree with the "error prone and frustrating for users" characteristics of such way of input. I assume this is rather for a quick and dirty testing. Plus, exactly the same approach will be applied if you have to read the array from a file line by line, so there is some broader value in this question.
#rahi-ratul75, the code above does not do any error checking. The most likely error will be an entry which won't parse as an integer. You may want, therefore, to use int.TryParse(,) and, when false, ask to re-enter the line. The main logic, however, is there:
read the line
split it into an array
parse the entry into an integer

how to copy received data from string into 1d char array c# forms

So im just learning C# and trying to use arrays, im getting input from user via a forms app and wish to copy it to an array called prevPos, in the format below
receiving data (string):
string1: "hello"
string2: "123"
//counting how many lines and using that to determine position associated with each
recieved
char[] prevPos;
prevPos = textBox_ReceievedData.Text.ToCharArray();
//count how many lines of receieved data in textbox
for (int i = 0; i < textBox_ReceievedData.Lines.Length; i++)
{
System.Console.WriteLine("charArray " +prevPos[i]);
}
right now if i wish to call it, i would get this, i do not want this fomat:
prevPos[1]=h
prevPos[2]=e
prevPos[3]=l
etc.
I want this output:
prevPos[1]=hello
prevPos[2]=123
please replace with the below and try
for (int i = 0; i < textBox_ReceievedData.Lines.Length; i++)
{
System.Console.WriteLine("Each Line " +textBox_ReceievedData.Lines[i]);
}
prevPos = textBox_ReceievedData.Text.Split('\n');
This will give you an array of all text separated by the new line character \n.
If that is the output you desire, then a string array (not a char array) is what you want. The Lines() property already gives you that, though:
string[] prevPos = textBox_ReceievedData.Lines;
for(int i=0; i< prevPos.Length; i++)
{
System.Console.WriteLine(prevPos[i]);
}

Incremental counting and saving all values in one string

I'm having trouble thinking of a logical way to achieve this. I have a method which sends a web request with a for loop that is counting up from 1 to x, the request counts up until it finds a specific response and then sends the URL + number to another method.
After this, saying we got the number 5, I need to create a string which displays as "1,2,3,4,5" but cannot seem to find a way to create the entire string, everything I try is simply replacing the string and only keeping the last number.
string unionMod = string.Empty;
for (int i = 1; i <= count; i++)
{
unionMod =+ count + ",";
}
I assumed I'd be able to simply add each value onto the end of the string but the output is just "5," with it being the last number. I have looked around but I can't seem to even think of what I would search in order to get the answer, I have a hard-coded solution but ideally, I'd like to not have a 30+ string with each possible value and just have it created when needed.
Any pointers?
P.S: Any coding examples are appreciated but I've probably just forgotten something obvious so any directions you can give are much appreciated, I should sleep but I'm on one of those all-night coding grinds.
Thank you!
First of all your problem is the +=. You should avoid concatenating strings because it allocates a new string. Instead you should use a StringBuilder.
Your Example: https://dotnetfiddle.net/Widget/qQIqWx
My Example: https://dotnetfiddle.net/Widget/sx7cxq
public static void Main()
{
var counter = 5;
var sb = new StringBuilder();
for(var i = 1; i <= counter; ++i) {
sb.Append(i);
if (i != counter) {
sb.Append(",");
}
}
Console.WriteLine(sb);
}
As it's been pointed out, you should use += instead of =+. The latter means "take count and append a comma to it", which is the incorrect result you experienced.
You could also simplify your code like this:
int count = 10;
string unionMod = String.Join(",", Enumerable.Range(1, count));
Enumerable.Range generates a sequence of integers between its two parameters and String.Join joins them up with the given separator character.

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

Print all combinations from 0000 to 9999 in C#

just wondering if anyone had an algorithm lying around that printed all possible combos from 0000 to 9999 (trying to crack code into old phone and new to learning C#)...Million thanks. Bela
Why complicate matters?
for (Int32 index = 0; index < 10000; index++)
Console.Out.WriteLine(index.ToString("0000"));
Since you're commenting that you're outputting to a label, with linefeeds between each value, here's a better way:
List<String> values = new List<String>();
for (Int32 index = 0; index < 10000; index++)
values.Add(index.ToString("0000"));
label1.Text = String.Join(
Environment.NewLine,
values.ToArray());
Try that and see if it gives you what you want.
WTF entry:
Console.WriteLine("0000");
Console.WriteLine("0001");
Console.WriteLine("0002");
Console.WriteLine("0003");
// snip everything in the middle
Console.WriteLine("9998");
Console.WriteLine("9999");
For those of you who are lacking of humor, don't try this at home.
Do you want to count to 9999?
I think Digitalex's solution is the most elegant but too memory-consuming.
Here's a better option:
foreach (var number in Enumerable.Range(0, 10000).Select(i => i.ToString("0000")))
Console.WriteLine(number);
for (int index = 0; index < 10000; index++)
{
Console.WriteLine(index);
}
Like Lasse said, simply print them in sequence. But you can do even simpler with Linq;
Enumerable.Range(0, 9999).ToList().ForEach(Console.WriteLine);
You could avoid the "ToList" as well, if you had a helper function (which I normally would have in a Utilities class);
public static void ForEach<T>(this IEnumerable<T> elements, Action<T> action)
{
foreach (var element in elements) { action(element); }
}
Note that this utility method is not strictly required for it to work, but would greatly diminish the memory requirements (since ToList actcually creates a list of all the numbers in memory).

Categories

Resources