Seperate a label into 2 different Textbox C# - c#

I wanted to know how i could split this label into 2 different textboxes. Before writing here i searched google and came this far, but now both of my textboxes is showing the value 1000. The program is supposed to split the numbers between the x.
Example: Left textbox = 80 & Right textbox = 1000. What am I missing?
private void Split_btn_Click(object sender, EventArgs e)
{
string s = label1.Text;
// Split string on spaces.
// ... This will separate all the words.
string[] words = s.Split('x');
foreach (string word in words)
{
Left_txtbox.Text = word;
Right_Textbox.Text = word;
}
}

The problem is the loop. You are setting both textboxes with the same value and overwriting it with every iteration so the last values wins.
You could simply assign the values like follows:
Left_txtbox.Text = words[0];
Right_Textbox.Text = words[1];

I would add the trim() command in as well because you will end up with a space after the 80 and before the 1000.
private void button1_Click(object sender, EventArgs e)
{
string s = label1.Text;
string[] words = s.Split('x');
Left_txtbox.Text = words[0].Trim();
Right_Textbox.Text = words[1].Trim();
}
or add the split directly into the textbox assign
private void button1_Click(object sender, EventArgs e)
{
string s = label1.Text;
Left_txtbox.Text = s.Split('x')[0].Trim();
Right_Textbox.Text = s.Split('x')[1].Trim();
}

Try this instead of your foreach loop:
if (words.Length > 1)
{
Left_txtbox.Text = words[0];
Right_Textbox.Text = words[1];
}

Related

Need to sort words in an array using a separate method

Question:
Write a program named SortWords that includes a method that accepts any number of words and sorts them in alphabetical order. Demonstrate that the program works correctly when the method is called with one, two, five, or ten words.
What I have thus far:
private void button1_Click(object sender, EventArgs e)
{
String[] outWords = new string[20];
outWords[0] = textbox1.Text;
outWords[1] = textBox2.Text;
outWords[2] = textBox3.Text;
outWords[3] = textBox4.Text;
outWords[4] = textBox5.Text;
outWords[5] = textBox6.Text;
outWords[6] = textBox7.Text;
outWords[7] = textBox8.Text;
outWords[8] = textBox9.Text;
outWords[9] = textBox10.Text;
sortAndPrint(outWords[11]);
}
private void sortAndPrint(params string[] newWords)
{
Array.Sort(newWords);
label1.Text = newWords[0];
label2.Text = newWords[1];
label3.Text = newWords[2];
label4.Text = newWords[3];
label5.Text = newWords[4];
label6.Text = newWords[5];
label7.Text = newWords[6];
label8.Text = newWords[7];
label9.Text = newWords[8];
label10.Text = newWords[9];
}
My issues here is that I either don't get anything in my label boxes or I get errors thrown from can't convert a string into string[] or System.IndexOutOfRangeException. I'm sure im doing something completely wrong here.
Try this :
private void button1_Click(object sender, EventArgs e)
{
string[] outWords = new string[10];
outWords[0] = textbox1.Text;
outWords[1] = textBox2.Text;
outWords[2] = textBox3.Text;
outWords[3] = textBox4.Text;
outWords[4] = textBox5.Text;
outWords[5] = textBox6.Text;
outWords[6] = textBox7.Text;
outWords[7] = textBox8.Text;
outWords[8] = textBox9.Text;
outWords[9] = textBox10.Text;
sortAndPrint(outWords);
}
private void sortAndPrint(string[] newWords)
{
Array.Sort(newWords);
label1.Text = newWords[0];
label2.Text = newWords[1];
label3.Text = newWords[2];
label4.Text = newWords[3];
label5.Text = newWords[4];
label6.Text = newWords[5];
label7.Text = newWords[6];
label8.Text = newWords[7];
label9.Text = newWords[8];
label10.Text = newWords[9];
}
Summary
Pass whole array sortAndPrint(outWords); not single element.
Take array length only what you need. string[] outWords = new string[10];
Please check this question for the use of params. You need to pass values when you user param but if you need to pass variable, you have to remove params.
Example of params
private void button1_Click(object sender, EventArgs e)
{
sortAndPrint("one","two","three","four","five");
}
private void sortAndPrint(params string[] newWords)
{
Array.Sort(newWords);
label1.Text = newWords[0];
label2.Text = newWords[1];
label3.Text = newWords[2];
label4.Text = newWords[3];
label5.Text = newWords[4];
}
sortAndPrint(outWords[11]);
will pass a single string (as an array) to sortAndPrint, so when you call
label2.Text = newWords[1];
you get an out of bounds exception. Try just
sortAndPrint(outWords);
to pass the entire array. Also note that empty slots in the array wil get sorted before other strings, so you need to come up with a way to get rid of the blank/null string.
Or, if the intent is to demonstrate how to use params, you could do something like:
sortAndPrint(textbox1.Text,
textbox2.Text,
textbox3.Text,
textbox4.Text,
textbox5.Text);
But you need to check the bounds of the array in sortAndPrint, rather than just assuming the array has a size of at least 10.
If you read the instructions carefully, you have this requirement:
...includes a method that accepts any number of words...
You accomplish this by using the params keyword along with a string[].
...and sorts them in alphabetical order.
This part you doing with Array.Sort(newWords);
Demonstrate that the program works correctly when the method is called with one, two, five, or ten words
This part you're not doing - you're assuming in your code that the input array will have 10 items, when instead you should check to see how many items it has before outputting the results.
Since the array size cannot be determined by the method, then it cannot make any assumption that there will be enough labels on the form to populate with the results. Given this, we could use a MessageBox to show the results instead, and we can use String.Join to join all the items in the array with an Environment.NewLine character in order to show the sorted words in different lines:
private void SortAndPrint(params string[] newWords)
{
Array.Sort(newWords);
MessageBox.Show(string.Join(Environment.NewLine, newWords));
}
Now, we can demonstrate the use of this function by passing in different numbers of arguments to it.
First, just so we're on the same page, I have this code in the Form_Load method that adds 10 textboxes to the form, all with the tag "input":
private void Form1_Load(object sender, EventArgs e)
{
var stdHeight = 20;
var stdWidth = 100;
var stdPad = 10;
var count = 10;
for (int i = 0; i < count; i++)
{
var textBox = new TextBox
{
Name = "textBox" + (i + 1),
Left = stdPad,
Width = stdWidth,
Height = stdHeight,
Top = (stdHeight + stdPad) * i + stdPad,
Tag = "input"
};
Controls.Add(textBox);
}
}
Now, in our button click event, we can search for all controls on the form who have the Tag == "input" and whose .Text property is not empty, and we can pass these Text values to our method both as a single array OR as individual items:
private void button1_Click(object sender, EventArgs e)
{
// Select all textbox Text fields that have some value
var words = Controls.Cast<Control>()
.Where(t => t.Tag == "input" && !string.IsNullOrWhiteSpace(t.Text))
.Select(t => t.Text)
.ToArray();
// Pass all the words in a single array to our method
SortAndPrint(words);
// We can also demonstrate this by passing individual words
// Pass one word if we can
if (words.Length > 0)
{
SortAndPrint(words[0]);
}
// Pass two words if we can
if (words.Length > 1)
{
SortAndPrint(words[0], words[1]);
}
// Pass five words if we can
if (words.Length > 4)
{
SortAndPrint(words[0], words[1], words[2], words[3], words[4]);
}
// Pass ten words if we can
if (words.Length > 9)
{
SortAndPrint(words[0], words[1], words[2], words[3], words[4],
words[5], words[6], words[7], words[8], words[9]);
}
}

