Below is some of my code that isn't working. I wanted to see it could count the number of spaces in the text box so I'm having it display the number in a message box and it currently just throws a blank one. The problem is either in the float to string conversion or in the counter.
private static string _globalVar = "n";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
public Form1()
{
InitializeComponent();
button1.Text = "Enter";
}
string LNum { get; set; }
public void button1_Click_1(object sender, EventArgs e)
{
MessageBox.Show(LNum);
}
public void richTextBox1_TextChanged(object sender, System.Windows.Forms.KeyEventArgs e)
{
float n = 0;
if (Control.ModifierKeys == Keys.Space)
{
n = n + 1; ;
}
string.Format("{0:N1}", n);
string LNum = Convert.ToString(n);
}
What you are doing is an excellent way to learn how and when the events are raised and how they can be leveraged to customize an applications behavior and is something similar to what many of us have done over the years.
Based on what you say you are wanting to do, there are several issues. If you take a look at this code, it will do what you want.
public void button1_Click(object sender, EventArgs e)
{
int n = 0;
for (int counter = 0; counter < richTextBox1.TextLength; counter++)
{
if (richTextBox1.Text[counter] == ' ')
{
n++;
}
}
MessageBox.Show(n.ToString("N1"));
}
The key difference is that I am only looking at the entered text when the button is clicked. (TextChanged is run every time there is a change in the text displayed). I chose not to use a float variable to store the count of spaces as the count will always be an integer.
In addition, the parameter to TextChanged System.Windows.Forms.KeyEventArgs e is incorrect and will never compile if correctly bound to the TextChanged event.
The KeyEventArgs parameter is used by the KeyUp and KeyDown events. If you use these events, you will be looking to count every time the space bar is pressed and not the number of spaces in the text box. And like their name suggests, the events are raised every time a Key on the keyboard goes Up (Pressed) and Down (Released).
Related
I have a GUI that is using a text field for a user int input.
a combo box that has drop downs for calculations (sum, add, div, mult. etc.)
then I click a button to calculate.
the Results show in bottom text field.
I am having trouble getting the combobox to string, so that I can make the right calculation.
The first part also needs the combobox to be selected on "Initialize" to add the value to the result text field. After that is added, all combobox choices after will utilize the initialized value in the results field and the user input field for any function calls.
namespace GUI
{
public partial class Form1 : Form
{
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string path = #"C:\Users\calculations.txt";
StreamReader sr = new StreamReader(path);
string x = sr.ReadToEnd();
string[] y = x.Split('\n');
for (int i = 0; i < y.Length; i++)
{
comboBox1.Items.Add(y[i]);
}
}
//Button to calculate Resualt
private void button1_Click(object sender, EventArgs e)
{
string x = comboBox1.SelectedItem.ToString();
int b = int.Parse(textBox2.Text);
if(x == "Initialize")
textBox1.Text = (b).ToString();
else if (textBox1 == null)
Console.WriteLine("Please Initialize value");
if(x == "Sum")
textBox1.Text = (b + b).ToString();
}
//Result text box
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
//User number input box
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
Values in calculation.txt
Initialize
Sum
Subtract
Product
Power
Log
I have a textbox, a button, and a progressbar. I would like the keydown event of the textbox therefore the entry, is found using a button in the progressbar, in fact I would like the number entered in the textbox to become the value of the progressbar and that in this case the progressbar value increases. If you could put me a sample code, that would be nice, thank you.
public void button1_Click(object
sender,EventArgs e)
{
//I don't know.
}
public void textbox2_KeyDown(object
sender,KeyEventArgs e)
{
if(e.KeyCode <= Keys.NumPad0 ||
e.KeyCode >= Keys.NumPad9)
{
// I don't know !
}
As I understood, you want to change the progress bar value based on the textBox input and detect that change.
Well, to get the input from the textBox on change, there is an event for that which called:
TextChanged
so with every change in the input, you'll be able to capture the input.
For the progressbar, you can change the value by the property: Value.
Read more:
ProgressBar.Value
so if your progressBar control named: progressBar1, change it by:
progressBar1.Value = 5; // here the value is 5.
Now, you can use textChanged event to set the progress bar value like:
public void textbox2_TextChanged(object sender,KeyEventArgs e)
{
progressBar1.Value = int.Parse(textBox2.Text); // parse the input to int value. Consider using int.TryParse
}
On KeyDown capture the keyValue
int keyValue { get; set; }
private void textbox2_KeyDown(object sender, KeyEventArgs e)
{
int keyVal = (int)e.KeyValue; keyValue = -1;
if ((keyVal >= (int)Keys.D0 && keyVal <= (int)Keys.D9))
{
keyValue = (int)e.KeyValue - (int)Keys.D0;
}
else if (keyVal >= (int)Keys.NumPad0 && keyVal <= (int)Keys.NumPad9)
{
keyValue = (int)e.KeyValue - (int)Keys.NumPad0;
}
}
On Button Click Increase the ProgessBar value
public void button1_Click(object sender,EventArgs e)
{
//Here Increment the progress bar by keyValue
progressBar1.Value += keyValue;
}
KeyValues and KeyCodes
I have this project with a method like so.
private void LoopThis()
{
MessageBox.Show("Hello World!");
}
And I have this button that invokes the method, and a textbox where I enter a int let's say i enter 10.
Ten I want that method to execute 10 times.
What kind of loop do I use to do this?
private void Button_Click(object sender, RoutedEventArgs e)
{
int times;
if (Int32.TryParse(TextBox.Text, out times))
{
// It could parse the input text (so we deduce it was an integer)
// and not a string.
for (int i = 0; i < times; i++)
{
LoopThis();
}
}
else
{
// Throw exception or show a message to the user
}
}
I'm new to C#. Using the code below, whenever I press a number key on my keyboard, it will display twice in the textbox. When I press "1" on the keyboard it will display
"11", and when I press "2" it will display "22". Why is this?
private void Window_TextInput(object sender, TextCompositionEventArgs e)
{
if(!isNumeric(e.Text))
{
string display = string.Empty;
display += e.Text;
displayNum(display);
}
else
{
String inputOperator = string.Empty;
inputOperator += e.Text;
if (inputOperator.Equals("+"))
{
ApplySign(sign.addition, "+");
}
}
}
private bool isNumeric(string str)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
return reg.IsMatch(str);
}
private void window_keyUp(object sender, KeyEventArgs e)
{
if (e.Key >= Key.D0 && e.Key <= Key.D9)
{
int num = e.Key - Key.D0;
outputText2.Text += num;
}
}
private void BtnNum_Click(object sender, RoutedEventArgs e)
{
Button num = ((Button)sender);
displayNum(num.Content.ToString());
}
private void displayNum(String n)
{
if (operator1 == 0 && double.Parse(n) == 0)
{
}
else
{
if (operator1 == 0)
{
outputText2.Clear();
}
outputText2.Text += n;
operator1 = double.Parse(outputText2.Text);
outputText2.Text = Convert.ToString(operator1);
}
}
You have two events that are handeling the Keyboard events. Although not really sure what the displayNum() method is doing
I am assuming the Window_TextInput event is the event you wish to primarily handle the event.
Try adding
e.Handled = true;
In the Window_TextInput method. If that doesn't solve the problem can you post the displayNum() method?
EDIT:
After further review of the code and trying the same I do not see the relevance for the window_keyUp method as your Window_TextInput handles the input characters and has more applicable logic for handling the TextInput changes.
After I removed the window_keyUp event method the output appeared as expected (although commented out the ApplySign() method.
You've subscribed to two window-level text-related events - TextInput and KeyUp - and both of them end up appending input to the TextBox.
window_keyUp appends numbers to the TextBox
It looks like Window_TextInput is supposed to append non-numeric characters, but your RegEx is incorrect ([^0-9] matches anything that is not numeric, so IsNumeric returns True if the input is not a number)
The effect is that every numeric key press shows up twice.
I have Form1, RichTextBox1 and Button1 on my Form
To understand what i'm trying to do; take a look at this link, type in a facebook profile link and click on Hack Account AND SEE THE GREEN TEXT THAT APPEARS
I'm using the code below in C# to achieve what i want to do :
private void button1_Click(object sender, EventArgs e)
{
string myStr = "This is a test string to stylize your RichTextBox1";
foreach (char c in myStr.ToCharArray()) {
Thread.Sleep(100);
richTextBox1.AppendText(c.ToString());
}
}
But it doesn't work, the text appears in the text box at one time; Not char by char!
The reason your code is showing all the text at once is using Thread.Sleep() keep the main Thread (the UI thread) suspended / sleep mode, so none of the Application message are processed on form & the form paint / drawing event are not doing the job as the UI thread is sleeping/suspended!
Solution 1: Use a helper Thread so that Thread.Sleep() dont make ur app go in non-responsive mode
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string myStr = "This is a test string to stylize your RichTextBox1";
ThreadPool.QueueUserWorkItem(ShowTextInInterval, myStr);
}
private void ShowTextInInterval(object state)
{
string mystr = state as string;
if (mystr == null)
{
return;
}
for (int i = 0; i < mystr.Length; i++)
{
AppendNewTextToRichTextBox(mystr[i]);
Thread.Sleep(100);
}
}
private delegate void app_char(char c);
private void AppendNewTextToRichTextBox(char c)
{
if (InvokeRequired)
{
Invoke(new app_char(AppendNewTextToRichTextBox), c);
}
else
{
richTextBox1.AppendText(c.ToString(CultureInfo.InvariantCulture));
}
}
}
Solution # 2 : Use a timer
public partial class Form1 : Form
{
private Timer tbTimer = new Timer();
string myStr = "This is a test string to stylize your RichTextBox1";
private int charPos = 0;
public Form1()
{
InitializeComponent();
tbTimer.Interval = 100;
tbTimer.Tick += TbTimerOnTick;
}
private void TbTimerOnTick(object sender, EventArgs eventArgs)
{
if (charPos < myStr.Length - 1)
{
richTextBox1.AppendText(myStr[charPos++].ToString(CultureInfo.InvariantCulture));
}
else
{
tbTimer.Enabled = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
tbTimer.Enabled = true;
}
}
This is because the textbox is not refreshing whilst you are still running your code. Try putting this:
foreach (char c in myStr.ToCharArray()) {
Thread.Sleep(100);
richTextBox1.AppendText(c.ToString());
richTextBox1.Refresh();
}
The problem you are having is not in appending the text,
richTextBox1.AppendText(c.ToString()); //Good
works as expected but the issue is that you are putting the UI thread to sleep blocking the drawing of the text on the Rich Text Box.
Thread.Sleep(100); //Not so good
A quick workaround would be to add
richTextBox1.Refresh();
This forces the control to be redrawn after appending the text, but note your entire UI is still going to be frozen while the thread sleeping. A better solution maybe to use a System.Windows.Forms.Timer to accomplish your goal. This class triggers an event every specified interval. Some quick code,
private System.Windows.Forms.Timer TextUpdateTimer = new System.Windows.Forms.Timer();
private string MyString = "This is a test string to stylize your RichTextBox1";
private int TextUpdateCount = 0;
private void button1_Click(object sender, EventArgs e)
{
//Sets the interval for firing the "Timer.Tick" Event
TextUpdateTimer.Interval = 100;
TextUpdateTimer.Tick += new EventHandler(TextUpdateTimer_Tick);
TextUpdateCount = 0;
TextUpdateTimer.Start();
}
private void TextUpdateTimer_Tick(object sender, EventArgs e)
{
//Stop timer if reached the end of the string
if(TextUpdateCount == MyString.Length) {
TextUpdateTimer.Stop();
return;
}
//AppendText method should work as expected
richTextBox1.AppendText(MyString[TextUpdateCount].ToString());
TextUpdateCount++;
}
This updates the text box char by char without blocking the main thread and maintains usability on the front end.