Selecting dynamically created listboxs items in C# - c#

I dynamically created a Listbox and filled it with some items, Upon typing a dot in a Textbox i want to show the Listbox so that the user can select any item by using arrow keys .
I did everything up to this point. When the user types a dot in the Textbox, The Listbox gets shown, But the arrow keys wont select any items!
private void txtResults_KeyDown(object sender, KeyEventArgs e)
{
string[] words= ((TextBox)sender).Text.Split(' ');
string s = sampleWord.Text = words[words.Length - 1];
if (e.KeyCode == Keys.OemPeriod)
{
ShowPopUpList(s);
}
else if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)
{
lst.Focus();//doesnt work :-/
}
else
{
lst.Hide();
txtResults.Focus();
}
}
This is the code for creating the listbox on FormLoad()
private void CreateListBox()
{
lst = new ListBox();
lst.Size = new Size(70, 130);
lst.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
lst.KeyDown += lst_KeyDown;
lst.DoubleClick += lst_DoubleClick;
//adding some test input
lst.Items.Add("بسم");
lst.Items.Add("الله ");
lst.Items.Add("الرحمن ");
lst.Items.Add("الرحیم ");
lst.Items.Add("بنام ");
lst.Items.Add("خداوند ");
lst.Items.Add("بخشنده ");
lst.Items.Add("مهربان ");
lst.Items.Add("الهی شکرت ");
}
private void ShowListbox()
{
txtResults.SelectionStart = txtResults.Text.Length;
txtResults.SelectionLength = 0;
Point index = txtResults.GetPositionFromCharIndex(txtResults.SelectionStart-1);
lst.Location = new Point (index.X-50, index.Y+70);
this.Controls.Add(lst);
lst.BringToFront();
lst.Show();
}
In ShowPopUpList(s) the ShowListbox() method is called. nothing fancy about it!
Note:
I only need the list box to get focus when i use UP or DOWN arrow keys to explicitly select an item. unless then i need to be able to freely continue typing and dont lose focus to listbox.
Whats the way around doing it ?

Remove focus from the textbox keydown handler and place it here:
private void ShowPopUpList(string s)
{
//your initialization of the
//listbox here and after..
listBox1.Focus();
}
Another way:
if (e.KeyCode == Keys.OemPeriod)
{
ShowPopUpList(s);
listBox1.Focus();
}
The real big difference is it gets focus rightaway.with your old code would first check the keydown and on the second hit it would already contain the focus.
Final Edit:
If Listbox needs to get the focus on up/down arrow keys(and only with those keys):
if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)
{
ShowPopUpList();
listBox1.Focus();
listBox1.SelectedIndex = 0;
}

This worked just fine and dandy for me :)
ListBox lb;
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Contains("."))
{
lb = new ListBox();
lb.Location = textBox1.Location;
this.Controls.Add(lb);
lb.Items.Add("Item 1");
lb.Items.Add("Item 2");
lb.Items.Add("Item 3");
lb.Show();
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
lb.Focus();
}
}

Related

How can I enter data to Textboxes sequentially

I'm a newbee to C# and I'm trying to write code in Visual Studio. I need your help.
I want to enter numbers to 20pcs textbox in tabpage1 in form by hand held barcode scanner in C#. Cursor must go to next textbox after reading from barcode scanner. And I will check the read data with some conditions (between 2 values numbers etc) for every textbox.
I write some code but it makes code size big. I think it must be easy way I need your comment and help.
The barcode scanner reads the barcode and sends barcode number + enter code. And barcode scanner read and put number to first textbox then pass to next textbox and it repeating for all textbox - how can I do this easily?
Thanks
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox1.SelectAll();
textBox2.Focus();
e.Handled = true;
}
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.SelectAll();
textBox3.Focus();
e.Handled = true;
}
}
.
.
.
.
private void textBox20_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox20.SelectAll();
textBox1.Focus();
e.Handled = true;
}
}
The good news is that the sender object is always that control which has triggered the event. In other words the sender is a reference to one of your TextBoxs.
You can take advantage of this fact and you can have a single event handler, which could be reused for multiple events.
private void textBoxN_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textBoxCurrent = sender as TextBox;
textBoxCurrent.SelectAll();
//TODO: set focus for next
e.Handled = true;
}
}
So, the next question is how to get a reference to the next TextBox?
You can use the Tag property for this.
In case of WinForms the Control object has a property called Tag.
In case of WPF the FrameworkElement object has a property called Tag.
In both cases this property is an object so we can store anything in that. If we populate that with a reference to the next TextBox then the generic handler would look like this:
private void textBoxN_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textBoxCurrent = sender as TextBox;
textBoxCurrent.SelectAll();
var textBoxNext = textBoxCurrent.Tag as TextBox;
textBoxNext.Focus();
e.Handled = true;
}
}
What's left?
Populate the Tag properties
Subscribe to the KeyDown events
private void Init()
{
var textBoxes = new List<TextBox> { TextBox1, TextBox2, ..., TextBox20 };
foreach(var item in textBoxes.Select((textBox, index) => (textBox, index))
{
var nextIdx = (item.index + 1) % textBoxes.Count;
item.textBox.Tag = textBoxes[nextIdx];
item.textBox.KeyDown += textBoxN_KeyDown;
}
}
We have created an iterator here which is deconstructed into a textbox and an index of this TextBox in the textBoxes collection.
We have calculated the next TextBox index into the nextIdx. Then we have wired up everything.
here is an idea for solving
class Program
{
LinkedList<TextBox> _textBoxes;
ctor()
{
_textBoxes = new LinkedList<TextBox>();
_textBoxes.List.AddLast(textbox1);
_textBoxes.List.AddLast(textbox20);
}
private void textBox_KeyDown_justOneCommonHandle(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textboxCurrent = _textBoxes.Current;
// make sure that Value is the sender
textboxCurrent.SelectAll();
_textBoxes.MoveNext();
var textboxNext = _textBoxes.Current;
// check the end of list
textboxNext.Focus();
e.Handled = true;
}
}
}
# Peter Csala, #Ivan Stavenchuk
Thanks for your idea and help. I solved my problem as shown below
I added a main Textbox (textBox21) and used keydown event of main textbox
private void textBox21_KeyDown(object sender, KeyEventArgs e)
{
TextBox tb = new TextBox();
tb.Name = "textBox" + i.ToString();
if (e.KeyCode==Keys.Enter)
{
TextBox tbx = this.Controls.Find(tb.Name, true).FirstOrDefault() as TextBox;
tbx.Text = textBox21.Text ;
i++;
if (i>20) i=1;
textBox21.SelectAll();
}
}

