I'm sending the contents of text boxes and checkboxes to my database via a WCF service.
So far, I have
fNameTxtBox.Text, - string
(DateTime) BirthDate.Value, - System.DateTime
toggle1.IsChecked, - bool
But what happens if the datatype is int?
Unfortunately the autocomplete does not help me as such, and of course it doesn't accept .Text as an ending.
Anybody able to lend a hand and let me know what this would be?
EDIT:
Here is my complete statement that I am trying to complete. I am looking for the ending for ownerTextBox which for which the method required it to be an int, when the source is a text box on a WP7 app:
private void addAccountBtn_Click(object sender, RoutedEventArgs e)
{
_ServiceClient.AddDriverAsync(fnameTxtBox.Text, snameTxtBox.Text, (DateTime)BirthDate.Value, phonemobNumBox.Text, toggle1.IsChecked, toggle2.IsChecked, toggle3.IsChecked, toggle4.IsChecked, toggle5.IsChecked, toggle6.IsChecked, toggle7.IsChecked, toggle8.IsChecked, toggle9.IsChecked, toggle10.IsChecked, toggle11.IsChecked, toggle12.IsChecked, toggle13.IsChecked, toggle14.IsChecked, toggle15.IsChecked, ownerTextBox.????);
}
ie replace the ???? with the correct ending, or reformat that part as such so that it works.
You need to perform validation on the client to ensure that an invalid value never gets sent to your service. You can do this by checking if the value is a integer, and display a message if its not. Only send the data to your service if it meets the validation criteria.
public void OnButtonClick(object sender, EventArgs e) {
int value;
bool isValid = int.TryParse(textBox.Text, out value);
if (isValid) {
// send to WCF
}
else {
// display a message
}
}
You will need to parse the value using the int class, e.g.
int.Parse(myTextBox.Text)
Note that int.Parse will throw an exception if the value cannot be represented as an integer, so you may want to perform appropriate validation or exception handling. Look into the TryParse family of methods.
You may find it useful to read up on Casting, Type Conversion, and Parsing.
Using the source-code you posted, you would change it to:
private void addAccountBtn_Click(object sender, RoutedEventArgs e)
{
_ServiceClient.AddDriverAsync(
fnameTxtBox.Text, <snip_lots_of_arguments>,
toggle15.IsChecked,
int.Parse(ownerTextBox.Text)); //I've only changed the very last bit here
}
Related
I have a simple application that reverses any text typed to it in another textbox. The catch is, you can modify either textbox and the changes will be (literally) reflected in the other.
I wrote this code, believing for it to cause problems.
private void realText_TextChanged(object sender, EventArgs e)
{
mirrorText.Text = mirror(realText.Text);
}
private void mirrorText_TextChanged(object sender, EventArgs e)
{
realText.Text = mirror(mirrorText.Text);
}
private string mirror(string text)
{
return new string(text.Reverse().ToArray()).Replace("\n\r", "\r\n");
}
I then tried it out, believing that it would cause an infinite loop (realText changes mirrorText, another event happens, mirrorText changes realText, etc). However, nothing except the intended behavior happened.
I'm of course happy about this, I could just leave it here. Or could I?
I'm quite sure the TextChanged event is supposed to be fired whenever Text is changed. Is this intended behavior of some error protection in the events, or was I just lucky? Can this code misbehave on another computer, with other build settings, etc? It can be easily fixed:
private void realText_TextChanged(object sender, EventArgs e)
{
if (realText.Focused)
{
mirrorText.Text = Mirror(realText.Text);
}
}
I'll probably do it anyway to be safe, but is it required to check this? (I'm not even going to ask if it's recommended.)
Per the comments, and as already answered, the TextChanged event is not getting raised when you set the Text property to the value it already has.
It's not clear whether this is something you can safely rely upon. It is a sensible optimisation, and I would be very surprised if future versions of .NET Framework drop it, but I cannot speak for older versions, nor for third-party implementations (Mono).
To be absolutely safe, I would not use the Focused check you put in your question. I would do exactly what the Text setter does now.
private void realText_TextChanged(object sender, EventArgs e)
{
var newMirrorText = Mirror(realText.Text);
if (mirrorText.Text != newMirrorText)
mirrorText.Text = newMirrorText;
}
This has the same advantage of preventing infinite recursion, but plays more nicely with other code you may put in your form that changes the text as a result of some other event.
The reason it doesn't cause a loop is that it checks whether the Text property actually changed, i.e. if the new value does not equal the old value. In your case the mirror function happens to reverse itself, which leads to the same text after two passes.
It's pretty easy to check.
First, replace both textbox controls with
class T : TextBox
{
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
}
}
}
Second, set the breakpoint on setter. Add these expressions to the Watch window:
Name
Text
value
Third, launch the app, copy '123' from somewhere and paste it to the first textbox. Here it goes:
1st break:
Name: "mirrorText"
Text: ""
value: "321"
2nd break:
Name: "realText"
Text: "123"
value: "123"
3rd... whoops, it does not breaks anymore. To detect why we had to go deeper. Look at referencesource: text box setter does nothing unusual, but TextBoxBase's one looks interesting:
set {
if (value != base.Text) { // Gotcha!
base.Text = value;
if (IsHandleCreated) {
// clear the modified flag
SendMessage(NativeMethods.EM_SETMODIFY, 0, 0);
}
}
}
So, as hvd already answered, the reason is the textbox does not raise TextChanged if old and new values are the same. I don't think the behavior will change, at least for winforms. But if you want more robust solution, here it is:
private void RunOnce(ref bool flag, Action callback)
{
if (!flag)
{
try
{
flag = true;
callback();
}
finally
{
flag = false;
}
}
}
private bool inMirror;
private void realText_TextChanged(object sender, EventArgs e)
{
RunOnce(ref inMirror, () =>
{
mirrorText.Text = mirror(realText.Text);
});
}
private void mirrorText_TextChanged(object sender, EventArgs e)
{
RunOnce(ref inMirror, () =>
{
realText.Text = mirror(mirrorText.Text);
});
}
private string mirror(string text)
{
return new string(text.Reverse().ToArray()).Replace("\n\r", "\r\n");
}
P.S. mirror() will fail on surrogate pairs. Here're some solutions.
If textbox has a Text, and we try to change it with the same Text, the TextChange event is not raising because new text is same as the previous.
In your code, the realText_TextChanged event reverses the text and changes the mirrorText with it.
The mirrorText_TextChanged event reverses the text and try to change the realText.
The realText has already this text and does not raises the realText_TextChanged event.
I'm C# with Compact Framework and I realized something weird today. I'm calling a method by an event that applies a set to an object and when I debug, it passes by this, but just performs after the last close bracket of the method. My example:
public string Loading
{
set { lblLoading.Text = value; }
}
private void btnAuth_Click(object sender, EventArgs e)
{
Loading = "Loading...";
_presenter.PerformAuth();
}
When I debug, it passes by my first statement, applies it, but doesn't change anything on the screen... Oh, until it do PerformAuth(). After it, so, then the label value is changed. Oh, the problem isn't just by it be synchronous. The same occurs when I try to do an asynchronous task:
private void btnAuth_Click(object sender, EventArgs e)
{
ASyncResult res = BeginInvoke(new Action(() =>Loading = "Loading..."));
EndInvoke(res);
_presenter.PerformAuth();
}
I think it might be a bug in thread and in C# design implementation. And also with direct set it is stubborn to me. As you can see in the image below:
I just want to set a text in a label, call a method and unset it in an event. Why does C# get it so complicated?
I have a method called BuyShares() that is supposed to take a value in a textbox and add another user input value to it. I would like to use a messagebox that sets off the method by the user clicking okay. The only problem is that I can't seem to call upon the method.
This is the method.
public void BuyShares(int anAmount)
{
int newShares;
newShares = GetInvestmentShare() - anAmount;
SetInvestmentShare(newShares);
}
And this is the messagebox I have set up
private void button1_Click(object sender, EventArgs e)
{
DialogResult result;
result = MessageBox.Show("Your transaction is complete", "Success", MessageBoxButtons.OK);
if(result==DialogResult.OK)
{
txtStockSharesTab3.Text=??????
}
This is a windows form application and the program has several different classes
Without giving away the answer because you probably want to learn something from this...
I'm guessing you want to get the amount of shares to buy from one textbox, then call BuyShares and finally update txtStockSharesTab3 to this value.
Your BuyShares method returns void meaning it won't return a value. Somewhere in that method is where you're going to update your txtStockSharesTab3 textbox. Is that exact method signature for BuyShares required?
I am trying to make sure that user uses at least 6 characters as a password in my program.
I know how to set maximum size by using MaxLength, but how I do this for the minimum length?
if (passwordTextBox.Text.Length < 6)
{
MessageBox.Show("Passwords must be at least 6 characters long.");
return /*false*/;
}
// Do some stuff...
return /*true*/;
If you are going to have multiple user interfaces where the user can enter their password (web, mobile, windows client, etc) or would provide a service for doing the same (web, wcf, etc), then I think your best option is to catch this type of error at the most common level to all of these platforms.
We generally implement business rules like this in the database (through stored procedures) so that we have one well-known location to check and change these rules.
If you are using a database that doesn't support stored procedures, then you could implement this functionality in the "business layer", or the set of code responsible for performing the business logic for your application.
Use the validating method on your password textbox to enforce length.
if (TextBox1.Text.Length < 6)
{
MessageBox.Show("password too short");
TextBox1.Focus();
}
Although competent_tech gives you my recommended approach, a primitive solution would be the following:
Drop a label on your form and give it an ErrorText.
Use the following code for your textbox KeyDown event:
protected override void OnLoad(object sender, EventArgs e)
{
base.OnLoad(sender, e);
txtPassword.KeyDown += OnPasswordKeydown;
}
protected void OnPasswordKeydown(object sender, KeyEventArgs e)
{
bool isValid = txtPassword.Text.Length < 6;
ErrorText.Visible = isValid;
AcceptButton.Visible = isValid;
}
I have a c# .net project and want an input text box for a date value. I want it to display a default value of mm/dd/yyyy and then allow users to enter valid dates.
I have tried using a masked text box but it doesn't like having the above format.
If i try and use //____ looks naff and so does 00/00/0000 and of course if you put in '0' like 03/11/2009 you get 3/11/29 because the 0's are deleted as part of the mask.
What is the best way to set up an input box like this, effectively with a mask, only allowing numbers, and validation (though at this point I am not so worried about that).
This seems so simple and isn't.
Try examining the the date in the OnChange event. Check the length of the text, adding / when appropriate.
Alternatively, see if the the DatePicker may be a better choice...
Why not try and use a plugin like the jQuery UI DatePicker?
http://docs.jquery.com/UI/Datepicker
They are lightweight, tested and saves work!
Assuming Windows Forms, the DateTimePicker is the tool for the job.
Here is an example with the MaskedTextBox, but since you say it doesn't work...
Another good try, if you're using DataBinding, if by instantiating a Binding (Binding for WPF) class and handling its Parse and Format events (these don't seem to exist in WPF, but there must be some way).
In short:
Binding b = new Binding("Text", BindingSourceInstance, "data.DateCreated");
b.Parse += new EventHandler(b_Parse);
b.Format += new EventHandler(b_Format);
private void b_Format(object sender, ConvertEventArgs e) {
if (e.DesiredType != typeof(DateTime)) return;
e.Value.ToString("dd/MM/yyyy");
// Or you may prefer some other variants:
// e.Value.ToShortDateString();
// e.Value.ToLongDateString();
// e.Value.ToString("dd/MM/yyyy", CultureInfo.CurrentCulture.DateTimeInfo.ShortDatePattern);
}
private void b_Parse(object sender, ConvertEventArgs e) {
// Choose whether you to handle perhaps bad input formats...
e.Value = DateTime.Parse(e.Value, CultureInfo.InvariantCulture); // The CultureInfo here may be whatever you choose.
}
Using masked text box for date is a headache, best to use DateTime.TryParseExact() with control validated event.
It will guarantee user input in correct format without too much coding, like in this example:
you need to use also a ToolTip to instruct the user to the correct input.
private void txtEntryDate_Validated(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtEntryDate.Text))
{
DateTime entryDate;
if (DateTime.TryParseExact(txtEntryDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out entryDate))
{
// further actions for validations
}
else
{
setTooltip(txtEntryDate, "txtEntryDate", "Invalid date format date must be formatted to dd/MM/yyyy");
txtEntryDate.Focus();
}
}
else
{
setTooltip(txtEntryDate, "txtEntryDate", "Please provide entry date in the format of dd/MM/yyyy");
txtEntryDate.Focus();
}
}
and the ToolTip class:
private void setTooltip(Control Ctrl, string CtrlCaption, string ToolTipMsg)
{
ToolTip tt1 = new ToolTip();
tt1.AutoPopDelay = 5000;
tt1.InitialDelay = 1000;
tt1.ReshowDelay = 500;
tt1.ShowAlways = false;
tt1.SetToolTip(Ctrl, CtrlCaption);
tt1.Show(ToolTipMsg, Ctrl,5000);
}