How should I attach event to value changed - c#

I want to have the abilitiy to add numeric fields using an event as i have over 50 i dont fancy adding event to each one is there a better way of doing the following. Also I cant seem to get sumEarnings to be reconized by the compiler does anybody have any suggestions.
protected void Page_Load(object sender, EventArgs e)
{
wagesnET.ValueChanged += sumEarnings();
}
protected void btnSave_Click(object sender, EventArgs e)
{
StringDictionary KeyValue = new StringDictionary();
KeyValue.Add("", "");
foreach (string key in Request.Form)
{
if (!key.StartsWith("checkbox")) continue;
}
}
private void sumEarnings(object sender, EventArgs e)
{
int total = Convert.ToInt16(wagesnET.Text) + Convert.ToInt16(partnerearningscic.Text);
return total;
}

sumEarnings is a method without return type, change it as
private int sumEarnings()
{
return Convert.ToInt16(wagesnET.Text) + Convert.ToInt16(partnerearningscic.Text);
}
To attach it to multiple controls from the code you can use enumerator. For example:
foreach (Control c in this.Controls)
{
//if (c is TextBox)
c.ValueChanged += sumEarnings();
}

You need to remove the () from the event handler assignment:
wagesnET.ValueChanged += sumEarnings;
After you calculate the new total value udpate the appropriate control:
private void sumEarnings(object sender, EventArgs e)
{
int total = Convert.ToInt16(wagesnET.Text) + Convert.ToInt16(partnerearningscic.Text);
// todo: update the total value...
}
It's not possible to have an event handler that return a value at the same time.

Related

Condensing lots of Button Click Events

I have 40 buttons that all do something slightly different when clicked, I would like to condense this down if I can. I also want to say, if one of the buttons is clicked, create a timestamp which can be accessed by the class.
Here is the code for 2 out of 40 of the buttons:
private void Btn1_Click(object sender, RoutedEventArgs e)
{
for (int i = 1; i < 5; i++)
{
CheckBox CheckBox = (this.FindName(string.Format("Check{0}", i)) as CheckBox);
if (CheckBox != null)
{
CheckBox.IsChecked = true;
}
}
}
private void BtnDisable1_Click(object sender, RoutedEventArgs e)
{
for (int i = 1; i < 5; i++)
{
CheckBox CheckBox1 = (this.FindName(string.Format("Check_D{0}", i)) as CheckBox);
if (CheckBox1 != null)
{
CheckBox1.IsChecked = false;
}
}
}
I think one way of doing it is putting it in an array and whenever one of the 40 buttons are clicked it looks in the array on what to do next? I'm not really sure, thank you!
You can make this simple using one method.
Answer is updated based on this discussion
private void DoWork(int checkboxGroup, bool enable)
{
int start = checkboxGroup * 4;
for (int i = start; i < start + 4; i++)
{
CheckBox CheckBox = this.FindName("CheckBox" + i) as CheckBox;
if (CheckBox != null)
{
CheckBox.IsChecked = enable;
}
}
}
private void Btn1_Click(object sender, RoutedEventArgs e)
{
DoWork(1 , true);
}
private void BtnDisable1_Click(object sender, RoutedEventArgs e)
{
DoWork(1 , false);
}
Because there are 40 methods like this you can use Expression bodied methods. You must have C#6 to use this feature.
private void Btn1_Click(object sender, RoutedEventArgs e) => DoWork(1 , true);
private void BtnDisable1_Click(object sender, RoutedEventArgs e) => DoWork(1 , false);
private void Btn2_Click(object sender, RoutedEventArgs e) => DoWork(2, true);
private void BtnDisable2_Click(object sender, RoutedEventArgs e) => DoWork(2, false);
// and so on

Creating a Total of subtotals

