How to send the value to textbox programatically? - c#

I have one textbox and to that textbox i have to send value from virtual keyboard i desigend.
I am send like
txtNumber.Text = txtNumber.Text.Insert(txtNumber.CaretIndex, ((Button)sender).Content.ToString());
txtNumber.CaretIndex += txtNumber.Text.Length;
txtNumber.focus();
The problem is when user forcefully place the cursor in between the text after typing some character, then pressing the key means first time the value is inserting correctly and after that cursor needs to be there.
This logic above make it to stay the cursor position in the end.
How to achieve this ?

Use this code, i have checked it:
int CurrentIndex;
private void textNumber_Click(object sender, EventArgs e)
{
CurrentIndex = textNumber.SelectionStart;
}
private void Key_Click(object sender, EventArgs e)
{
textNumber.Text = textNumber.Text.Insert(CurrentIndex, "_");
}

If I'm understanding the question, I would keep the string being modified in a buffer string variable and make your changes there depending on the virtual kb input. Once this is done, update the TextBox value by txtNumber.Text = bufferedString;

try to do like this txtNumber.Text +=// your code..
and try to put txtNumber.focus(); this line at the start.

There are a couple to ways you can do this.
When the user intents that he/she wants to use the virtual keyboard,
by click of a checkbox or something, you can make the textbox readonly.
or you could set the CaretIndex in the lost focus event of the textbox.
else you can simply call the AppendText("nextsetofchars") method
http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.appendtext.aspx
You can also set the SelectionStart to the length of the string in the lost focus event.
http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.selectionstart.aspx

Related

Trackbar value displayed in textbox C#

Using C# and WinForms, I am trying to display a trackbar value in a textbox. I thought it would be simple enough, and I used the code from the Microsoft Visual studio website. However it simply doesn't work. Here is the code I have:
private void trackBar1_Scroll(object sender, System.EventArgs e)
{
// Display the trackbar value in the text box.
textBox1.Text = "" + trackBar1.Value;
}
If it makes a difference, the trackbar is getting its min/max values from numeric up down boxes, changeable by the user.
Try putting your code into the ValueChanged event handler instead.
Now you seem to use the scroll event, which fires when the user uses scrolling.
You must use the ToString() method.
Value returns an int and text property must be set with string value. (you have a design time error).
private void trackBar1_Scroll(object sender, EventArgs e)
{
textBox1.Text = trackBar1.Value.ToString();
}

Count the number of clicks for two different buttons with one calculate function

I'm sure this is simple but I can't seem to wrap my mind around it
I have two buttons in my C# wpf form: one to mark an answer right, one to mark it wrong. All I need to do is keep track of how many times each button is clicked, but with ONE calculate method.
Any ideas?
Use this
private int correctCounter = 0; // Declared at class level
private int incorrectCounter = 0; // Declared at class level
private void buttonsClicked(object sender, EventArgs e)
{
string s = (sender as Button).Text; // Or ((Button)sender).Text;
if(s == "Correct") { // Change "Correct" to whatever the text of the button is
correctCounter += 1;
} else if (s == "Incorrect") {
incorrectCounter += 1;
}
// Do other things
}
string s = (sender as Button).Text; Will get the text of the button that was clicked and then you just have to compare whatever text is in your two buttons.
More in depth:
(sender as Button) essentially casts the value of the sender to be a Button. So you will end up getting properties of the Button that called the method. You can also write it as ((Button)sender).Text
In your case, we can use the .Text value of the Button object to capture the text of the button. We can then compare the text of the buttons to see which one was clicked.
Having not worked with WPF itself, I'm not certain that this would work but if you had a public function and a pair of global integer variables, each button could call the public function with a boolean passed as a parameter and have the function increment the two variables.

How to set TextBox to only accept numbers?

