I have a multi-line TextBox that I can either type or paste items into.At the bottom of the textbox I have an "Item Count = " label and "0" textbox next to it.
I would like the text in the "0" textbox to keep track of the number of items in my textbox list in real time. Is this possible?
This is what I have, but I can't get it to work:
private void textBox2_TextChanged(object sender, EventArgs e)
{
char[] delimiterChars = { ',', ':', '|', '\n' };
List<string> sortBox =
new List<string>(textBox_ListSource.Text.Split(delimiterChars));
var itemCount = sortBox.Count();
textBox_SourceCount.Text = itemCount;
}
I am getting a red squiggly under the "itemCount" in the last line. It won't compile and says can't explicitly convert 'int' to 'string'.
Try
textBox_SourceCount.Text = itemCount.ToString();
Also, you don't need to use the LINQ Count function as a List has a Count property.
var itemCount = sortBox.Count(); // Calls a LINQ function which calls the Count property
var itemCount = sortBox.Count; // Calls the Count property directly
For future reference, C# will not automatically cast an int to a string. You need to perform the conversion explicitly in most cases.
Related
So I am so fresh into the world of programming, starting new, I decided to start messing around in C# to create simple apps from ideas that come to mind, with this little app, I'm trying to have multiple TextBoxes named d1,d2,d3,d4,etc... the user inserts numbers into the textboxes then clicks button1, which begins the process in the code below creating a new list which contains all of the values of the textboxes and then the list is converted to an array and the array is then converted into an int array, etc....
BUT, when starting the application and I add values to the textboxes and then click button1, it shows 2 error like shows in the //gray code line below
Please help.
private void button1_Click(object sender, EventArgs e)
{
List<string> dodo = new List<string>();
dodo.Add(d1.Text); dodo.Add(d2.Text); dodo.Add(d3.Text); dodo.Add(d4.Text); dodo.Add(d5.Text);
dodo.Add(d6.Text); dodo.Add(d7.Text); dodo.Add(d8.Text); dodo.Add(d9.Text); dodo.Add(d10.Text);
dodo.Add(d11.Text); dodo.Add(d12.Text); dodo.Add(d13.Text); dodo.Add(d14.Text); dodo.Add(d15.Text);
dodo.Add(d16.Text); dodo.Add(d17.Text); dodo.Add(d18.Text); dodo.Add(d19.Text); dodo.Add(d20.Text);
foreach(string numb in dodo)
{
if (numb == "")
numb = "0"; //numb word has a red underline
}
string[] terms = dodo.ToArray();
int[] valv = {};
int x = 0;
for(int i=0;i<=19;i++)
{
valv[i] = int.Parse(terms[i]); //the ; in the end has a red underline and shows "FormatException was unhandled" error
i++;
x = x + valv[i];
}
string myString;
myString = x.ToString();
Result1.Text = myString;
}
you can't change the iteration variable which is numb in your case. Please change in the List container instead
List<string> dodo = new List<string>();
dodo.Add(d1.Text); dodo.Add(d2.Text); dodo.Add(d3.Text); dodo.Add(d4.Text); dodo.Add(d5.Text);
dodo.Add(d6.Text); dodo.Add(d7.Text); dodo.Add(d8.Text); dodo.Add(d9.Text); dodo.Add(d10.Text);
dodo.Add(d11.Text); dodo.Add(d12.Text); dodo.Add(d13.Text); dodo.Add(d14.Text); dodo.Add(d15.Text);
dodo.Add(d16.Text); dodo.Add(d17.Text); dodo.Add(d18.Text); dodo.Add(d19.Text); dodo.Add(d20.Text);
int k = 0;
foreach (string numb in dodo)
{
if (numb == "")
{
//numb = "0"; //numb word has a red underline
dodo[k] = "0";
}
k++;
}
Now your code on parsing into integer won't give any runtime error.
The first line "tells" you that you are not able to assign a new value to the variable which is used as a foreach iteration variable.
The second line, "tells" you that you have string value which is not able to be parsed correctly (e.g. user put string which is not a number). To avoid this you can use Int32.TryParse method instead, which will safely try to parse the given string.
The best and easiest way to achieve what you need is using LINQ methods, here is the example based on few things/assumptions:
Since you are converting empty strings into zeros, you could simply skip those entries from counting
To avoid FormatException, you should use TryParse method instead. Since TryParse method will safely parse the given string, you don't even have to filter empty strings at all (they will be skipped). However, I deliberately left filtering part, to get you a better overview of a solution.
You can use list initializer to make list initialization more readable
Solution:
List<string> dodo = new List<string>()
{
d1.Text, d2.Text //...others
};
int sum = dodo
.Where(item => !String.IsNullOrEmpty(item))
.Sum(item =>
{
if (Int32.TryParse(item, out int parsedItem))
{
return parsedItem;
}
return 0;
});
You can get more familiar with LINQ and used methods on following link
I'm trying to build a program with that displays the number of characters and words while a user is typing into the text box. I thought I knew what I was doing but ran into this error:
'Cannot implicitly convert type 'string' to
'Systems.Windows.Forms.Label'
This is what I have so far. The last line of code contains the error:
private void userTextBox_TextChanged(object sender, EventArgs e)
{
string userInput = userTextBox.Text;
char charCount;
charCount = userInput[0];
charCountOutput = charCount.ToString();
}
1) You need to set the property on the Label to set the text
charCountOutput.Text = ...
2) The length of a string can be accessed through the Length property
charCountOutput.Text = userInput.Length.ToString();
charCountOutput.Text = charCount.ToString();
Assuming charCountOutput is the label
Your code is trying to assign the Label object the value of a string, which is a type mismatch (obviously).
You're assigning to a textfield, changing the text of the field.
charCountOutput.Text = charCount.ToString();
int countChar = userTextBox.Text.ToString().Length;
Here's a late addition - you probably already have seen this, but here's a really fast approach. Assumes charCountOutput is label on your form:
private void userTextBox_TextChanged(object sender, EventArgs e)
{
var userInput = userTextBox.Text;
charCountOutput.Text = userInput.Length.ToString();
}
I'am a 2 months c# studient.
I have 3 textBox array defined in a form and I want pass to program.cs
Those names below are declared as public and it works in the form where they are declared but as I call same thing from other forms, I want to put it in program.cs under the public GeneralMethodes
_textBox = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9 };
_textBox1 = new TextBox[] { textBox10, textBox11, textBox12, textBox13, textBox14, textBox15, textBox16, textBox17, textBox18 };
_textBox2 = new TextBox[] { dateTxt, deadLineTxt, qtyprodTxt };
In program.cs I have the code below:
public static void EraseTextBox(Form[] MyBox, Form[] MyBox1)
{
for (int i = 0; i < 9; ++i)
{
MyBox[i].Text = "";
MyBox1[i].Text = "";
}
In my caller form I have this code:
GeneralMethodes.EraseTextBox(_textBox, _textBox1); // This works if the code is in the same form.
I tried with Type[], string[],Array[],Object[],object[] but they don't work and don't accept .Text except Form.
What should I put for defining this array in EraseTextBox(? MyBox, ? MyBox1) ?
public static void EraseTextBox(TextBox[] MyBox, TextBox[] MyBox1)
{
for (int i = 0; i < 9; ++i)
{
MyBox[i].Text = "";
MyBox1[i].Text = "";
}
Probably your error is that you're using Form[] instead of TextBox[] on EraseTextBox
As others have said, EraseTextBox should accept a TextBox[].
Besides just modifying the type of the array parameter, in EraseTextBox you should really be going off of the length of the array instead of a hardcoded upper limit. The EraseTextBox function should be using the length of the array to determine when to stop iterating. With a hard coded upper limit, you can use the code and either not clear all the text boxes, or get an IndexOutOfRangeException.
You should also consider not accepting two arrays. What happens when the length of one array does not match the other, one or the other will not be entirely cleared, or an exception could occur.
public static void EraseTextBoxes(TextBox[] boxes)
{
for (var i = 0; i < boxes.Length; ++i)
boxes[i].Text = "";
}
Then you call it like so:
EraseTextBoxes(_textBox);
EraseTextBoxes(_textBox1);
An array is a collection of objects with a certain type.
You said you want an array of text boxes, so you want to declare an array that can hold many TextBoxes.
For example,
TextBox[] _textBoxes = new TextBox[3];
would create an array that can hold 4 TextBoxes.
In your case, change Form[] MyBox to TextBox[] MyBox.
I have 10 text boxes namely TB1, TB2, TB3, TB4 and so on.. to TB10
I want to store them into a single string value named toBeStored.
Now I m doing the manual way
String toBeStored=null;
tobeStored=TB1.text.toString();
tobeStored+=TB2.text.toString();
and so on..
I want to make a for loop and add them
something like this..
for(int i=1;i<11;i++)
{
toBeStored+=TB+i+.text.ToString()+" ";
}
I know that is wrong.. anything to make it right?
No. Because you defined the text boxes as variables there simply is no enumerator defined.
You could define your own enumerator. In the simpliest case that is as simple as
TextBox boxes [] = new TextBox [] { TB1, TB2, TB3....}
foreach (TextBox box in boxes) {
}
While I think the premise may be flawed, you could do this by
for (int i = 1; i <= 10 ; i++) {
TextBox textbox = (TextBox)Page.FindControls( "TB" + i.ToString);
toBeStored += textbox.Text;
}
Put the controls into an array and then iterate the array.
First of all, you didn't tell us whether you're using winforms, webforms, or what. That would be good.
Second, you probably don't need to use .ToString() on the Text property, which I would assume is already a string.
Finally, if you insist on being lazy, then put the text boxes into an array, and loop over the array:
private TextBox[] _textBoxes = new TextBox[10];
// In init code:
TextBox[0] = TB1;
TextBox[1] = TB2;
// ...
StringBuilder toBeStored = new StringBuilder();
for (int i=0; i<10; i++)
{
toBeStored.Append(TextBox[i].Text);
}
// Now process toBeStored.ToString();
You can use reflection in general if you want to get a field by name.
Type type = GetType();
for (int i = 1; i <= 10; i++)
{
var name = "TB" + i;
var field = type.GetField(name, BindingFlags.Instance | BindingFlags.NonPublic); //or appropriate flags
TextBox tb = (TextBox)field.GetValue(this);
//...
}
If was to do such a thing I would create a helper method to accumulate the text into a string.
public string AccumulateNames(params string[] names)
{
return names.Aggregate(string.Empty, (current, name) => current + name);
}
which would be called similar to this
var toBeStored = AccumulateNames(TB1.Text, TB2.Text, ..., TBn.Text);
How do I check for null in a array list and remove them? It keeps giving me a error of "ArgumentOutOfRange was handled" or if I change the SMTPException to just Exception it says "Index out of range". Looking at the debugger and taking a look specifically at mails.Count it gives me Count = 4. I originally gave it 3 emails to check. The last Array is a "". I believe this is causing the problem.
private void button1_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text == "")
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
}
// textBox1.Text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
// Grabs Emails supplied in textbox1 amd then seperates array using '\n'
ArrayList mails = new ArrayList(textBox1.Text.Split('\n'));
// Note: For thought
// IEnumerable<string> myResults = mails.Split('\n').Where<string>(s => !string.IsNullOrEmpty(s));
for (int i = 0; i < mails.Count; i++)
{
// Seperates user & pass to be passed for authentification.
ArrayList mailInfo = new ArrayList(mails[i].ToString().Split(':'));
textBox3.Text += "[+] Checking email format for" + "\r\n" + "[/] " + mails[i] + "\r\n";
// Attach domain name if not attached.
if (!mailInfo[0].ToString().EndsWith("#gmail.com")) mailInfo[0] = mailInfo[0] + "#gmail.com";
// Debug: Check point
//
// Error message:
// Index was out of range. Must be non-negative and less than the size of the collection. Parameter name index.
// mails.Count = 4 when feeding only 3 emails.
//
// Function: Check mail & Password
// error: index out of range
// MessageBox.Show(mailInfo[0].ToString() + "\n\n" + mailInfo[1].ToString());
if (mails[i] == "") throw new ArgumentOutOfRangeException("No Mail", "No more mail to check.");
if (checkAccount(mailInfo[0].ToString(), mailInfo[1].ToString()))
{
textBox3.Text += "[+] Connection Successful! Checking mail.: mailInfo[0].ToString()\r\n";
}
}
}
What am I doing wrong??? Is the null my problem and if so how do I remove it or am I missing something?
To remove items from a list by checking conditions can be tricky. If you're not using a nifty LINQ statement (since you're using an ArrayList im going to assume LINQ is not availiable to you) you will need to use reverse iteration.
If you iterate over a list like this:
foreach(object o in ArrayList)
{
}
Or
for(int i = 0; i < myArray.Count; i++)
{
}
You will run into issues removing items because you'll run out of items (since the list is now smaller than when you defined your for/foreach).
You need to use reverse iteration or store a list of items to remove later.
Example 1: Reverse Iteration
for(int i = myArray.Count - 1; i >= 0; i--)
{
object o = myArray[i];
if (<some condition here>)
myArray.Remove(i);
}
Example 2: Removal List*
ArrayList toRemove = new ArrayList();
foreach(object o in myArray)
{
if(<some condition here>)
toRemove.Add(o);
}
foreach(object o in toRemove)
myarray.Remove(o);
Example 3: LINQ Approach
var cleanEntities = myArray.Where(x => <some condition on x, which is your item>);
Try populating the array like this:
ArrayList mails = new ArrayList(textBox1.Text.Trim().Split('\n'));
That should remove any trailing white space and remove that last item from getting into the array.
I think the empty entry is caused by a carriage return after the last item in your textbox.
It's generally simpler to iterate over one list while building up another. Hard to go wrong that way.