How to select all text in Winforms NumericUpDown upon tab in? - c#

When the user tabs into my NumericUpDown I would like all text to be selected. Is this possible?

private void NumericUpDown1_Enter(object sender, EventArgs e)
{
NumericUpDown1.Select(0, NumericUpDown1.Text.Length);
}
(Note that the Text property is hidden in Intellisense, but it's there)

I wanted to add to this for future people who have been search for Tab and Click.
Jon B answer works perfect for Tab but I needed to modify to include click
Below will select the text if you tab in or click in. If you click and you enter the box then it will select the text. If you are already focused on the box then the click will do what it normally does.
bool selectByMouse = false;
private void quickBoxs_Enter(object sender, EventArgs e)
{
NumericUpDown curBox = sender as NumericUpDown;
curBox.Select();
curBox.Select(0, curBox.Text.Length);
if (MouseButtons == MouseButtons.Left)
{
selectByMouse = true;
}
}
private void quickBoxs_MouseDown(object sender, MouseEventArgs e)
{
NumericUpDown curBox = sender as NumericUpDown;
if (selectByMouse)
{
curBox.Select(0, curBox.Text.Length);
selectByMouse = false;
}
}
You can use this for multiple numericUpDown controls. Just need to set the Enter and MouseDown Events

I was looking around i had the same issue and this Works for me, first select the Item and the second one selects the Text, hope it helps in future
myNumericUpDown.Select();
myNumericUpDown.Select(0, myNumericUpDown.Value.ToString().Length);

I created an extension method to accomplish this:
VB:
<Extension()>
Public Sub SelectAll(myNumericUpDown As NumericUpDown)
myNumericUpDown.Select(0, myNumericUpDown.Text.Length)
End Sub
C#:
public static void SelectAll(this NumericUpDown numericUpDown)
numericUpDown.Select(0, myNumericUpDown.Text.Length)
End Sub

I had multiple numericupdown box's and wanted to achieve this for all. I created:
private void num_Enter(object sender, EventArgs e)
{
NumericUpDown box = sender as NumericUpDown;
box.Select();
box.Select(0, num_Shortage.Value.ToString().Length);
}
Then by associating this function with the Enter Event for each box (which I didn't do), my goal was achieved. Took me a while to figure out as I am a beginner. Hope this helps someone else out

For selecting all text by mouse click or by Tab button I use:
public frmMain() {
InitializeComponent();
numericUpDown1.Enter += numericUpDown_SelectAll;
numericUpDown1.MouseUp += numericUpDown_SelectAll;
}
private void numericUpDown_SelectAll(object sender, EventArgs e) {
NumericUpDown box = sender as NumericUpDown;
box.Select(0, box.Value.ToString().Length);
}

Try
myNumericUpDown.Select(0, myNumericUpDown.Value.ToString().Length);

Related

Why I can not change focus?

Im making a calculator.and for the buttons that type numbers, I wrote a condition that if the focus was on text box 1, it would enter the text there, if not, it would enter text box 2. But unfortunately the code does not work and I dont understand the problem.
(WindosForm(.Net framework))
if (textBox1.Focus() == true)
{
textBox1.Text = textBox1.Text + "1";
}
else
{
textBox2.Text = textBox2.Text + "1";
}
Subscribe to "Enter" event for your two textbox and save it. Use the same method for the two textboxes.
TextBox focusedTB;
private void textBox_Enter(object sender, EventArgs e)
{
focusedTB = sender as TextBox;
}
...
this.textBox1.Enter += new System.EventHandler(this.textBox_Enter);
...
this.textBox2.Enter += new System.EventHandler(this.textBox_Enter);
Now you know the last textbox that got focus.
private void button1_Click(object sender, EventArgs e)
{
focusedTB.Text += "1";
}
Your code appears to be attempting to check if the control is focused. The correct way to do that is:
if (textBox1.Focused)
{
// Because 'Focused' is a property. 'Focus()' is a method.
textBox1.Text = textBox1.Text + "1";
}
.
.
.
The answer to your question Why I can not change focus? is that textBox1 receives the focus every time you call this:
if (textBox1.Focus())
As mentioned in one of the comments, here's how the Focus method works:
// Summary:
// Sets input focus to the control.
//
// Returns:
// true if the input focus request was successful; otherwise, false.
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool Focus();
Note: This is a copy-paste of metadata that you can look at by right-clicking over Focus() in your code and selecting Go to Definition then expanding the definition.
I think you talk about Windows Form ?
You cannot manage like this but use event "Enter" of your textboxes, when you click inside the textbox, you give the focus to this textbox and you can do anything inside. Here I put the right focuses TextBox in a variable.
private TextBox _textBoxFocused; //this is always the righ TextBox
private void textBox1_Enter(object sender, EventArgs e)
{
_textBoxFocused = textBox1;
}
private void textBox2_Enter(object sender, EventArgs e)
{
_textBoxFocused = textBox2;
}

Event that would listen to any label click in form

Well, I'm making a chess game that's based on labels. I need to listen for label click, so when user clicks on an label, I get the name of label he clicked. I know I can do it for each label, but is there an universal event that would help me do the same thing for all of them in one event / loop?
Suppose you have taken 64 labels.
In windows form, on click event of Label1 you will write following code:
private void Label1_Click(object sender, EventArgs e)
{
var label = sender as Label;
MessageBox.Show(label.Name);
}
For remaining 63 Lables, In Design view, select all 63 lables by using Ctrl key --> Go to Property window --> Under Event option select Click option --> From dropdownlist select 'Label1_Click' option.
Just finish & run the application.
You can use a Panel
structure to group your labels and then call the desired event on that Panel, so it will trigger whenever you click one of it's elements.
Another solution would be to identify your label with the coordinates of the mouse click (the amount of code that requires depends how you placed them of course).
Like mentioned in the comments you can assign one event to all...
List<Label> lbls = this.Controls.OfType<Label>().ToList();
foreach (var lbl in lbls)
{
lbl.Click += lbl_Click;
}
void lbl_Click(object sender, EventArgs e)
{
Label lbl = sender as Label;
MessageBox.Show(lbl.Name);
}
You can assign these methods to every label you need to manage in the VS form designer (you go to events of controls, at the click line and select the method in the list instead of double click on it):
private void Label_Click(object sender, EventArgs e)
{
var nameLabel = ( sender as Label )?.Name ?? "Error";
// ...
}
private void Label_Enter(object sender, EventArgs e)
{
( sender as Label ).Cursor = Cursors.Hand;
}
private void Label_Leave(object sender, EventArgs e)
{
( sender as Label ).Cursor = Cursors.Default;
}
Cursor change added for convenience if you want.
If you want to dynamically assign events, you can use the #caner answer, and you can group all in a panel to parse Panel.Controls and assign event.
You can create a custom label class that inherits from Label. You can then subscribe to the Click event of the base class and do your thing.
public class MyLabel : Label
{
public MyLabel()
: base()
{
Click += ProcessClickEvent;
}
private void ProcessClickEvent(object sender, System.EventArgs e)
{
// Do what you want to do
}
}

How to output to a TexBox directly using RadioButtons and CheckBoxes without clicking Buttons

I want to know how to output to a TextBox as soon as a user has clicked on a series of RadioButtons and clicked the CheckBox(es) which are found inside various GroupBoxes on the Form.
Any help will be really appreciated, in case this question has already been answered in the past let me know I have search for it but could not find anything like this.
Sample Form layout:
I am no good at chasing the pictures and especially code as picture doesn't help anyone. Anyway next time please don't do that.
First, for all of your radio and checkboxes (radChocolate, radVanilla, ... radSmall, ..., chkChocoChips, ...) double click and fill Checked event such as:
private void radChocolate_CheckedChanged(object sender, EventArgs e)
{
CalculatePrice();
}
private void radVanilla_CheckedChanged(object sender, EventArgs e)
{
CalculatePrice();
}
// Do the same for other radio and checkboxes
Then add the CalculatePrice code as such (prices are arbitrary):
private void CalculatePrice()
{
decimal price = 0M;
if (radChocolate.Checked) price += 75M;
if (radVanilla.Checked) price += 65M;
if (radStrawberry.Checked) price += 55M;
if (radSmall.Checked) price += 20M;
if (radLarge.Checked) price += 30M;
if (chkChocoChips.Checked) price += 5M;
if (chkCookieCandy.Checked) price += 4M;
if (chkNuts.Checked) price += 3M;
if (chkFreshFruits.Checked) price += 2M;
txtPrice.Text = price.ToString("C");
}
This would do what you wanted to.
You either need to create an event handler for each radio button, or create a single event handler for all the radio buttons. It would depend on what you are trying to accomplish. For the radio button you would want to subscribe to the CheckedChanged event. Then inside this event you can change the text box.
private void radioButtonChangeText_CheckedChanged(object sender, EventArgs e)
{
//Code here to change text box or call sub
textBox.Text = "Hello world";
}
Based upon your link, you can create one event handler and bind it to all the events. (Link explaining binding)
So, every time any value is changed in your form, only one function gets called.
Then, check the values of every component present in your form and calculate value of your textbox.
Right click on a radio button and the go to properties, there click on "events" (that lightning sign). There is an event there called "CheckedChanged". Double click on the cell next to it to generate the event method.
it will generate a code like this,
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show("hi there");
}
you should be able to put any thing you want in there. Assuming you want to show hide the TextBox, you can do it in there.
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
setCheckBoxValue();
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
setCheckBoxValue();
}
private void setCheckBoxValue()
{
int finalPrice = 0;
if (radioButton1.Checked == true)
{
finalPrice = finalPrice + 75;
}
else if (radioButton2.Checked == true)
{
finalPrice = finalPrice + 87;
}
textBox1.Text = finalPrice.ToString("C");
}