I have already checked other questions here but the answers are not related to my issue. the following code allows textbox1 to only accept numbers if the physical keyboard (laptop) is pressed:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if ( !char.IsDigit(ch))
{
e.Handled = true;
}
}
but this is not what I wanted (I dont use physical laptop keyboard).
As shown in screenshot, I have windows form with buttons and a textbox. I designed this keyboard and it works well but I want textbox1 to only accept numbers and the ".".
There are only two lines of code inside each button (and only code in the project) which is:
private void buttonName_Click(object sender, EventArgs e)
{
// each button only has this code.
textBox1.Focus();
SendKeys.Send(buttonName.Text);
}
I know how to set txtbox to accept numbers if the physical (laptop ) keys are pressed but here in this case I have control buttons in windwos form and I want to set textBox1 to only accept numbers and the ".". Please help in how to achieve this. Thank you
Declare a string variable at form level, use it to store the last valid text and to restore it when an invalid text is entered on the TextChanged event of your textbox.
string previousText;
public Form1()
{
InitializeComponent();
previousText = String.Empty;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
int dummy, changeLenght, position;
if (!String.IsNullOrWhiteSpace(textBox1.Text) && !int.TryParse(textBox1.Text, out dummy))
{
position = textBox1.SelectionStart;
changeLenght = textBox1.TextLength - previousText.Length;
textBox1.Text = previousText;
textBox1.SelectionStart = position - changeLenght;
}
else
{
previousText = textBox1.Text;
}
}
position and changeLenght are used to keep the cursor where it was before restoring the text.
In case you want to accept numbers with decimals or something bigger than 2147483647, just change dummy to double and use double.TryParse instead of int.TryParse.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int changeLenght, position;
double dummy;
if (!String.IsNullOrWhiteSpace(textBox1.Text) && !double.TryParse(textBox1.Text, out dummy))
{
...
}
}
Suppose button1 is your button control, you could do this:
private void allButtons_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
char c = btn.Text[0]; //assuming all buttons have exactly 1 character
if(Char.IsDigit(c) || c == '.')
{
//process
textBox1.Focus();
SendKeys.Send(btn.Text);
}
//otherwise don't
}
I'm assuming you put this in a common handler, to which you already wired all your buttons (i.e. allButtons_Click).
Problem with this approach, it allows you to type values like 0.0.1, which are most likely invalid in your context. Another way to handle this is to process TextChanged event, store previous value, and if new value is invalid, restore the old one. Unfortunately, TextBox class does not have TextChanging event, which could be a cleaner option.
The benefit of you determining the invalid value is modularity. For example, if you later decide your user can enter any value, but only numbers can pass validation, you could move your check from TextChanged to Validate button click or similar.
Why users may want that - suppose one of the options for input is copy/paste - they want to paste invalid data and edit it to become valid, for example abc123.5. If you limit them at the entry, this value will not be there at all, so they now need to manually paste into Notepad, cut out in the invalid characters, and paste again, which goes against productivity.
Generally, before implementing any user interface limitation, read "I won't allow my user to...", think well, whether it's justified enough. More often than not, you don't need to limit the user, even for the good purpose of keeping your DB valid etc. If possible, never put a concrete wall in front of them, you just need to guide them correctly through your workflow. You want users on your side, not against you.

Defocusing TextBox by clicking it again

I'm making a settings form, where user can assign custom hotkeys for the application. There's a TextBox, and by clicking it with mouse, it focuses and waits for one keypress and then defocuses (by focusing another label):
private void txtKey_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
}
private void txtKey_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.Text = e.KeyCode.ToString();
label1.Focus();
}
Is there a way to defocus focused TextBox (and cancel the key assinging process), by either clicking it again with mouse, or by clicking the GroupBox around it? I can't figure out how to check if TextBox was already focused when clicked (because when clicked, it gets focused before I can test if it's focused). Of course I can add a button "Cancel" next to the TextBox, but that's not what I want.
There is no Click-event for GroupBox, so I can't defocus TextBox by clicking GroupBox around it. Or can I somehow?
You can set/remove the Focus with
Keyboard.Focus = null;
You can also register to the following event:
public event MouseButtonEventHandler PreviewMouseLeftButtonDown
This event fires every time you click on the TextBox, thus you can set the Focus there if you want to.
For Winforms there is a way as well. I'm not proficient in it, but here would be a way:
Make a textBox (e.g. named textBoxFocus) that lies outside your window. Size it 1, 1 and move it to -10,-10 for example. Then you can register to the Click event and write
textBoxFocus.Focus();
It's a bit of a roundabout way, but should achieve what you want.
Thanks to private_meta for getting me to right direction (in comments)! I set the flag with click event, and before setting the flag, testing if flag is set. So first click does not find the flag, but second will. And flag is cleared within textbox Enter-event (which fires before Click-event). Now every other click focuses and every other defocuses textbox, as I wanted.
private void txtKey_Enter(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.Tag = null;
}
private void txtKey_Click(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Tag != null) label1.Focus();
textBox.Tag = "clicked";
}
One of the simple way is that, you may use a bool flag here.
Algorithm:
By default, the bool value is 0;
If(Textbox Selected && flag = 0)
Do your task; and flag = 1;
I hope I could satisfy your query and you can follow this algorithm.

How to detect if an event is sent by an argument

I don't know if it is called an argument (i.e. textbox1.text = "Hello";).
I have a control and there is a text box in it. It has a dropdown box that opens when the text is changed. But when I update the text in the text box that box drops down.
I need a way to make it so it only drops down if someone manually does it.
TBAddressBar.ABText.Text = getCurrentBrowser().Source.ToString();
and
public void ABText_TextChanged(object sender, TextChangedEventArgs e)
{
if (sender == 1*)
{
ABDropDown.Visibility = Visibility.Visible;
}
else
{
ABDropDown.Visibility = Visibility.Collapsed;
}
}
If someone manually does it, presumably they are using keypresses to do so. In that case, use KeyDown or KeyUp events to show the dropdown instead.
What I have done in the past is use a boolean variable that I set when I update my textboxes programically to bypass the TextChangedEvent.
i.e.
bool loading;
....
loading =true;
TBAddressBar.ABText.Text = getCurrentBrowser().Source.ToString();
loading = false;
public void ABText_TextChanged(object sender, TextChangedEventArgs e)
{
if(loading) return;
....
}
Simple, just remove the code from your TextChanged Event.
Anyway you got the basic idea.. Now do your dropdown logic in KeyPress event, since it accepts only characters and not the modifiers. So it behaves closer to your requirement. Not that you cant handle the same using KeyDown and KeyUp, you can, but more code..

Categories