C# TextBox Auto Caps Lock On

I need the following code : When I press shift key then I write small letters in my TextBox in other case I write big letters something like a “reverse” or all time pressed Caps Lock Key.
So This code and other similar is helpless because there are only one kind of letter size :
textBox1.CharacterCasing = CharacterCasing.Upper;
textBox1.CharacterCasing = CharacterCasing.Lower;
Thanks for help !
The easiest option is to change the text in the TextChanged event method. After entering a character, change its layout. But you must remember that text can be pasted / cut.
If you ignore this problem, you can use this simple example:
public partial class Form1 : Form
{
int last_len = 0;
bool char_to_lower = false;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
// save last cursor position
var select_index = textBox1.SelectionStart;
// if text not delete - change char casing
if (textBox1.Text.Length > last_len && select_index > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append(textBox1.Text.Take(select_index - 1).ToArray());
// check SHIFT and CAPS
if (char_to_lower || Control.IsKeyLocked(Keys.CapsLock))
sb.Append(textBox1.Text[select_index - 1].ToString().ToLower());
else
sb.Append(textBox1.Text[select_index - 1].ToString().ToUpper());
sb.Append(textBox1.Text.Skip(select_index).ToArray());
// insert new text in textBox
textBox1.Text = sb.ToString();
// return cursor position
textBox1.SelectionStart = select_index;
}
// save last length
last_len = textBox1.Text.Length;
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Shift) char_to_lower = true;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Shift) char_to_lower = false;
}
}

C# KeyUp & KeyDown textbox event to control the selected item of listbox

I have a textbox in my form that I am using as a search bar for my listbox. Currently I have the textbox set up to actively select an item in the listbox while you type with the following code:
private void TextBox1_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox)sender;
listBox1.SelectedIndex = textBox.TextLength == 0 ?
-1 : listBox1.FindString(textBox.Text);
}
What I would like to accomplish is to be able to also use the up & down arrow keys to adjust what is selected. For example if the listbox contains two items: Test1 & Test2 when you begin typing "t" test1 will be selected. Opposed to having to finish typing "test2" to change what is selected I would like to be able to type "t" then press the down arrow key to select test2 however keep the focus in the textbox.
I have tried using the following, however when pressing the up or down arrow key the cursor in the textbox adjusts instead of the selectedIndex
private void TextBox1_KeyUp(object sender, KeyEventArgs e)
{
int index = listBox1.SelectedIndex;
index = index--;
listBox1.SelectedIndex = index;
}
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
int index = listBox1.SelectedIndex;
index = index++;
listBox1.SelectedIndex = index;
}
You got confused by the event name.
KeyUp and KeyDown refers to pushing a keyboard button up and down, not pressing up and down arrows. To do what you are looking for, you would need either one of them, e.g: KeyUp like follows:
private void TextBox1_KeyUp(object sender, KeyEventArgs e)
{
int index = listBox1.SelectedIndex;
if(e.KeyCode == Keys.Up)
{
index--;
}
else if(e.KeyCode == Keys.Down)
{
index++;
}
listBox1.SelectedIndex = index;
}
#Sohaib Jundi THANK YOU!!! This cleared things up beyond belief! I ended up adjusting the code slightly to fix an error that was occurring, as well as a little bug the cursor was having in case anyone else runs into anything similar to this.
private void TextBox1_KeyUp(object sender, KeyEventArgs e)
{
int index = listBox1.SelectedIndex;
int indexErrorFix = listBox1.Items.Count;
if (e.KeyCode == Keys.Up)
{
index--;
}
else if (e.KeyCode == Keys.Down)
{
index++;
}
if (index < indexErrorFix && index >= 0)
{
listBox1.SelectedIndex = index;
}
else { }
textBox1.SelectionStart = textBox1.Text.Length;
}

