I have code using an AutoCompleteStringCollection:
private void txtS_TextChanged(object sender, EventArgs e)
{
TextBox t = sender as TextBox;
string[] arr = this.dbService.GetAll();
if (t != null)
{
if (t.Text.Length >= 3)
{
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
collection.AddRange(arr);
this.txtSerial.AutoCompleteCustomSource = collection;
}
}
}
How can I get the event for "item selected" after user selects an AutoComplete suggestion? And value of field?
There's no such thing as chosen item Event for a textBox, which I believe you're using for the AutoComplete. What you could do is add a key down event to your textBox. There you could verify if the enter key was pressed (clicking on a suggested link is the same as pressing enter). Something like that:
private void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == Keys.Enter) {
String selItem = this.textBox1.Text;
}
}
Rather than focusing on detecting if an item from the autocomplete list was selected, instead you should check if the current value of the textbox is in the set of autocomplete entries.
if (txtSerial.AutoCompleteCustomSource.Contains(t.Text))
{
// Logic to handle an exact match being selected
...
}
else
{
// Update the autocomplete entries based on what was typed in
}
If the user typed in an exact string which happens to be be within the list of autocomplete values -- OR -- they select that value from the autocomplete list -- should this produce any different behavior? I think that in most cases it should not.
Short answer: make a custom event
Long answer:
You can intercept the KeyDown event of your textbox for numpad Enter or normal Enter and the mouse doubleclick event of the toolbox and compare the content of the toolbox then fire an event if they match that a delegate will pick up.
It depends a bit on the situation and workflow of your program but I have an example where I trigger the check on focuslost of the combobox. And then I check if the selected value is part of the collection:
private void cmbt1Name1_LostFocus(object sender, RoutedEventArgs e)
{
ComboBox cmb = sender as ComboBox;
FillFivePoints(cmb);
}
private void FillFivePoints(ComboBox usedCombobox)
{
if (txtSerial.AutoCompleteCustomSource.Contains(t.Text))
{
...
Related
I have two ComboBoxs 1st with CmdGuarantor and the 2nd with CmdGuarantorClass as names.
CmdGuarantor has a list of 7 items:
NSSF Private MOH Army IS GS UNHCR while CmdGuranatorClass has 1st Class 2nd Class 3rd Class in its items list.
I want to disable CmdGuarantorClass whenever CmdGuarator.SelectedItem.ToString() == "Private" || CmdGuarator.SelectedItem.ToString() == "UNCHR"
how can I accomplish that?
P.S.: I tried using the EnableChanged event on CmdGuarantorClass ComboBox using this method
private void ComboBox2_EnabledChanged(object sender, EventArgs e)
{
if (CmdGuarantor.SelectedItem.ToString() == "Private" || CmdGuarantor.SelectedItem.ToString() == "UNCHR")
{
CmdGuarantorClass.Enabled = false;
}
else CmdGuarantorClass.Enabled = true;
}
but with no luck.
thank you in advance.
You should be listening for the SelectedIndexChanged event, not the EnabledChanged event. EnabledChanged is only raised when the Enabled property is changed.
Assuming the datagridview tag is a mistake and you are talking about two different winform ComboBoxes… then… I suggest you wire up the first combo boxes SelectedIndexChanged event.
This event will fire when the user changes the selection in the combo box. In that event you can check the combo box values as you have done and then set the other combo boxes Enabled property as needed. Something like…
private void comboGuarantor_SelectedIndexChanged(object sender, EventArgs e) {
if (comboGuarantor.SelectedItem.ToString() == "Private" ||
comboGuarantor.SelectedItem.ToString() == "UNCHR") {
comboGuarantorClass.SelectedIndex = -1;
comboGuarantorClass.Enabled = false;
}
else {
comboGuarantorClass.Enabled = true;
}
}
I am trying to fill two text box in a form using button controls but it seems to work for 1 only. when I run the program, I can't select between two text box. what condition should I use?
private void Button0_Click(object sender, EventArgs e)
{
if (???????????????????)
{
metroTextBoxQuantity.Text = metroTextBoxQuantity.Text + "0";
}
else
{
metroTextBoxItemcode.Text = metroTextBoxItemcode.Text + "0";
}
}
One possible solution is to create a Control variable that stores a reference to the last clicked textbox. This would be handled by the Click event for both textboxes. Then, in your number button clicks, just append the number to the selected textbox variable. Something like this:
Control SelectedTextbox { get; set; } = null;
//Use this event handler for both the Quantity and Itemcode textbox
public TextBox_Click(object sender, EventArgs e)
{
SelectedTextbox = (Control)sender;
}
private void Button0_Click(object sender, EventArgs e)
{
if(SelectedTextbox == null)
throw new Exception("SelectedTextbox has not been set");
SelectedTextbox.Text += "0";
}
Note, if MetroTextBox doesn't inherit from Control, you'll need to change SelectedTextbox to a different type. It most likely does though.
You also may want to consider using a single event handler for all the button clicks instead of one for each. You can either parse what number button was clicked using the sender's name, or you can store the number of the button in the button's Tag and read it from there. But that's best left for another question.
I understand that there are Listbox Select index change questions floating around. However, this question focuses on a different matter. I have a list box, with some strings on the form. What I am trying to accomplish is to be able to scroll through the items in the list box (i.e using the arrow keys to navigate to a particular item). Once I navigate to the item I want, I want to either be able to press enter on the item and continue my application. So, the question is How to determine the Event type of that was raised on the List box in order to compare the event with either a Mouse Click event or a Keydown event, thus allowing me to decide which conditional statement to execute based of the result of the boolean expression......The reason I need to determine the type is because if the user presses ENter on the selectedIndexed Item a Dialogbox Appears, currently the dialogbox appears everytime a user HIGHLIGHTS a new item (you can see how that is a problem).
Psuedo Code
if (Listbox_Selected_Event_EventType isEqualTo Mouse_Click)
{
// execute code
} else if (Listbox_Selected_Event_EventType isEqualTo KeydownEvent)
{
// execute code
}
Finished code thanks to Evan,
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
if (e.KeyChar == (char)Keys.Return)
{
var file = Directory.GetFiles(urlHistoryFolder, listBox1.Text).FirstOrDefault();
String line;
try
{
using (StreamReader sr = new StreamReader(file))
{
line = sr.ReadToEnd();
}
DialogResult result1 = MessageBox.Show("Are You sure you want to Load this WebService", "Important Question", MessageBoxButtons.YesNo);
if (result1 == DialogResult.Yes)
{
//MessageBox.Show("Loading WebService");
textEndPointUri.Text = line;
listBox1.Visible = false;
GetBtn_Click(sender, e);
}
}
catch (Exception exp)
{
Console.WriteLine("File could not be read:");
Console.WriteLine(exp.Message);
}
}
}
}
The problem is you are looking at the wrong event. You should be handling the MouseClick event and the KeyUp or KeyDown event on the list box.
private void listBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Get the selected item and do whatever you need to it
//Open your dialog box
}
}
private void listBox1_Click(object sender, MouseEventArgs e)
{
//Get the selected item and do whatever you need to it
//Open your dialog box
}
Then there is no need for a conditional as you have handled both the events individually. Make sure you remove your Dialog box code from the SelectedIndexChanged event.
EDIT:
SelectedIndexChanged fires every time you select and item in the ListBox Object. The box still stores an index even if you don't handle that event. So you can reference or manipulate the PROPERTY of SelectedIndex anywhere. If you handle the two above events, any time a user clicks an item or presses enter you check if there is a selected item:
if (listBox1.SelectedIndex != -1)
{
//Now we know you have an item selected
//Do some stuff
}
Add a Button to the Form and set the AcceptButton() Property of the FORM to that Button. Now when Enter is pressed the Button will fire. Display your dialog in the Button Click() handler. This has the added benefit that people can also click the Button instead of pressing Enter:
private void button1_Click(object sender, EventArgs e)
{
if (ListBox.SelectedIndex != -1)
{
// ... display the dialog ...
Console.WriteLine(ListBox.SelectedItem.ToString());
}
}
To identify if ENTER has been pressed:
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
// do something
}
This is my LostFocus event handler:
private void txtThrow_LostFocus(object sender, System.EventArgs e)
{
TextBox source = (TextBox)sender;
if (source.Text == "")
source.Text = "0";
}
This actually interferes with txtThrow_KeyPress, so that after I do my processing on my TextBox which accepts to only hold one character, I find it having two: mine and this zero you see here!! What I want to do is to keep txtThrow_KeyPress exactly as it is, but whenever the user types nothing, I want to enforce a zero.
What I can understand from here is that txtThrow_LostFocus is triggered before txtThrow_KeyPress is done with its job, since at the time txtThrow_LostFocus is triggered, the text is still empty. How can that be correct?!
I would recommend using the TextChanged event instead of the KeyPress event. I am assuming the text box could be empty already, and the user presses Backspace or something of the nature.
TextChanged event is triggered every time the text is changed within the field.
And the code you have should work perfectly fine when you fill the new event handler method with such. However, you may need to use
private void txtThrow_LostFocus_TextChanged(object sender, System.EventArgs e)
{
TextBox source = (TextBox)sender;
if (source.Text == "" || source.Text == null)
source.Text = "0"
}
Hope this helps!
Try to this code
private void txtThrow_LostFocus_TextChanged(object sender, System.EventArgs e)
{
TextBox source = (TextBox)sender;
if (string.nullorempty(source.text)
source.Text = "0"
}
I am using c# winform.
I have 2dimensional array of text boxes I want them to accept only Letters from A-I I've created the method but that works for only one text box.
Here is my code:
textbox[i,j].Validated+=new EventHandler(TextBox_KeyPress);
private void TextBox_KeyPress(object sender, EventArgs e)
{
bool bTest = txtRegExStringIsValid(textbox[1,1].Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false)
{
tip.Show("Only A-I", textbox[1,1], 2000);
textbox[1,1].Text = " ";
}
}
private bool txtRegExStringIsValid(string textToValidate)
{
Regex TheRegExpression;
string TheTextToValidate;
string TheRegExTest = #"^[A-I ]+$";
TheTextToValidate = textToValidate;
TheRegExpression = new Regex(TheRegExTest);
if (TheRegExpression.IsMatch(TheTextToValidate))
{
return true;
}
else
{
return false;
}
}
Can anyone please guide what should I do make this code work for all text boxes?
if this works for textbox[1,1] you could register your private void TextBox_KeyPress(object sender, EventArgs e) as eventhandler for all your textboxes and instead of textbox[1,1] you could use ((TextBox)sender)
i want text boxes to accept only letters from a-i actually i am trying to make sudoku
There's a much simpler solution than regular expressions, and you don't even need to handle the Validated event to implement it.
In a situation like this, where there are only certain characters that you want to prevent the user from entering, handling the KeyDown event is a much better solution. The user gets immediate feedback that the letter they tried to enter was not accepted. The alternative (the Validating and Validated events) actually wait until the user tries to leave the textbox to rudely alert them that their input was invalid. Especially for a game, this tends to break concentration and isn't particularly user-friendly.
Doing it this way also makes it irrelevant which individual textbox raised the event. Instead, you will handle it the same way for all of the textboxes—by completely ignoring all invalid input.
Here's what I'd do:
First, attach a handler method to your textbox's KeyDown event. You can do this from the Properties window in the designer, or you can do it through code, as you have in the question:
textbox[i,j].KeyDown += TextBox_KeyDown;
Then, you need to put the logic into your event handler method that determines if the key that the user just pressed is in the allowed range (A through I), or outside of it:
private void TextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Determine if the keystroke was a letter between A and I
if (e.KeyCode < Keys.A || e.KeyCode > Keys.I)
{
// But allow through the backspace key,
// so they can correct their mistakes!
if (e.KeyCode != Keys.Back)
{
// Now we've caught them! An invalid key was pressed.
// Handle it by beeping at the user, and ignoring the key event.
System.Media.SystemSounds.Beep.Play();
e.SuppressKeyPress = true;
}
}
}
If you want to restrict the user to typing in only one letter, you can add code to handle that in the above method, or you can take an even simpler route and let the textbox control handle it for you automatically. To do that, set the MaxLength property of the textbox to true, either in the designer or through code:
textbox[i,j].MaxLength = true;
Check the text of the sender instead of whatever textbox[1,1] is.
Use the sender parameter of the event handler to identify the textbox responsible for the event.
The first thing that will help you is casting the sender of your event to a TextBox like this:
(Also, as Cody Gray said, this is a TextBox_Validated event, not a KeyPress event so I've renamed it appropriately)
private void TextBox_Validated(object sender, EventArgs e)
{
TextBox tb = sender as TextBox()
if (sender == null)
return;
bool bTest = txtRegExStringIsValid(tb.Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false) {
tip.Show("Only A-I", tb, 2000);
tb .ext = " ";
}
Next you need to actually get into that code for every textbox. There are two obvious approaches to that, you can either assign the eventhandler to each textbox in the array or you can use a custom textbox which always does this validation and then add that to your array.
Assign eventhandler to textboxes
foreach(var tb in textbox)
{
tb.Validated += new EventHandler(TextBox_KeyPress);
}
Create custom textbox control
Create the custom text box control (Add a user control to the project) and then just use it exactly as you would a normal textbox.
public partial class ValidatingTextBox: TextBox
{
public ValidatingTextBox()
{
InitializeComponent();
}
protected override void OnValidating(CancelEventArgs e)
{
bool bTest = txtRegExStringIsValid(this.Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false)
{
tip.Show("Only A-I", this, 2000);
this.Text = " ";
}
}
private bool txtRegExStringIsValid(string textToValidate)
{
// Exactly the same validation logic as in the same method on the form
}
}