Displaying a character count while the user is typing? - c#

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();
}

Related

The field 'Form1.answer' is never used

I am getting a random word from a dictionary using:
var word = File.ReadAllLines(#"c:\\CTEMP\\Dictionary2.txt");
and displaying it only partially for the player to guess using:
hintTextBox.Text = GetPartialWord(word[new Random().Next(word.Length)]);
var answer = word[new Random().Next(word.Length)]; // answer = word from dictionary
However I am not able to compare the word the user enters to the word from the dictionary.
I have tried :
private string answer; //assign answer to word from dictionary
private void button2_Click(object sender, EventArgs e)
{
if (answerTextBox.Text == answer)
{MessageBox.Show("You Guessed The Word !");
However I am getting the following warning:
Warning CS0169 The field 'Form1.answer' is never used WindowsFormsApplication2
Any ideas on how I can compare the answer to what is entered in answerTextBox?
The problem is in this line:
var answer = word[new Random().Next(word.Length)];
Here you create new variable instead of using class level one. In if statement you compare value of textbox with class level variable. Also, you get warning because you never assign value to class level variable but compare value of textbox.
That line should be changed to:
this.answer = word[new Random().Next(word.Length)]; //or without "this."

Input string was not in a correct format - Slot Mchine App

I get the error: 'Input string was not in a correct format'..... I am running an if else calculation and then populating a label with the result the variable is declared as decimal then ToString('C') to the label...
List<string> moneyWon = new List<string>();
private void calculateAmountWon()
{
moneyWon.Add(amountWonlabel.Text);
decimal won = moneyWon.Sum(str => Convert.ToInt32(str));
moneyWonLabel.Text = won.ToString("C");
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
The only thing that will throw that error is the Convert.ToInt32(str) call. One of the items in the moneyWon list is not a valid int value.
You should probably also declare moneyWon as a List<int> and store all the values as int's instead of string's. It doesn't make sense to store everything as a string and then convert it to int when you need it.
Based on what you're outputting I'm assuming that your strings are formatted as currency with a currency symbol and two decimal places. If that's the case you can change your parsing to:
decimal won = moneyWon.Sum(str => decimal.Parse(str, NumberStyles.Currency));
You're still vulnerable to invalid formats but if the values are all set programatically then they should be predictable.
Another option is to use a list of numeric types and parse up front:
List<decimal> moneyWon = new List<decimal>();
private void calculateAmountWon()
{
moneyWon.Add(decimal.Parse(amountWonlabel.Text, NumberStyles.Currency));
decimal won = moneyWon.Sum();
moneyWonLabel.Text = won.ToString("C");
}

How to add the numbers stored in Label.Text

I basically want to total the amount.
The amount gets stored in a label. I want to add labels. Basically I want to do an addition of labels but i can't because label is .Text which is String so when i add it I get a string of added label while i want the Numbers stored in the labels to get added. this is my code below.
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
temp4 = Int32.Parse(DropDownList3.Text);
temp5 = temp4 * 76;
Label7.Text = temp5.ToString();
}
On the click of a button the amount in Lablel7 should get added with another Label.
protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
{
Label16.Text = Label7.Text+Label6.Text;
}
So that the total amount can be found.
Am kinda new to programming and all itself and this is part of my project am sorry if this questions seems stupid
Label16.Text = (int.parse(Label7.Text)+int.parse(Label6.Text)).toString();
Use above code.
Convert your addition to string datatype.
Parse both label's Text property to integer and then do the addition.
Label16.Text = (int.Parse(Label7.Text) + int.Parse(Label6.Text)).ToString();
Its better if you can use int.TryParse which would save you from the exception if the text is not a number.
int number1;
int number2;
if(!int.TryParse(Label7.Text, out number1))
{
// invalid number in Label7
}
if(!int.TryParse(Label6.Text, out number2))
{
// invalid number in Label6
}
Label16.Text = (number1 + number2).ToString();
Label7.Text is type of string, you can add int, so you have to convert it. Afterr all you have convert back int to string
Label16.Text = (int.Parse(Label7.Text)+int.Parse(Label6.Text)).ToString();
Try to rename your controls and var. For example lblAmount tell you maore than Label6. Please read about Camel, Pascal convertion, It will help you in the future.
Two solutions :
1- You can parse each Text to convert into Int32, that you can add and then convert in text with ToString()
protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
{
Label16.Text = (Int32.Parse(Label17.Text) + Int32.Parse(Label6.Text)).ToString();
}
2- On each chanching, you can save values in private properties of type Int32, and work with them.

C# - Display Multi-line TextBox count in real-time

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.

C# Split() in ListBox

listBox2 contents:
0:FirstProduct
1:ProductAgain
2:AnotherProduct
3:OkFinalProduct
What I'm trying to do, when the selected index has changed on listBox2, is to have it make my int "DBID" the value of the number before the ":".
Here's my attempt:
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox2.SelectedIndex == -1)
{
return;
}
int DBID;
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(":"[0]));
ShowProduct(DBID);
}
ANY help with this is greatly appreciated :)
Thanks guys
EDIT -
Sorry, yes I actually tried:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
but im getting the following errors:
The best overloaded method match for string.Split(params char[])' has some invalid arguments
Argument1: cannot convert from 'string' to 'char[]
EDIT #2 -
When using:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
After running the application and clicking on a different listbox item, I'm encountering this exception:
NullReferenceException was unhandled. Object reference not set to an instance of an object.
I appreciate all the help so far guys!
Try changing:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(":"[0]));
To:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
Update
Try this instead. It explicitly adds a new char:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(new char[] { ':' })[0]);
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
A safer way will be to replace the single statement with the following code,
if (listBox3.SelectedValue != null)
{
string selectedValue = listBox3.SelectedValue.ToString();
if (!string.IsNullOrEmpty(selectedValue))
{
if (Int32.TryParse(selectedValue.Split(':')[0], NumberStyles.Integer, CultureInfo.CurrentCulture, out DBID))
{
// Process DBID
}
else
{
// Cannot convert to Int32
}
}
}
Then use breakpoints in the code, to find where the NullReferenceException is occurring.
Note that this example assumes that you are using System.Windows.Controls.ListBox or System.Windows.Forms.ListBox, and not System.Web.UI.WebControls.ListBox. In the later case, the SelectedValue is a string and not an object (as pointed out by #Srinivas Reddy Thatiparthy in another answer's comment)

Categories

Resources