C# Call a function when a second key is pressed

I'm lost calling a function when a second key is pressed. I have used KeyDown event for my buttons. And that KeyDown will call a function that will check that button. My problem is after checking that button, the user must press another Enter Key or Spacebar to go on the next data.
This is for my radiobutton1 KeyDown event
private void btn1_KeyDown(object sender, KeyEventArgs e)
{
btn1.BackColor = Color.Blue;
checkAns(btn1.Text, btn1);
}
This is my checkAns function that will check the selected button
private void checkAns (string ansText, RadioButton rdo)
{
var row = dTable.Rows[currentRow];
var ans = row["ANSWER"].ToString();
if (ansText == ans)
{
rdo.BackColor = Color.Green;
correctAdd();
//MessageBox.Show("Correct");
}
else
{
rdo.BackColor = Color.Red;
wrongAdd();
//MessageBox.Show("Wrong. Answer is" + " \n " + ans);
}
nextEnter (------); //Here I'm not sure how to call the another keydown/keypress event or value of the enter key
}
This is my nextEnter function
private void nextEnter(------) //Also at this part.
{
if (------ == Keys.Enter) //And here.
currentRow++;
currentNo++;
remain--;
nextRow();
}
i solve this problem by having the form increment a variable during enter keydown event.
private void frmTest_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Space)
{
entCount++;
}
}
and use if statement when entCount == 2, show the next data and reset the entCount to 0.
To demonstrate what I meant in my comment:
You could pass the KeyCode property of your KeyEventArgs from btn1_KeyDown
private void btn1_KeyDown (object sender, KeyEventArgs e)
{
btn1.BackColor = Color.Blue;
checkAns (btn1.Text, btn1, e.KeyCode);
}
to checkAns
private void checkAns (string ansText, RadioButton rdo, Keys pressedKey)
{
var row = dTable.Rows [currentRow];
var ans = row ["ANSWER"].ToString ();
if (ansText == ans)
{
rdo.BackColor = Color.Green;
correctAdd ();
//MessageBox.Show("Correct");
}
else
{
rdo.BackColor = Color.Red;
wrongAdd ();
//MessageBox.Show("Wrong. Answer is" + " \n " + ans);
}
nextEnter (pressedKey); //Here I'm not sure how to call the another keydown/keypress event or value of the enter key
}
And further on to nextEnter:
private void nextEnter (Keys key) //Also at this part.
{
if (key == Keys.Enter) //And here.
currentRow++;
currentNo++;
remain--;
nextRow ();
}
Tell me if I misunderstood anything, you need further help or my solution doesn't work for you.

Pressing Enter Key will Add the Selected Item From ListBox to RichTextBox

related to this topic:
Hidden ListBox will appear while Typing Words in RichTextBox
im working on a code editor and i just want to know if how can I add items from listbox to textbox using enterkey .
further more heres my strings:
public String[] ab = { "abstract" };
public String[] am = { "AmbientProperties", "AmbientValueAttribute" };
sample:
in richtextbox (rtb) , i type Ab, then hiddenlistbox will appear with "abstract" text on it (already do that) using this code:
if (token == "letterA" || token.StartsWith("Ab") || token.StartsWith("ab"))
{
int length = line.Length - (index - start);
string commentText = rtb.Text.Substring(index, length);
rtb.SelectionStart = index;
rtb.SelectionLength = length;
lb.Visible = true;
KeyWord keywordsHint = new KeyWord();
foreach (string str in keywordsHint.ab)
{
lb.Items.Add(str);
}
break;
}
then after that after i press enterkey i want to add the abstract from listbox to the richtextbox .
RichTextBox declared as rtb and ListBox declared as lb
what should i do? thanks .
Certain controls do not recognize some keys when they are pressed in key down event.
For eg ListBox do not recognize if key pressed is Enter Key.
Please see remarks section in following link -
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(v=vs.110).aspx
one of the solution for your problem can be
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown(v=vs.110).aspx
implement PreviewKeyDown Event for your listbox for listbox to recognize your actions.
Here is sample code snippet -
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Do your task here :)
}
}
private void listBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
e.IsInputKey = true;
break;
}
}
You cannot directly type text to a listbox, so I created a example with textBox:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
this.richTextBox1.AppendText((sender as TextBox).Text);
e.Handled = true;
}
}
If you meant comboBox you can easily adjust this, replace line above:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
this.richTextBox1.AppendText((sender as ComboBox).Text);
e.Handled = true;
}
}
Copy selected listbox entries to rtf box:
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
foreach (string s in listBox1.SelectedItems)
{
this.richTextBox1.AppendText(s + Environment.NewLine);
}
e.Handled = true;
}
}

Categories

Resources