How to give an initial value to textBox? - winforms

I want my C# program to have initial values for its textboxes. For example, in one of the textboxes, it should say "Please enter your name".
When you click (or tabStop) on the textbox, the initial value should disappear and the user will be able to enter their input to the textbox.
I can do all this with click_event, but using this method the initial text would not have less opacity. How am I able to achieve this?

This is how I finally did it:
Boolean first_time_click = true;
private void Form1_Load(object sender, EventArgs e)
{
textBox1.ForeColor = System.Drawing.Color.Gray;
textBox1.Text = "Enter the Text";
}
private void For_First_Click()
{
if (first_time_click)
{
textBox1.Clear();
textBox1.ForeColor = textBox1.ForeColor = SystemColors.WindowText;
}
first_time_click = false;
}
private void textBox1_Click(object sender, EventArgs e)
{
For_First_Click();
}

I assume you are talking about winform (tabstop) you have to handle it within the event key-press. you can use the below code:
TextBox1.Select(0, TextBox1.Text.Length);
this will select the text and window will remove it for you as soon as the user start to typing
you can use the same code to have this behavior also for TabStop

All you need to do is set the Textbox's .Text property and use GotFocus event to clear the box when the person clicks (or tabs) into it to start typing.
Always remember that there are more ways than the mouse to navigate a form, so use the GotFocus event to determine when the user enters a control, and use the Validated event to determine when they've changed data and exited the control.

For this type of effect you need java script.Because java script provide you functionality of mouse hover and mouse out these are the functions which provide you the same functionality which u seeing in this page of search bar. If you need code reply me i can give you.

Related

Winforms- Stop SelectedItem being highlighted without using the style DropDownList

This is about ComboBox used in Winforms. I need to stop the selected item being heighlighted. I know I can get it done if I set the style of the combobox to ComboBoxStyle.DropDownList.
But I'm looking for a solution where I don't have to use that. Instead, at the moment what I have done is using ComboBoxStyle.DropDown.
I don't have any other option, because if I set it to DropDown, I have to deal with some other issue in my code. It's due to something else which I cannot avoid.
Can someone suggest an alternative pls ?
use the following code in your form's Paint event.
private void myForm_Paint(object sender, PaintEventArgs e)
{
comboBox1.SelectionLength = 0;
}
or pass focus to another control in your combo box selected index changed event:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.Focus();
}

How can I get more than one character to show in a messagebox from a textbox user input?

I have made a textbox and I want the user to type in a string of numbers and hit enter. I have setup the following:
private void textBox1_TextChanged(object sender, EventArgs e)
{
String UserBarcode;
Focus();
UserBarcode = Console.ReadLine();
MessageBox.Show(UserBarcode);
}
When I enter any key into the textbox, I get a message box with nothing in it. I want to have the program wait til it hears the enter key then display the contents of the textbox.
The Textbox.TextChanged event fires as soon as the text in the textbox is changed at all. If you want a message box with the full string, you probably want to consider using the Textbox.LostFocus event or a button's Click event.
So you could have something like (I'm taking a stab at this here, as I've used VB rather than C#)
private void textBox1_LostFocus(object sender, EventArgs e)
{
MessageBox.Show(sender.Text)
}
If you're using a button, the above function should work, but you'll want to substitute textBox1.Text for sender.Text.
Take a look at Focus and Validation Events
There are several events that you can handle, depending on your goals and how your application is designed. If you want to perform validation and/or are using data binding, you may want to go with handling the validating/validated events. By default data bindings update a bound property after OnValidating. If you use LostFocus and read the value from a bound object, instead of your control, you will get inconsistent results.
I was able to figure it out finally. For some reason when I manually entered the code I kept getting multiple random errors. I started a new Visual C # Windows Forms Application, Made a textbox, chose the keydown property and double clicked on it to have the program inject the code for the keydown function and then I filled in the if statement pointing to the enter key. The final code looks like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show(textBox1.Text);
}
}

How to prevent key entry with NumericUpDown control?

I have a numericupdown control on a winform and I noticed while testing that not only you have the option of changing the value by pressing up and down key but also simply entering the values from your keyboard.
I don't want that. I only want the user to be able to change the numericupdown's value only by clicking the up and down buttons within the box.
So far I simply can't find a solution.
Does anyone know how to do this?
To disable user from editing, set Readonly property to true.
updown.ReadOnly = true;
For more tailoring, you may refer this answer.
Sounds bad for user experience depending on the range of values you are allowing.
To do this you need to create a control with inherits from NumericUpDown and override the OnKeyPress/OnKeyDown methods.
Using updown.ReadOnly = True; does not work for me. It seems to be a reoccuring bug.
But catching any changes and then undo it does. For this bind the function updown_ValueChanged() to the updown.ValueChanged attribute.
decimal spin = 1;
private void updown_ValueChanged(object sender, EventArgs e)
{
if (updown.ReadOnly)
{
if (updown.Value != spin)
{
updown.Value = spin;
}
}
else spin = updown.Value;
}