Prevent selecting text in a TextBox

Similar questions have been already asked (e.g., here), however I've not found an answer for my specific case. I'm building a custom control based on a DevExpress control, which in turns is based on standard TextBox and I've a flickering problem that seems due to the base TextBox component, which tries to update selection.
Without explaining all the details of my custom control, to reproduce the problem you just need to place a TextBox inside a Form and then use this code:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
textBox1.MouseMove += TextBox1_MouseMove;
}
private void TextBox1_MouseMove(object sender, MouseEventArgs e) {
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
}
}
If you launch it, you click on the TextBox and then you move the cursor toward right you will notice the flickering problem (see video here). For my custom control I would need to avoid this flickering. I'm bound to use a TextBox (so no RichTextBox). Any idea?
The solution has been provided in the meantime by Reza Aghaei by overriding WndProc and intercepting WM_SETFOCUS messages. See here
Depending on what u want to do there are several solutions:
If you want to prevent the selection it would be:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
(sender as TextBox).SelectionLength = 0;
}
Or for selecting all:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
(sender as TextBox).SelectAll();
}
And besides that u also could specify the conditions for selecting, for example:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
if (MouseButtons == MouseButtons.Left) (sender as TextBox).SelectAll();
else (sender as TextBox).SelectionLength = 0;
}
But as long as you want to select the text you always will get some flickering, because a normal Textbox has not the possibility to use things like BeginEdit and EndEdit and so it will change the text first and then select it.
Looking at the video it looks like your textbox is calling WM_ERASEBKGND unnecessarily. In order to remedy this problem you can subclass the textbox class and intercept these messages. Below is sample code which should do the trick (untested) Disclaimer: I have used this technique for other WinForm controls that had the type of flicker shown in your video but not TextBox. If it does work for you, please let me know. Good luck!
// textbox no flicker
public partial class TexttBoxNF : TextBox
{
public TexttBoxNF()
{
}
public TexttBoxNF(IContainer container)
{
container.Add(this);
InitializeComponent();
//Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
//http://stackoverflow.com/questions/442817/c-sharp-flickering-listview-on-update
protected override void OnNotifyMessage(Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
}

get textbox that is in the selected tab

I have a tabcontrol with numerous tabs that all contain a textbox. How can I select the textbox that is in the currently selected tab?
I have this which captures the tabchanged event and tells me which tab is selected, but I cannot figure out how to find the textbox that is in the tab and do
textbox.Select(0, 0);
to select certain text in this textbox...
private void onTabChange(Object sender, TabControlEventArgs e)
{
}
This really sounds like a design mistake. High odds that this TextBox should not be on a tab page at all. If you want to have one text box to be present on every tab page then that's possible, Winforms makes it easy to move controls:
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) {
textBox1.Parent = tabControl1.SelectedTab;
}
If you really meant for any text box to be picked, like the first one in the tab order then:
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) {
var box = tabControl1.SelectedTab.Controls.OfType<TextBox>().Reverse().FirstOrDefault();
if (box != null) {
// etc...
}
}
Use This:
Tab TabView = (Tab)sender;
TextView txt_Tab = (TextView)TabView.FindControl("TextBoxName");
Try this:
TextBox myTB = tabControl2.SelectedTab.Controls[0] as TextBox;
myTB.Select(0, 0);
I think the following links can provide you some hints about your problem
How to access controls that are inside a TabControl tab?
and
How to get control(s) from TabPage in C#?

Categories

Resources