Hi im trying to create this program where the txtbox1 will multiply on user's input and automatically shows the total in decimal point same as in other txtboxes, but i'm having a trouble to sum up all the subtotals of every result to overall txtbox total
here is my code in every subtotals
private void txtbox11_TextChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtbox12.Text))
txtTotal11.Text =
(Convert.ToInt32(txtbox11.Text)*Convert.ToDecimal(112.61)).ToString();
}
private void txtbox12_TextChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtbox12.Text))
txtTotal12.Text =
(Convert.ToInt32(txtbox12.Text) * Convert.ToDecimal(32.10)).ToString();
}
How do i automatically get the sum of txtTotal11 & txtTotal12 to display on txtTotal13?
or should i put an event like "textChanged" on every txtTotal# too?
thanks guys i'm really having a headache on this.
It will be something like:
private void txtboxSubTotal1_TextChanged_1(object sender, EventArgs e)
{
CalcGrandTotal();
}
private void txtboxSubTotal2_TextChanged_1(object sender, EventArgs e)
{
CalcGrandTotal();
}
private void CalcGrandTotal()
{
decimal grandTotal = 0;
decimal parseValue= 0;
if (!string.IsNullOrEmpty(txtboxSubTotal1.Text) && decimal.TryParse(txtboxSubTotal1.Text, parseValue))
grandTotal += parseValue;
if (!string.IsNullOrEmpty(txtboxSubTotal2.Text) && decimal.TryParse(txtboxSubTotal2.Text, parseValue))
grandTotal += parseValue;
txtboxGrandTotal.Text = grandTotal.ToString();
}
Try this: (in every TextChanged event)
decimal total13;
private void txtbox11_TextChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtbox12.Text))
var thisTotal = (Convert.ToInt32(txtbox11.Text)*Convert.ToDecimal(112.61)).ToString();
txtTotal11.Text = thisTotal
total13 += thisTotal
txtTotal13.Text = thisTotal.ToString();
}

textchanged event calling custom method but custom method reports textbox text is empty

I've not touched C# in some time, was trying to help a new programmer friend of mine and became utterly stumped by the following:
private void textBox1_TextChanged(object sender, EventArgs e)
{
activateEnterButton();
TextBox t = (TextBox)sender;
string theText = t.Text;
MessageBox.Show("text: " +theText);
}
private void activateEnterButton()
{
bool allGood = true;
foreach (Control control in Controls )
{
if (control is TextBox)
{
string test = ((TextBox)control).Text;
if (test.Length == 0)
{
MessageBox.Show("text: " +test);
allGood = false;
break;
}
}
}
btnEnter.Enabled = allGood;
}
Our goals is utterly simple: We have 5 textboxes and each needs to have some text in them before a button is enabled. When each has text, button is enabled.
When I walk through the code while debugging everything is called okay but no matter how much text I put in the textbox the activateEnterButton never knows it's there. The two MessageBoxes show different output as well: the one in the activateEnterButton never has any, the one in the event handler always does.
Any assistance would be greatly appreciated. Thank you.
I have removed the calls to the activateEnterButton(), I have put guts of that code inside the event handler for textBox5 but the button is still not being enabled.
The answer I accepted didn't give me the functionality I wanted (entering data into textbox5 would make the button active)the following code gave me all the functionality I wanted. And lastly, the reason for my errors were because A) foreach iterates from the last control to the first, and B) the last textbox control I have on the form is a ReadOnly textbox control, its text is always "", hence I was always getting dumped out of my earlier code. At any rate, new code:
private void checkMe()
{
bool allGood = true;
foreach (Control control in Controls)
{
// Make sure the ReadOnly textbox doesn't cause false
if (control.Name.Equals("ReadOnlyTextBox"))
{
// MessageBox.Show("hidden textbox: " + ((TextBox)control).Text);
allGood = true;
}
else if (control is TextBox)
{
string test = ((TextBox)control).Text;
//MessageBox.Show("test: " + test);
if (test.Length < 1)
{
allGood = false;
// MessageBox.Show("All textboxes need input");
break;
}
else
{
allGood = true;
}
}
}
btnEnter.Enabled = allGood;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
checkMe();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
checkMe();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
checkMe();
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
checkMe();
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
checkMe();
}
In your activateEnterButton() method you looping through the controls and if control is textbox; checking whether it has text or not.
Say if textbox1 has fired the textchanged event; how does that guarantee that other textbox has text in it?
You said in your post The two MessageBoxes show different output as well: .. that should be.
say textbox1 have fired textchanged event and so does in textchanged event you have the text displayed in messagebox but in method activateEnterButton() where you are looping through all controls in form there is no guarantee of order like textbox1 .. 5 (in that order loop will check them) and you are breaking out pf loop once it has no text. So does, in your method you don't see any text in messagebox.
Best way of doing it would be as below (consider that you have TextBox 1..5; have the textchanged on TextBox5 only.)
private void textBox5_TextChanged(object sender, EventArgs e)
{
bool allGood = false;
foreach (Control control in Controls )
{
if (control is TextBox)
{
string test = ((TextBox)control).Text;
if (test.Length > 0)
{
allGood = true;
}
else
{
MessageBox.Show("Fill all textbox first");
break;
}
}
}
btnEnter.Enabled = allGood;
}
Hope this helps.

