I have a textbox in a Windows form, I have clear button which basically clears the text char by char(that is one by one not all at once), my problem is i want to add another textbox to this form and would like to control both the textboxes with clear button meaning the clear should only clear the textbox which i have selected or clicked on, i tried doing it but either i am able to clear both the textboxes simultaneously or clear only textbox my code for single textbox is
private void clearBtn_Click(object sender, EventArgs e)
{
string s = txtID.Text;
if (s.Length > 0) txtID.Text = s.Substring(0, s.Length - 1);
}
You can set the which control has focus upon focus and then use that to see which one needs to be removed.
private Textbox SelectedTextBox;
protected void Form_Load(object sender, EventArgs e)
{
TextBox1.GotFocus += TextBox_GotFocus;
TextBox2.GotFocus += TextBox_GotFocus;
}
private void clearBtn_Click(object sender, EventArgs e)
{
if(this.SelectedTextBox == null) return;
string s = this.SelectedTextBox.Text;
if (s.Length > 0) this.SelectedTextBox.Text = s.Substring(0, s.Length - 1);
}
private void TextBox_GotFocus(object sender, EventArgs e)
{
this.SelectedTextBox = (Textbox)sender;
}
private void clearBtn_Click(object sender, EventArgs e)
{
sting textbox1text = textbox1.tostring();
string textbox2text = textbox2.tostring();
if (textbox1text.length > 0){
textbox1text = textbox1text.Remove(textbox1text.length - 1)
}
if (textbox2text.length > 0){
textbox2text = textbox2text.Remove(textbox1text.length - 1)
}
}
that will "backspace" one character of each textbox.
if you want to do a clear on the one you last updated textbox, add this to each if statement
if (textbox2text.length > 0 && textbox2text == textbox2text)
that will check if the textbox was updated before it clears, it wont clear if it hasnt been updated
Related
When i click on a button,text will appear in textbox1 but then i want it to change focus to another textbox(textbox2) and when i click the same button again,display the same text but in textbox2.
private void btna_Click(object sender, EventArgs e)
{
textBox1.Text = ("A");
if (textBox1.Text.Length > 0)
{
textBox2.Focus();
}
If you want to alternate between different TextBoxes in your click event to determine which one to update, you can track them in a private variable, and then just switch which one you're using based on the current value, for example:
private TextBox textBoxToUpdate = null;
private void button1_Click(object sender, EventArgs e)
{
// Swap the textBoxToUpdate between textBox1 and textBox2 each time
textBoxToUpdate = (textBoxToUpdate == textBox1) ? textBox2 : textBox1;
textBoxToUpdate.Text = "A";
}
Another way to do this if you're updating multiple controls is to store them in a list and increment an integer that defines the index to the next item.
// holds the text boxes we want to rotate between
private List<TextBox> textBoxesToUpdate = new List<TextBox>();
private void Form1_Load(object sender, System.EventArgs e)
{
// add some text boxes to our list
textBoxesToUpdate.Add(textBox1);
textBoxesToUpdate.Add(textBox2);
textBoxesToUpdate.Add(textBox3);
textBoxesToUpdate.Add(textBox4);
}
// stores the index of the next textBox to update
private int textBoxToUpdateIndex = 0;
private void button1_Click(object sender, EventArgs e)
{
textBoxesToUpdate[textBoxToUpdateIndex].Text = "A";
// increment the index but set it back to zero if it's equal to the count
if(++textBoxToUpdateIndex == textBoxesToUpdate.Count) textBoxToUpdateIndex = 0;
}
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 got few textboxes in my form. I would like to type in one textbox and the other textboxes will be automatically canceled (Canceled so the user wont be able to type anymore in the other textboxes).
If the user delete the word he typed in the textbox (or in other words: if the textbox is empty) all other textboxes will be enabled again.
Here is what I got so far:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 0)
{
// Disable other textboxes (I have no idea how can I do that).
}
else if (textBox1.Text.Trim().Length == 0)
{
// Enable other textboxes
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 0)
{
// Keep this comboBox enabled while typing in textBox1.
}
}
How can I disable other textboxes while typing in priticillar textbox? (also keeping comboBox enabled).
DO NOTICE: I would like to do the same on textBox2 (when I type in textBox2, textbox 1 and 3 will be disabled) and textBox3.
You don't need a condition on your 'else if', just 'else' will do, as if the length is more than 0, the only other possibility is 0. Also you can use the sender instead of hardcoding the control name.
Then set the Enabled property for the textbox's you want disabled. You can loop through all the textbox's on the form, excluding the one you are typing into, or just manually list them. SImpler is putting the textbox's in a groupbox, then if you disable the groupbox it will disable the controls with in it.
private void textBox1_TextChanged(object sender, EventArgs e)
{
var senderTextBox = (TextBox)sender;
var textBoxesEnabled = senderTextBox.Text.Trim().Length == 0;
textBox2.Enabled = textBoxesEnabled;
textBox3.Enabled = textBoxesEnabled;
// OR
groupBox1.Enabled = textBoxesEnabled;
}
REPLY EDIT: You can chain of textbox's, say 4 of them, disable the last 3, then:
void TextBox1TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox2.Enabled = !isTextEmpty;
}
void TextBox2TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox1.Enabled = isTextEmpty;
textBox3.Enabled = !isTextEmpty;
}
void TextBox3TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox2.Enabled = isTextEmpty;
textBox4.Enabled = !isTextEmpty;
}
void TextBox4TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox3.Enabled = isTextEmpty;
}
But for a large amount of textbox's, another alternative is having multiple textbox share the same TextChanged event. You need to click on each TextBox control, go into the Events list and manually select the method for TextChanged. Here is the method:
private void TextBoxGroup_TextChanged(object sender, EventArgs e)
{
var groupOrder = new List<TextBox>() { textBox1, textBox2, textBox3, textBox4 };
var senderTextBox = (TextBox)sender;
var senderIndex = groupOrder.IndexOf(senderTextBox);
var isTextEmpty = senderTextBox.Text.Trim() == "";
if (senderIndex != 0) groupOrder[senderIndex - 1].Enabled = isTextEmpty;
if (senderIndex != groupOrder.Count - 1) groupOrder[senderIndex + 1].Enabled = !isTextEmpty;
}
Use Controls collection and some LINQ:
if (textBox1.Text.Trim().Length > 0)
{
var textboxes = this.Controls.OfType<TextBox>().Where(x => x.Name != "textBox1");
foreach(var tBox in textboxes)
tBox.Enabled = false;
}
int selectedRowIndex = 0;
private void listViewUserList_SelectedIndexChanged(object sender, EventArgs e)
{
if(listViewUserList.SelectedIndices.Count == 0)
return;
}
private void Form_Load(object sender, EventArgs e)
{
if(listViewUserList.Items.Count > 0)
{
listViewUserList.Items[selectedRowIndex].Selected = true;
listViewUserList.Select();
}
}
On form load I'm selecting first row in ListView. But when I select blank row it deselect items from ListView.
What should I do when click on blank row then select previously selected row? I have searched on Google but didn't find any good answers. Answers on stackoverflow only for WPF not for windows form.
This can be done by adding an event handler for the ListView's MouseUp event. If you still need the event handler for the SelectedIndexChanged and it's delegate method, listViewUserList_SelectedIndexChanged, remove from it any code that handles the item selection:
private void listViewUserList_SelectedIndexChanged(object sender, EventArgs e)
{
// remove the 2 lines below, as the selection handling is done in the
// MouseUp event handler
//if(listViewUserList.SelectedIndices.Count == 0)
// return;
// TODO: get the column data
}
Add the following event handler:
listViewUserList.MouseUp += new MouseEventHandler(this.listViewUserList_MouseUp);
and the following method:
private void listViewUserList_MouseUp(object sender, MouseEventArgs e)
{
if (listViewUserList.SelectedItems.Count > 0)
{
selectedRowIndex = listViewUserList.SelectedItems[0].Index;
}
else
{
listViewUserList.Items[selectedRowIndex].Selected = true;
}
}
Save the previous index in the class.
If current index points to an empty string, change the selection back to previous selection using (1)
Then call myListView.Select();
Code:
private void Form_Load(object sender, EventArgs e)
{
if(listViewUserList.Items.Count > 0 && (String.Empty != listViewUserList.Items[selectedRowIndex].ToString() ))
{
listViewUserList.Items[selectedRowIndex].Selected = true;
listViewUserList.Select();
}
}
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('.');
}