I have these two methods and I have to use them to modify the selected item in a ListBox and after editing it in the same txtBox I use for filling up the ListBox to get it back and replace It with the old one.
private void txtBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
List.Items.Add(Label.Content);
Label.Content = "";
txtBox.Text = "";
}
}
private void ButtonModify_Click(object sender, RoutedEventArgs e)
{
int index = List.SelectedIndex;
object item = List.SelectedItem;
txtBox.Text = (string)item;
txtBox_KeyUp(????????);
}
My intuition says I have to call the EventMethod I've use to fill the ListBox, but there are some parameter which I can't remove cause I need them in the txtBody_KeyUp(). So my question is what I have to write as an arguments to work or is there some other way for doing this?
You Can Use Below Code.
Text Box PreviewKeyDown Event
private int _tmpIndex = -1;
private void TextBox_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter || _tmpIndex == -1) return;
ListBox1.Items[_tmpIndex] = TextBox1.Text;
TextBox1.Text = "";
_tmpIndex = -1;
}
ListBox MouseDoubleClick Event
private void ListBox_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (ListBox1.SelectedIndex <= 0) return;
TextBox1.Text = ListBox1.SelectedItem.ToString();
_tmpIndex = ListBox1.SelectedIndex;
}
Have Fun
Related
i am making a windows form application in which i used a datagridview.
i want that when i write something in textbox in datagridview,than a messagebox appears containing the string i wrote..
ican't get my text in textchanged event..
all thing must be fired in textchanged event..
here is my code:-
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
TextBox tb = (TextBox)e.Control;
tb.TextChanged += new EventHandler(tb_TextChanged);
}
}
void tb_TextChanged(object sender, EventArgs e)
{
//listBox1.Visible = true;
//string firstChar = "";
//this.listBox1.Items.Clear();
//if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
string str = dataGridView1.CurrentRow.Cells["Column2"].Value.ToString();
if (str != "")
{
MessageBox.Show(str);
}
}
void tb_TextChanged(object sender, EventArgs e)
{
var enteredText = (sender as TextBox).Text
...
}
Showing MessageBox in TextChanged will be very annoying.
Instead you could try it in DataGridView.CellValidated event which is fired after validation of the cell is completed.
Sample code:
dataGridView1.CellValidated += new DataGridViewCellEventHandler(dataGridView1_CellValidated);
void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}
I have a ListBox that when an item is selected, it is shown in a label as well. However, when I want to remove the selected item, program breaks and shows a NullReferenceException.
My code:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = "Your Selected: " + listBox1.SelectedItem.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
label1.Text = "";
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
It may appear, that there's no selected item in the listbox, so you have to check for that:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = null == listBox1.SelectedItem
? ""
: "Your Selected: " + listBox1.SelectedItem.ToString();
}
private void button2_Click(object sender, EventArgs e) {
// Looks redundant, listBox1_SelectedIndexChanged will do
//label1.Text = "";
// Deselect item, but not remove it
if (listBox1.SelectedIndex >= 0)
listBox1.SelectedIndex = -1;
// In case you want to remove the item (not deselect) - comment out the code below
// if (listBox1.SelectedIndex >= 0)
// listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
Edit: as for counting listbox items, there's no event fo this in the current listbox implementation. So you have to do it manually:
if (listBox1.SelectedIndex >= 0) {
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
lbItemsCount.Text = listBox1.Items.Count.ToString();
}
Another way is to use click event of the list box , if we do not want to double click the one list box item for the deselection of another list items.
ex:
private void ListBox_Right_Click(strong textobject sender, EventArgs e)
{
Btn_Left.Enabled = ListBox_Right.SelectedIndex >= 0;
ListBox_Left.ClearSelected(); // to clear the list selection/highlight
Btn_Right.Enabled = false; // for my specification
}
}
private void ListBox_Left_Click(object sender, EventArgs e)
{
Btn_Right.Enabled = ListBox_Left.SelectedIndex >= 0;
ListBox_Right.ClearSelected(); //to clear the list selection/highlight
Btn_Left.Enabled = false;// for my specification
}
I have a DataGridView. I want its 1st column or any desired column (which has textboxes in it) to be NUMERIC ONLY. I am currently using this code:
private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)
{
TextBox itemID = e.Control as TextBox;
if (itemID != null)
{
itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
}
}
}
private void itemID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
This code works but the problem is that all the textboxes in all the columns are getting numeric only.
I figured it out myself :)
Just removed the previous events in the starting of the function which resolved my issue.
private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(itemID_KeyPress);//This line of code resolved my issue
if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)
{
TextBox itemID = e.Control as TextBox;
if (itemID != null)
{
itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
}
}
}
private void itemID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You can add in a List all the numeric cells index.
Like this:
List<int> list_numeric_columns = new List<int>{ dataGridViewItems.Columns["itemID"].Index};
You add all the columns you need there.
Then, instead of doing this:
if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)
You do this:
if (list_numeric_columns.Contains(dataGridViewItems.CurrentCell.ColumnIndex))
That should work. You will have to add the columns just once..
Hope thats helps
This is how to use EditingControlShowing with TextBox → Keypress Event
private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var itemID = e.Control as TextBox;
if (dataGridViewItems.CurrentCell.ColumnIndex == 1) //Where the ColumnIndex of your "itemID"
{
if (itemID != null)
{
itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
itemID.KeyPress -= new KeyPressEventHandler(itemID_KeyPress);
}
}
}
private void itemID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
e.Handled = true;
}
Click the textbox that you want to be numeric only then in the properties click the "events" (looks like thunder) then look for the "keypress" then double click then type this:
if (char.IsNumber(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
This is the code I currently have:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) && e.KeyChar != '.';
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) e.Handled = true;
}
KeyPress isn't good enough to do this kind of validation. A simple way to bypass it is to paste text into the text box with Ctrl+V. Or the context menu, no key event at all.
In this specific case, the TextChanged event will get the job done:
private void textBox_TextChanged(object sender, EventArgs e) {
var box = (TextBox)sender;
if (box.Text.StartsWith(".")) box.Text = "";
}
But there's a lot more to validating numeric values. You also need to reject stuff like 1.1.1 or 1.-2 etcetera. Use the Validating event instead. Drop an ErrorProvider on the form and implement the event like this:
private void textBox_Validating(object sender, CancelEventArgs e) {
var box = (TextBox)sender;
decimal value;
if (decimal.TryParse(box.Text, out value)) errorProvider1.SetError(box, "");
else {
e.Cancel = true;
box.SelectAll();
errorProvider1.SetError(box, "Invalid number");
}
}
You probably want to use the TextChanged event, since the user could paste in values. For the best experience given the requirements, I'd suggest simply removing any leading . characters.
void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.StartsWith("."))
{
textBox1.Text = new string(textBox1.Text.SkipWhile(c => c == '.').ToArray());
}
}
This does not address a requirement to use only digits -- wasn't clear in the question if that is the case.
This works for copy and pasting too.
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
int decimalCount=0;
string rebuildText="";
for(int i=0; i<textBox1.Text.Length; i++)
{
if (textBox1.Text[i] == '.')
{
if (i == 0) break;
if (decimalCount == 0)
rebuildText += textBox1.Text[i];
decimalCount++;
}
else if ("0123456789".Contains(textBox1.Text[i]))
rebuildText += textBox1.Text[i];
}
textBox1.Text = rebuildText;
textBox1.SelectionStart = textBox1.Text.Length;
}
You can try this:
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox.Text = TextBox.Text.TrimStart('.');
}
I have magnetic card reader, It emulates Keyboard typing when user swipes card. I need to handle this keyboard typing to one string, when my WPF window is Focused. I can get this typed Key list, but I don't know how to convert them to one string.
private void Window_KeyDown(object sender, KeyEventArgs e)
{
list.Add(e.Key);
}
EDIT: Simple .ToString() method not helps. I've tried this already.
Rather than adding to a list why not build up the string:
private string input;
private bool shiftPressed;
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
{
shiftPressed = true;
}
else
{
if (e.Key >= Key.D0 && e.Key <= Key.D9)
{
// Number keys pressed so need to so special processing
// also check if shift pressed
}
else
{
input += e.Key.ToString();
}
}
}
private void Window_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
{
shiftPressed = false;
}
}
Obviously you need to reset input to string.Empty when you start the next transaction.
...or you can try this:
string stringResult = "";
list.ForEach(x=>stringResult+=x.ToString());
EDIT:
After good Timur comment I decided to suggest this:
you can use keyPress event to everything like this:
string stringResult = "";
private void Window_KeyPress(object sender, KeyPressEventArgs e)
{
stringResult += e.KeyChar;
}
Listen To PreviewTextInput Event Instead ...
the TextCompositionEventArgs has a property called "Text" which give you the text representation for key
for example Key.D2 will be just "2" ...i think it will
do the purpose
private void MainWindow_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
list.Add(e.Text);
}
You could have a member variable which is a StringBuilder.
something like
class A
{
StringBuilder _contents = new StringBuilder();
private void Window_KeyDown(object sender, KeyEventArgs e)
{
_contents.Append(e.Key.ToString());
}
}
You would have to create a new StringBuilder each time a new card was swiped and then to get the string you would use _contents.ToString();
String combined = String.Empty;
private void Window_KeyDown(object sender, KeyEventArgs e)
{
combined = combined + e.Key.ToString();
}