I am creating a Windows Form Application and I want to create a method to be able to pass in a specified text box from a _Click event. Such as below: My Method is AddTo() and I want to call from the 2 click events which have 2 separate text boxes. I want to be able to pass in the correct text box.
void AddTo(string ctrl)
{
int num= int.Parse(ctrl);
num++;
ctrl = num.ToString();
}
private void btnAddLevel_Click(object sender, EventArgs e)
{
AddTo(TextBox1.Text);
}
private void btnAddSecond_Click(object sender, EventArgs e)
{
AddTo(TextBox2.Text);
}
I am pretty new to C#, is this possible to do? Thanks in advance for any help.
UPDATE:
Here is the full code with the fix below
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
txtName.Text = "0";
}
void AddTo(ref TextBox tBox)
{
if (tBox.Text.Trim().Length > 0)
{
int num = 0;
//CHECK IF THE TEXT IS CONVERTIBLE TO NUMBER
if (int.TryParse(tBox.Text, out num))
{
num++;
tBox.Text = num.ToString();
}
}
}
private void btnAddUnit_Click(object sender, EventArgs e)
{
AddTo(ref txtName);
}
}
Use ref key word to retain data updates for passing objects.
Try below code:
//YOUR TEXTBOX IS A REFERNCE HERE. SO THAT THE UPDATES ARE RETAINED
void AddTo(ref TextBox tBox)
{
//VALIDATED YOUR TEXT BOX IF DATA EXISTS BEFORE UPDATING
if (tBox.Text.Trim().Length > 0 )
{
int num = 0;
//CHECK IF THE TEXT IS CONVERTIBLE TO NUMBER
if (int.TryParse(tBox.Text, out num))
{
num++;
tBox.Text = num.ToString();
}
}
}
While calling
//USE REF WHILE CALLING
AddTo(ref textBox1);//textbox object
Related
What do I have to put in the private void textbox to make a user enter a amount and that amount will be applied to where await Connection.SendToServerAsync(2700, 790); is now. so let's say a user enters 2000, 8 in the texbox, then the (2700,790) has to change to (2000, 8)
namespace Application
{
public partial class Form1 : ExtensionForm
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
int repeat = 5;
for (int i = 0; i <= repeat; i++)
{
await Connection.SendToServerAsync(2700, 790);
await Connection.SendToServerAsync(3745);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
I got this as a answer:
You can get the textbox value using TextBox.Text.
It comes as a string, so you have to convert to int. You can do that using one of the following:
Int.Parse
Convert.ToInt32
With the converted value you can just call the methods with the new values when the button is clicked.
Could anyone show me how it's done by copying my code?
you don't need a textBox1_TextChanged() event
a dirty way could be the following
private async void button1_Click(object sender, EventArgs e)
{
int repeat = 5;
for (int i = 0; i <= repeat; i++)
{
await Connection.SendToServerAsync(2700, Int32.Parse(textBox1.Text); // <--|use the integer value to which textBox1 value can be cast to
await Connection.SendToServerAsync(3745);
}
}
while a more robust way would check the possibility of actually casting the textBox1 value to an integer before going on:
private async void button1_Click(object sender, EventArgs e)
{
int repeat = 5;
int amount;
if (Int32.TryParse(textBox1.Text, out amount)) // <--| go on only if textBox1 input value can be cast into an integer
for (int i = 0; i <= repeat; i++)
{
await Connection.SendToServerAsync(2700, amount); // <--| use the "amount" integer value read from textBox1
await Connection.SendToServerAsync(3745);
}
}
I have TextBoxA and TextBoxB. What i want to do is , whenever i put a number (yes, both of the textboxes values are always integers) in TextBoxA , TextBoxB should "autocomplete" with value (100-TextBoxA). Same thing goes for TextBoxB. The sum of TextBoxA and TextBoxB should always be 100.
Here's what i've already tried:
static void TextBoxA_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-a).ToString();
TextBoxB.Text = text;
}
Static void TextBoxB_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-b).ToString();
TextBoxA.Text = text;
}
But it doesn't work.
Here's what you can try:
private void TextBoxA_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxA.Text, out num))
{
string text = (100 - num).ToString();
TextBoxB.Text = text;
}
}
private void TextBoxB_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxB.Text, out num))
{
string text = (100 - num).ToString();
TextBoxA.Text = text;
}
}
This will autocomplete on either TextBox on TextChanged Event.
First, i dont know why your event handlers are declared static.. its usually got to be :
private void TextBoxA_TextChanged(object sender, EventArgs e) { }
Secondly, you know if you have 2 textboxs, and each one triggers the other, you'll never go out of the TextChanged event.
To understand me more, here's an example :
1- You set TextBoxB.text = "1";2- TextBoxB.TextChanged triggers, it
sets TextBoxA.Text = "2"; 3- TextBoxA.TextChanged triggers, it sets
TextBoxB.Text = "1";
And it continues like this until i believe you'll get an Exception of memory.
EDIT : The opertator '-' works on numbers. You can't substract a number from a string. they have to be both numbers, so convert them first.
EDIT 2 :
Here's a code i wrote that works fine
private void textBox1_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox1.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox2.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox2.Text = m.ToString();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox2.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox1.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox1.Text = m.ToString();
}
}
Try this. This is a more efficient and elegant way I'd choose using lambda expressions, without repeating the method:
private void onChangeDoSum(object sender, EventArgs e,
TextBox substractNumber, TextBox sumNumber)
{
sumNumber.Text = (100 - Int32.Parse(substractNumber.Text)).ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox1, textBox2);
textBox2.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox2, textBox1);
}
Alternatively use Int32.TryParse to prevent unexpected results.
I think you can do something like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = (100 - Int32.Parse(textBox1.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Text = (100 - Int32.Parse(textBox2.Text)).ToString();
}
when I see that static word I think you have tried to create these method by yourself and you forgot to add
textBox1.TextChanged += textBox1_Changed;
// I saw other post where you wrote that it could raise exception and fall. Of course it can. You can use if condition like
textBox1.Text != null && textBox1.Text != ""
before value would be changed or TryParse() method
i have textbox on a windows form and i want to be insert only numbers in this textbox.i use the following c# code for that
private void ChildAge_TextChanged(object sender, EventArgs e)
{
int i;
if (!int.TryParse(ChildAge.Text, out i))
{
MessageBox.Show("Plaese enter a valid Age");
}
}
it is working, but the problem is that , after showing the Message, when i Backspace the content and text box become null, on that situation also this message box shows again.
Do a little test like bellow:
int i = 0;
if(!string.IsNullOrEmpty(ChildAge.Text) &&
!int.TryParse(ChildAge.Text, out i)
)
{
MessageBox.Show("Enter Valid Age");
}
Try Using Below. This works better.
bool m_BackPressed = false;
private void ChildAge_TextChanged(object sender, EventArgs e)
{
int i;
if (!m_BackPressed)
{
if (!int.TryParse(ChildAge.Text, out i))
{
MessageBox.Show("Plaese enter a valid Age");
}
}
}
private void ChildAge_KeyPress(object sender, KeyPressEventArgs e)
{
m_BackPressed = (e.KeyChar.Equals((char)Keys.Back)) ? true : false;
}
I made a simple application to add 2 numbers together but when I add two letters together or a invalid sign it crashes the program. How do I create a message box showing something saying "please put in a number" when someone inserts a letter
Here's my code:
public partial class frmAdd : Form
{
string first;
string second;
public frmAdd()
{
InitializeComponent();
}
private void btnFirst_Click(object sender, EventArgs e)
{
first = txtNumber.Text;
}
private void btnSecond_Click(object sender, EventArgs e)
{
second = txtNumber.Text;
}
private void btnResult_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(first);
int b = Convert.ToInt32(second);
int c = a + b;
txtResult.Text = c.ToString();
}
}
Use TryParse instead:
private void btnResult_Click(object sender, EventArgs e)
{
int a, b;
if (int.TryParse(first, out a) && int.TryParse(second, out b))
{
int c = a + b;
txtResult.Text = c.ToString();
}
else
{
MessageBox.Show("Invalid Input!");
}
}
Or perhaps a better method would be to trap the error when the user first inputs the data:
public partial class frmAdd : Form
{
int first; // changed to int
int second;
private void btnFirst_Click(object sender, EventArgs e)
{
if (!int.TryParse(txtNumber.Text, out this.first))
{
MessageBox.Show("Invalid Input!");
}
}
private void btnSecond_Click(object sender, EventArgs e)
{
if (!int.TryParse(txtNumber.Text, out this.second))
{
MessageBox.Show("Invalid Input!");
}
}
private void btnResult_Click(object sender, EventArgs e)
{
int c = first + second;
txtResult.Text = c.ToString();
}
}
You can use NumericUpDown control instead of TextBox - it will not allow user to input invalid data.
Or you can add validation to TextBox value after user entered something. Add ErrorProvider to your form. And subscribe to Validating event of txtNumber textbox. This event will occur when textbox loses focus. If entered text is not an integer, then error will be shown near texbox, and your button will not be clicked:
private void txtNumber_Validating(object sender, CancelEventArgs e)
{
int value;
if (!Int32.TryParse(txtNumber.Text, out value))
{
errorProvider1.SetError(txtNumber, "Value is not an integer");
return;
}
errorProvider1.SetError(txtNumber, "");
first = value; // it's better to save integer value than text
}
Validation looks like:
You can add a bit of validation to check if you can create an int from the string value passed in.
int.TryParse is a simple way of doing this.
And for the MessageBox you can just use the MessageBox calss
Example:
private void btnResult_Click(object sender, EventArgs e)
{
int a = 0;
int b = 0;
if (!int.TryParse(first, out a))
{
MessageBox.Show("first is not a number");
return;
}
if (!int.TryParse(second, out b))
{
MessageBox.Show("second is not a number");
return;
}
int c = a + b;
txtResult.Text = c.ToString();
}
Instead of using Convert.ToInt32(string), you might actually use Int32.tryParse(String, out int), as shown below:
int a, b;
a = Int32.tryParse(first, out a);
b = Int32.tryParse(second, out b);
If the conversion fails, the tryParse method will result in a zero. If it succeeds, it will give you the number which is to be found in the string.
Hope it helped you out, had to find this too in my first few days of C#.
This may seem like a dumb question. I have a textbox that can be used to add items to a checkedlistbox at runtime on a windows form. I'm using c#. It works perfectly fine at runtime. The item gets added and stuff, when the form is open. But, when I close and open the form again, I don't see the added item in the checkedlistbox list. Note, I don't use a datasource and don't want to. I wouldn't want to hardcode anything and would prefer to use a textbox input on the form as a variable to feed into the collections list. I couldn't figure out a way to expand my checkedlistbox options. Any assistance would be appreciated.
How are you opening the form? Is it something like:
FormName form = new FormName();
form.Show()
The only reason I can think that's happening is that you're instantiating a new form instance every time you show it, instead of reusing the same form.
Have your Form take a ref List<string> values as parameter. Then make this as BindingSource for the CheckedListBox.
Here is the code:
class MyForm : Form {
List<string> values;
BindingSource source;
public MyForm()
{
InitializeComponent();
}
public MyForm(ref List<string> values):this()
{
if (values == null)
values = new List<string>();
this.values = values;
checkedListBox1.DisplayMember = "Value";
checkedListBox1.ValueMember = "Value";
source = new BindingSource(this.values, null);
checkedListBox1.DataSource = source;
}
private void AddItemButton_Click(object sender, EventArgs e)
{
this.source.Add(textBox1.Text);
textBox1.Text = string.Empty;
}
}
private void frmMain_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Properties.Settings.Default.CheckedItems))
{
string[] checkedIndicies = Properties.Settings.Default.CheckedItems.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
for (int i1 = 0; i1 < checkedIndicies.Length; i1++)
{
int idx;
if ((int.TryParse(checkedIndicies[i1], out idx)) && (checkedListBox1.Items.Count >= (idx+1)))
{
checkedListBox1.SetItemChecked(idx, true);
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
textBox1.MaxLength = 15;
// Change all text entered to be lowercase.
textBox1.CharacterCasing = CharacterCasing.Lower;
if (checkedListBox1.Items.Contains(textBox1.Text) == false)
{
checkedListBox1.Items.Add(textBox1.Text, CheckState.Checked);
textBox1.Text = "";
MessageBox.Show("Added! Click Move to see List Box");
}
else
{
MessageBox.Show("Already There!");
textBox1.Text = "";
}
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
string idx = string.Empty;
for (int i1 = 0; i1 < checkedListBox1.CheckedIndices.Count; i1++)
idx += (string.IsNullOrEmpty(idx) ? string.Empty : ",") + Convert.ToString(checkedListBox1.CheckedIndices[i1]);
Properties.Settings.Default.CheckedItems = idx;
Properties.Settings.Default.Save();
}