To get total marks into a textbox

My code is:
protected void txttotal_TextChanged(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtmaths.Text);
int b = Convert.ToInt32(txtsci.Text);
int c = Convert.ToInt32(txtenglish.Text);
int tot = a + b + c;
txttotal.Text = Convert.ToString(tot);
}
I am trying get the total marks to a textbox, but it is not working.Can you help me please?
You are trying to change the text in the same textbox that the text is changing, are you sure this is what you want to do?
Wouldn't you want to change the Total when the maths,sci and english values change? if so look at the following.
protected void txtmaths_TextChanged(object sender, EventArgs e)
{
UpdateTotals();
}
protected void txtsci_TextChanged(object sender, EventArgs e)
{
UpdateTotals();
}
protected void txtenglish_TextChanged(object sender, EventArgs e)
{
UpdateTotals();
}
protected void UpdateTotals()
{
int a = Convert.ToInt32(txtmaths.Text);
int b = Convert.ToInt32(txtsci.Text);
int c = Convert.ToInt32(txtenglish.Text);
int tot = a + b + c;
txttotal.Text = tot.ToString();
}
It looks like this method is the even handler for the TextChanged event of txttotal. I am guessing on "not working" here: You might run into a loop if you change a control in the handler to its changed-event.
You might want to check if you are hitting the handler because of a changed done by the handler.
Problem : there is no problem with the code but it looks you are writing your code inside total textbox TextChanged event handler, so who will raise the total textbox TextChanged event.
Solution : So you need to have some Button like Sumbit and you need to move the above code into Submit button click event handler as below:
protected void btnSubmit_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtmaths.Text);
int b = Convert.ToInt32(txtsci.Text);
int c = Convert.ToInt32(txtenglish.Text);
int tot = a + b + c;
txttotal.Text = Convert.ToString(tot);
}
You have the code to update txtTotal in txtTotal_TextChanged event. You need to put the code you have in some method and call it on change of txtmaths, txtsci, txtenglish instead of txttotal_TextChanged
protected void UpdateTotal()
{
txttotal.Text = Convert.ToInt32(txtmaths.Text) + Convert.ToInt32(txtsci.Text) + Convert.ToInt32(txtenglish.Text);
}
protected void txtmaths_TextChanged(object sender, EventArgs e)
{
UpdateTotal();
}
I can see this erroring due to type exceptions.
This is a safer way of doing this with less potential errors:
protected void txttotal_TextChanged(object sender, EventArgs e)
{
int a = 0;
int b = 0;
int c = 0;
if (!Int32.TryParse(txtmaths.Text, ref a))
// handle error...
if (!Int32.TryParse(txtsci.Text, ref b))
// handle error...
if (!Int32.TryParse(txtenglish.Text, ref c))
// handle error...
int tot = a + b + c;
txttotal.Text = Convert.ToString(tot);
}

Auto highlight text in a textbox control