Setting Default Keyboard Focus On Loading A UserControl

I have an MVVM setup with a mainwindow that contains a ContentControl.
I set this to a particular viewmodel which then maps to a view.
A view is a usercontrol.
I want to be able to set the default keyboard focus to a default element in the usercontrol(View) when it loads so the application can eventually be driven just by using up, down, left, right and enter.
Some of my failed attempts are setting
FocusManager.FocusedElement="{Binding ElementName=DefaultElement}"
in my content control tag. This sets the logical focus but not the keyboard focus
I'd rather keep the solution in xaml if possable but have tried placing the following in code behind.
Keyboard.Focus(DefaultElement);
This does not work but if I popup a message box first it does. I'm a little confused as to why.
MessageBox.Show(Keyboard.FocusedElement.ToString());
Keyboard.Focus(DefaultElement);
EDIT::::
I just placed this in my onloaded event of my user control. It seems to work but can anyone see any issues that might arrise at this priority level. I.E a circumstance when the action will never run?
Dispatcher.BeginInvoke(
DispatcherPriority.ContextIdle,
new Action(delegate()
{
Keyboard.Focus(DefaultElement);
}));
It seems that this wpf the you have to implement a workaround on a case by case basis. The solution that seemed to work best, most of the time for me was to insert the focus code inside the dispatcher when OnVisible was changed. This sets the focus not only when the View/Usercontrol loads but also if you a changing Views by way of Visibility. If you Hide and then Show a ContentControl that is mapped to your ViewModels then the Loaded event won't fire and you'll be forced to Mouse input, or tabbing (Not so good if you want to navigate your app with a remote control).
VisibilityChanged will always fire however. This is what I ended up with for my listbox.
private void ItemsFlowListBox_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue == true)
{
Dispatcher.BeginInvoke(
DispatcherPriority.ContextIdle,
new Action(delegate()
{
ItemsFlowListBox.Focus();
ItemsFlowListBox.ScrollIntoView(ItemsFlowListBox.SelectedItem);
}));
}
}
I had the same symptom for a WPF UserControl hosted in a Winforms application. Just wanted to note I was about to try this solution when I found a normal TabIndex in the Winforms app fixed it
Per How to set which control gets the focus on application start
"The one with the minimum tab index automatically gets the focus
(assuming the TabStop property is set to true). Just set the tab
indices appropriately."
It's a tricky one with no easy answer. I'm currently doing this, although I'm not sure I like it:
public MyView()
{
InitializeComponent();
// When DataContext changes hook the txtName.TextChanged event so we can give it initial focus
DataContextChanged +=
(sender, args) =>
{
txtName.TextChanged += OnTxtNameOnTextChanged;
};
}
private void OnTxtNameOnTextChanged(object o, TextChangedEventArgs eventArgs)
{
// Setting focus will select all text in the TextBox due to the global class handler on TextBox
txtName.Focus();
// Now unhook the event handler, since it's no longer required
txtName.TextChanged -= OnTxtNameOnTextChanged;
}
And in case you're wondering what the global class handler does, it's this:
protected override void OnStartup(StartupEventArgs e)
{
...
// Register a global handler for this app-domain to select all text in a textBox when
// the textBox receives keyboard focus.
EventManager.RegisterClassHandler(
typeof (TextBox), UIElement.GotKeyboardFocusEvent,
new RoutedEventHandler((sender, args) => ((TextBox) sender).SelectAll()));
which auto selects TextBox text when receiving keyboard focus.

ToolStrip Buttons flashes

I have a windows form with a toolstip in it with several buttons.
When the mouse is over a button of the toolstip then the toolstrip button starts to flash... looks like it gets and loses focus every second.
That results for the click to do nothing if the user click at the time that the button has no focus therefore the user has to click the button again and again util he gets the timing correct.
Does anyone knows anything about this?
I rally need some answers as soon as possible...
Thank you very much
I have found the reason...
The toolstrips in windows forms have by default the tooltips set to Auto and if the tooltip opens on the taskbar then the toolstrip loses focus.
The solution to this is to either disable the tooltips or to set it to manual and show the tooltip at another place.
Here is the code for showing the tool tip above the item manually:
private readonly ToolTip currentToolTip = new ToolTip();
private void ToolStripItem_MouseEnter(object sender, EventArgs e)
{
ToolStripItem item = (ToolStripItem)sender;
this.currentToolTip.Show(item.ToolTipText, item.Owner, item.Bounds.X, -20);
}
private void ToolStripItem_MouseLeave(object sender, EventArgs e)
{
ToolStripItem item = (ToolStripItem)sender;
this.currentToolTip.Hide(item.Owner);
}
You have to add the event handlers to all your ToolStripItems and set the ToolStrips' ShowItemToolTips to false.

Resources