Trim textbox text after 20 characters used and spaces if contains spaces

I have a WinFormApp with 2 txtboxes (LongName and ShortName) with a Button.
When txt is entered in the LongName txtbox, I want to press the button to shorten all txt inside LongName txtbox to the first 20 characters imput and to remove any spaces within' the txtbox then display the results in the ShortName txtbox. I'm having a real hard time trying to get this correct. I've tried a number of ways to try but ultimately can't seem to get it right. Here is example code:
private void btnGetSN_Click(object sender, EventArgs e)
{
Regex space = new Regex(#" ");
MatchCollection spacematch = space.Matches(txtLongName.Text);
if (txtLongName.Text.Length > 20)
{
string toTrim = txtLongName.Text;
toTrim = toTrim.Trim();
txtShortName.Text = ("'" + toTrim.ToString() + "'");
}
if (spacematch.Count > 0)
{
txtLongName.Text.Replace(" ", "");
}
}//closes method
I've been able to limit the txtbox to only 20 characters in the properties but I would like to setup a If variable to allow more customization.
Am I on the right track?
No errors in the code but when executing the button, nothing happens. Any help is appreciated.
string.Replace() doesn't update the string itself, but rather returns a new string that is modified.
private void btnGetSN_Click(object sender, EventArgs e)
{
// remove space from txtLongName
txtLongName.Text = txtLongName.Text.Replace(" ", string.Empty);
// take only the first 20characters from txtLongName
txtShortName.Text = txtLongName.Text.Substring(0, Math.Min(txtLongName.Text.Length, 20));
}
EDIT: Previous code will remove space from txtLongName. If that is not intended, use this instead :
private void btnGetSN_Click(object sender, EventArgs e)
{
// remove space from txtLongName
var name = txtLongName.Text.Replace(" ", string.Empty);
// take only the first 20characters from txtLongName
txtShortName.Text = name.Substring(0, Math.Min(name.Length, 20));
}
Looks like you need to write differently
private void button1_Click(object sender, EventArgs e)
{
var shortName = txtLongName.Text.Trim().Replace(" ", "");
var maxLength = (shortName.Length > 20) ? 20 : shortName.Length;
if(txtLongName.Text.Trim().Length > 0)
txtShortName.Text = shortName.Substring(0, maxLength);
}

How can i parse text from textBox and add each part of the text to a string variable?

private void textBox1_TextChanged(object sender, EventArgs e)
{
}
For example i type in the textNox: החטוף נמצא בתאריך: 25.6.2014 בשעה: 13:01
Then:
string t = בשעה: 13:01
string f = בתאריך: 25.6.2014
string g = החטוף נמצא
This is a working code i did now the result/s is just what i needed:
private void textBox1_TextChanged(object sender, EventArgs e)
{
List<string> allwords = new List<string>();
string firstPart = "";
string secondPart = "";
string thirdPart = "";
int t = 0;
textBox1.ForeColor = Color.Green;
if (textBox1.Text.Contains("בתאריך"))
{
t = textBox1.Text.IndexOf("בתאריך");
firstPart = textBox1.Text.Substring(0, t);
allwords.Add(firstPart);
}
if (textBox1.Text.Contains("שעה"))
{
int x = textBox1.Text.IndexOf("שעה");
secondPart = textBox1.Text.Substring(t, x-t);
thirdPart = textBox1.Text.Substring(x);
allwords.Add("דווח במקור " + secondPart + thirdPart);
}
}
To make more variables as you described, you can use a List. It's dynamic, so you can add or remove items from it. Each item can be accessed with proper indexes, starting from 0. I think you should create an "Add"-Button next to the TextBox, which creates a new string variable of the typed text to the list.
Make a new list:
List<string> texts = new List<string>();
Then make the button and add new Click-method for it:
public void myButton_Click(object sender, EventArgs e)
{
// Add the text to the list
texts.Add(yourTextBox.Text);
// Then clear the TextBox for next input
yourTextBox.Text = "";
}
Ten you can loop through the list, accesing all the texts that were added:
foreach (string text in texts)
{
// Do something with the text...
}

How to remove blank lines from a C# List<string>?

I am trying to create a routine in C# that sorts a list added to a Multi-Line text box. Once that is done, there is an option to remove all blank lines. Can someone tell me how I would go about doing this? here is what I have so far, but it doesn't work at all when I select the box and click sort:
private void button1_Click(object sender, EventArgs e)
{
char[] delimiterChars = { ',',' ',':','|','\n' };
List<string> sortBox1 = new List<string>(textBox2.Text.Split(delimiterChars));
if (checkBox3.Checked) //REMOVE BLANK LINES FROM LIST
{
sortBox1.RemoveAll(item => item == "\r\n");
}
textBox3.Text = string.Join("\r\n", sortBox1);
}
If you're splitting the string on '\n', sortBox1 won't contain a string containing \n. I would just use String.IsNullOrWhiteSpace, though:
sortBox1.RemoveAll(string.IsNullOrWhiteSpace);
You forgot to sort the lines:
sortBox1.Sort();
A blank line is not "\r\n", that is a line break. Blank lines are empty strings:
sortBox1.RemoveAll(item => item.Length == 0);
You can also remove the blank lines when splitting the string:
private void button1_Click(object sender, EventArgs e) {
char[] delimiterChars = { ',',' ',':','|','\n' };
StringSplitOptions options;
if (checkBox3.Checked) {
options = StringSplitOptions.RemoveEmptyEntries;
} else {
options = StringSplitOptions.None;
}
List<string> sortBox1 = new List<string>(textBox2.Text.Split(delimiterChars, options));
sortBox1.Sort();
textBox3.Text = string.Join("\r\n", sortBox1);
}

c# splitting an array and displaying it in descending order in a textbox

I wish to display an array of text in a textbox, after splitting it with a comma, i pass a bunch of numbers into textbox1 and split it with the commas, how do i sort the number in descending order. here is the method i got so far
private void btnCalc_Click(object sender, EventArgs e)
{
//string A = txtInput.Text;
string[] arrText = txtInput.Text.Split(',');
int[] newOne = new int[]{};
foreach (string r in arrText)
{
}
txtOutput.AppendText( );
}
int[] newOne = arrText.Select(x => int.Parse(x)).OrderByDescending(x => x).ToArray();
You should be able to do it like this:
private void btnCalc_Click(object sender, EventArgs e)
{
//string A = txtInput.Text;
string[] arrText = txtInput.Text.Split(',');
txtOutput.Text = string.Join(",",arrText.Select( s => int.Parse(s)).OrderByDescending( i => i))
}
Note that this will blow up if some of the input text between the commas is not a number.
this should work:
var newOne = arrText.OrderByDescending(int.Parse).ToArray();
foreach (var s in newOne)
{
txtOutput.AppendText(s);
}

Categories