How do you auto highlight text in a textbox control when the control gains focus.
In Windows Forms and WPF:
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
If you want to do it for your whole WPF application you can do the following:
- In the file App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
//works for tab into textbox
EventManager.RegisterClassHandler(typeof(TextBox),
TextBox.GotFocusEvent,
new RoutedEventHandler(TextBox_GotFocus));
//works for click textbox
EventManager.RegisterClassHandler(typeof(Window),
Window.GotMouseCaptureEvent,
new RoutedEventHandler(Window_MouseCapture));
base.OnStartup(e);
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
(sender as TextBox).SelectAll();
}
private void Window_MouseCapture(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}
In ASP.NET:
textbox.Attributes.Add("onfocus","this.select();");
It is very easy to achieve with built in method SelectAll
Simply cou can write this:
txtTextBox.Focus();
txtTextBox.SelectAll();
And everything in textBox will be selected :)
If your intention is to get the text in the textbox highlighted on a mouse click you can make it simple by adding:
this.textBox1.Click += new System.EventHandler(textBox1_Click);
in:
partial class Form1
{
private void InitializeComponent()
{
}
}
where textBox1 is the name of the relevant textbox located in Form1
And then create the method definition:
void textBox1_Click(object sender, System.EventArgs e)
{
textBox1.SelectAll();
}
in:
public partial class Form1 : Form
{
}
I think the easiest way is using TextBox.SelectAll like in an Enter event:
private void TextBox_Enter(object sender, EventArgs e)
{
((TextBox)sender).SelectAll();
}
Here's the code I've been using. It requires adding the attached property to each textbox you wish to auto select. Seeing as I don't want every textbox in my application to do this, this was the best solution to me.
public class AutoSelectAll
{
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
static void ue_Loaded(object sender, RoutedEventArgs e)
{
var ue = sender as FrameworkElement;
if (ue == null)
return;
ue.GotFocus += ue_GotFocus;
ue.GotMouseCapture += ue_GotMouseCapture;
}
private static void ue_Unloaded(object sender, RoutedEventArgs e)
{
var ue = sender as FrameworkElement;
if (ue == null)
return;
//ue.Unloaded -= ue_Unloaded;
ue.GotFocus -= ue_GotFocus;
ue.GotMouseCapture -= ue_GotMouseCapture;
}
static void ue_GotFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox)
{
(sender as TextBox).SelectAll();
}
e.Handled = true;
}
static void ue_GotMouseCapture(object sender, MouseEventArgs e)
{
if (sender is TextBox)
{
(sender as TextBox).SelectAll();
}
e.Handled = true;
}
public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
typeof(AutoSelectAll), new UIPropertyMetadata(false, IsEnabledChanged));
static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ue = d as FrameworkElement;
if (ue == null)
return;
if ((bool)e.NewValue)
{
ue.Unloaded += ue_Unloaded;
ue.Loaded += ue_Loaded;
}
}
}
The main change I made here was adding a loaded event to many of the examples I've seen. This allows the code to continue working after it's unloaded (ie. a tab is changed). Also I included code to make sure the text gets selected if you click on the textbox with the mouse, and not just keyboard focus it. Note: If you actually click on the text in the textbox, the cursor is inserted between the letters as it should.
You can use this by including the following tag in your xaml.
<TextBox
Text="{Binding Property}"
Library:AutoSelectAll.IsEnabled="True" />
If you need to do this for a large number of textboxes (in Silverlight or WPF), then you can use the technique used in the blog post: http://dnchannel.blogspot.com/2010/01/silverlight-3-auto-select-text-in.html. It uses Attached Properties and Routed Events.
You can use this, pithy. :D
TextBox1.Focus();
TextBox1.Select(0, TextBox1.Text.Length);
If you wanted to only select all the text when the user first clicks in the box, and then let them click in the middle of the text if they want, this is the code I ended up using.
Just handling the FocusEnter event doesn't work, because the Click event comes afterwards, and overrides the selection if you SelectAll() in the Focus event.
private bool isFirstTimeEntering;
private void textBox_Enter(object sender, EventArgs e)
{
isFirstTimeEntering = true;
}
private void textBox_Click(object sender, EventArgs e)
{
switch (isFirstTimeEntering)
{
case true:
isFirstTimeEntering = false;
break;
case false:
return;
}
textBox.SelectAll();
textBox.SelectionStart = 0;
textBox.SelectionLength = textBox.Text.Length;
}
if you want to select all on "On_Enter Event" this won't Help you achieving your goal.
Try using "On_Click Event"
private void textBox_Click(object sender, EventArgs e)
{
textBox.Focus();
textBox.SelectAll();
}
On events "Enter" (for example: press Tab key) or "First Click" all text will be selected. dotNET 4.0
public static class TbHelper
{
// Method for use
public static void SelectAllTextOnEnter(TextBox Tb)
{
Tb.Enter += new EventHandler(Tb_Enter);
Tb.Click += new EventHandler(Tb_Click);
}
private static TextBox LastTb;
private static void Tb_Enter(object sender, EventArgs e)
{
var Tb = (TextBox)sender;
Tb.SelectAll();
LastTb = Tb;
}
private static void Tb_Click(object sender, EventArgs e)
{
var Tb = (TextBox)sender;
if (LastTb == Tb)
{
Tb.SelectAll();
LastTb = null;
}
}
}
I don't know why nobody mentioned that but you can also do this, it works for me
textbox.Select(0, textbox.Text.Length)
textBoxX1.Focus();
this.ActiveControl = textBoxX1;
textBoxX1.SelectAll();
In window form c#. If you use Enter event it will not work. try to use MouseUp event
bool FlagEntered;
private void textBox1_MouseUp(object sender, MouseEventArgs e)
{
if ((sender as TextBox).SelectedText == "" && !FlagEntered)
{
(sender as TextBox).SelectAll();
FlagEntered = true;
}
}
private void textBox1_Leave(object sender, EventArgs e)
{
FlagEntered = false;
}
textbox.Focus();
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;

Categories

Resources