The text of my textboxes is not changing (info inside) - c#

I'm building a voice controlled application, and i want to set the text of the textboxes when the user speaks his username and password, however this is not happening, but if i display the string that is recognized using a message
public Form1()
{
InitializeComponent();
GrammarBuilder g = new Choices("wissam.h44", "jordan_6");
Grammar g1 = new Grammar(g);
Grammar g2 = new Grammar(g);
InitializeComponent();
this.Shown += new System.EventHandler(this.Form1_Shown);
Recognizer1.LoadGrammar(g1);
Recognizer2.LoadGrammar(g2);
}
private void Form1_Shown(Object sender, EventArgs e)
{
Synthesizer1.Speak("Application is loaded.");
Synthesizer1.Speak("Please Enter Your Email: ");
Recognizer1.SpeechRecognized +=
new EventHandler<SpeechRecognizedEventArgs>(recognizer1_SpeechRecognized);
Recognizer1.SetInputToDefaultAudioDevice();
Recognizer1.Recognize();
Synthesizer1.Speak("Please Enter Your Password: ");
Recognizer2.SpeechRecognized +=
new EventHandler<SpeechRecognizedEventArgs>(recognizer2_SpeechRecognized);
Recognizer2.SetInputToDefaultAudioDevice();
Recognizer2.Recognize();
}
void recognizer1_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string eml = e.Result.Text;
txtemail.Text = eml;
}
void recognizer2_SpeechRecognized(object sender, SpeechRecognizedEventArgs r)
{
txtpwd.Text = r.Result.Text;
}
So in the speech recognized events, if I put MessageBox.Show(eml) the email is displayed correctly, but the text of the text box is not changing

Most probably recognized text contains new line characters, or something like this.
To isolate this, try specifying concrete string in *SpeechRecognized events, like
txtemail.Text = "recognized text";
will it work? If yes, inspect string in debugger for specific characters.

Related

How to change password

I'm making an app right now with VisualStudio, and I'm using XAML and C#.
I'm making an app where you can enter a password (existing of numbers only), by clicking on buttons.
If you click on "button 1", it will write a "1" in a label, and if you click on "button 2" afterwards, it will add a "2", making it "12" in total.
If you enter the correct code, like "331122", then you have to press on a button, and a message will pop up saying it is the correct code.
If you fail, then you'll get an error message.
I've also added a "clear" button, that wipes out what you've entered. So far so good. Now I want to add a new button, which will bring you to a passwindow where you can enter your current password (which is the default password: "331122"), and a new password.
If your entered password in the current-password-box matches the default password, your default password will change to the new password you've typed in, if you click on a button below.
If it's incorrect, you'll get an error saying it's incorrect. When you change your password, you should be able to type it in the MainWindow app (by clicking the buttons). The old password has to be completely wiped out, and you should be able to keep on changing your password.
I'm stuck on this.
Here's the code:
string defaultCode = "331122";
public MainWindow()
{
InitializeComponent();
}
//string defaultCode = "331122";
private void knop_1_Click(object sender, RoutedEventArgs e)
{
label_Combinatie.Content += "1";
}
private void knop_2_Click(object sender, RoutedEventArgs e)
{
label_Combinatie.Content += "2";
}
private void knop_3_Click(object sender, RoutedEventArgs e)
{
label_Combinatie.Content += "3";
}
private void knop_klaar_Click(object sender, RoutedEventArgs e)
{
if ((string)label_Combinatie.Content == defaultCode)
{
MessageBox.Show("Unlocked.");
}
else
{
MessageBox.Show("You've entered the wrong code. Please try again.");
}
}
private void knop_reset_Click(object sender, RoutedEventArgs e)
{
label_Combinatie.Content = "";
}
private void knop_verander_code_Click(object sender, RoutedEventArgs e)
{
passwindow w = new passwindow();
w.ShowDialog();
}
public passwindow w { get; set; }
private void button_changePw_Click(object sender, RoutedEventArgs e)
{
string new_code;
new_code = w.textBox_new_code.Text;
defaultCode = w.textBox_current_code.Text;
if (w.textBox_current_code.Text == defaultCode && w.textBox_new_code.Text == new_code)
{
defaultCode = "";
new_code += defaultCode;
new_code = "";
MessageBox.Show("Password changed.");
}
else
{
MessageBox.Show("You've entered an incorrect code. Please try again.");
}
}
Some of the code is in Dutch, so allow me to translate them.
"Knop" means "Button".
"Combinatie" --> "Combination".
"Klaar" -->"Done".
"Verander" --> "Change".
I noticed two issues in your code that may both in combination cause your problems.
First one:
private void knop_verander_code_Click(object sender, RoutedEventArgs e)
{
passwindow w = new passwindow();
w.ShowDialog();
}
public passwindow w { get; set; }
In your method knop_verander_code_Click you are declaring a local variable w, whereas in your class you have declared a property with the same name - the local variable will hide the property.
Second issue:
defaultCode = "";
new_code += defaultCode;
new_code = "";
Here you are basically clearing your defaultCode, adding nothing to your new_code and after all you clear new_code, too.

How can add rules to textBox textchanged event?

What i want to do is:
When the user start typing anything in the textBox2 first make it empty and then start showing what the user is typing.
Then if the user deleting what he was typing then show the original text again.
Now what it does is that i need to delete on my own the text inside but then when i try to type anything i see the original text again since it's empty.
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text != "" || textBox2.Text == "Enter Email Account")
{
textBox2.Text = "Enter Email Account";
button2.Enabled = false;
}
else
{
button2.Enabled = true;
}
}
You should be using a Watermark. But in case you wish to do it as you started, you set the default value in properties.
You need first of all to create your event handlers during the Enter and Leave event;
private void Form1_Load()
{
textBox1.Text = "Enter Email Account";
textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
textBox1.LostFocus += new EventHandler(textBox1_Leave);
}
Then on Enter, the watermark text should be deleted;
protected void textBox1_GotFocus(object sender, EventArgs e)
{
if (textBox1.Text == "Enter Email Account")
{
textBox1.Text = "";
}
}
Then you re-check on Leave event;
protected void textBox1_Leave(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
textBox1.Text = "Enter Email Account";
}
}

C#- Confirm, Password and Email text box shows me message box when I enter first character

//code for confirm password text box:
private void txtRegPassConfirm_TextChanged_1(object sender, EventArgs e)
{
if (txtRegPassConfirm.Text != txtRegPass.Text)
{
MessageBox.Show("Passwords do not match");
txtRegPassConfirm.Clear();
}
else
{
MessageBox.Show("textbox can not be empty");
}
}
//code for text box Password:
private void txtRegPass_TextChanged(object sender, EventArgs e)
{
if (txtRegPass.Text.Length < 8)
{
MessageBox.Show("Password must be at least 8 characters long");
txtRegPassConfirm.Clear();
}
// code for text box Email:
private void txtRegEmail_TextChanged_1(object sender, EventArgs e)
{
string c = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("EmailReg", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email", this.txtRegEmail.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Email = " + dr[4].ToString() + "is Already exist");
txtRegEmail.Clear();
break;
}
Regex r = new Regex("^[a-zA-Z0-9){1,20}#[a-zA-Z0-9){1,20}.[a-zA-Z]{2,3}$");
if (!r.IsMatch(txtRegEmail.Text))
{
txtRegEmail.Clear();
MessageBox.Show("incorrect formate");
}
}
}
//code for button Registration:
private void btnRegistration_Click_1(object sender, EventArgs e)
{
string c = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("RegistrationForm", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#UserName", txtRegUserN.Text);
cmd.Parameters.AddWithValue("#Password", txtRegPass.Text);
cmd.Parameters.AddWithValue("#Confirm", txtRegPassConfirm.Text);
cmd.Parameters.AddWithValue("#Email", txtRegEmail.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Data Inserted Succesfully");
}
}
if (dr.HasRows == false)
{
MessageBox.Show("Access Denied, enter the correct fields");
}
else
{
MessageBox.Show("Enter correct info");
}
}
When I execute the application and enter the password in a confirm text box, it shows me the message box on entering the first character 'Password don't match'. As well as shows me message in the Password text box 'Password must be at least 8 characters long'. And as same as in the Email text box and I want to apply the Regex but not working. I moved my code in the email section but, it shows me the 'Email is invalid' regex message box. Now, tell me what I can do get the message box when I enter the mismatch words not on entering the first character.
Main Problem:
You are checking your validation rules in TextChanged event of your text boxes. Some options that may help you to perform validation is listed here:
Option1: validate in Click Event of Button
You can check for validations in Click event of your register button some thing like this:
private void registerButton_Click(object sender, EventArgs e)
{
//Check for password length
if (txtRegPass.Text.Length < 8)
{
MessageBox.Show("Password must be at least 8 characters long");
txtRegPass.Focus();
return;
}
//Check for other validations
//...
// don't forget to return; if the state is not valid
//If the code execution reaches here, it means all validation have been passed
//So you can save data here.
}
Option 2: Use Validating Event and ErrorProvider
As a better solution, you can use an ErrorProvider. Put an error provider in form and handle Validatin event of your TextBoxes and set error for that control.
Then in Click event of your register button you can check if there is any validation error or not.
and here a screenshot:
private void ValidationTest_Load(object sender, EventArgs e)
{
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;
}
private void passwordTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.passwordTextBox.TextLength < 8)
{
this.errorProvider1.SetError(this.passwordTextBox, "Password must be at least 8 character");
e.Cancel = true;
}
else
{
this.errorProvider1.SetError(this.passwordTextBox, "");
}
}
private void confirmTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.confirmTextBox.Text != this.passwordTextBox.Text)
{
this.errorProvider1.SetError(this.confirmTextBox, "Password and Confirm must be the same");
e.Cancel = true;
}
else
{
this.errorProvider1.SetError(this.confirmTextBox, "");
}
}
private void registerButton_Click(object sender, EventArgs e)
{
if (this.ValidateChildren())
{
//Do registration here
}
else
{
var listOfErrors = this.errorProvider1.ContainerControl.Controls
.Cast<Control>()
.Select(c => this.errorProvider1.GetError(c))
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
MessageBox.Show("please correct validation errors:\n - " +
string.Join("\n - ", listOfErrors.ToArray()),
"Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Because you are using TextChanged event and it raises every time you change the Text. You should check this on click of your button Register.
Not only this one, your all validations should be checked on the button click.
For the help of user, you can use a Label to show the the message while user is typing something, rather showing a MessageBox. That will be a smooth experience for user.
Here is your solution
private void btnRegistration_Click_1(object sender, EventArgs e)
{
if (txtRegPassConfirm.Text != txtRegPass.Text)
{
MessageBox.Show("Passwords do not match");
txtRegPassConfirm.Clear();
return;
}
else
{
if (txtRegPass.Text.Length < 8)
{
MessageBox.Show("Password must be at least 8 characters long");
txtRegPassConfirm.Clear();
return;
}
}
//put your next code as it is which you wrote in this click event
}
Thanks
The problem is you put your validation code in txtRegPassConfirm_TextChanged_1 function. As the name of the function said, that function will be triggered whenever the text in txtRegPassConfirm textbox changed. That's why you get the MessageBox when you first type.
To solve your problem, put your validation code in the Click event of Register button instead of TextChanged event of each textbox.
Another better solution is: use Error Provider Control to show your error instead of using MessageBox. To know more about it, take a look at MSDN.
The validation can also be done while moving to the next text box(Validation of previous text box input) by pressing tab or by mouse click. This can be done in the textbox events Leave or Enter.
private void textBox1_Leave(object sender, EventArgs e) // This event is triggered while leaving the textbox1
{
if ("a" != textBox1.Text)
{
MessageBox.Show("Invalid");
}
}
private void textBox2_Enter(object sender, EventArgs e)// This event is triggered while entering the textbox2
{
if ("a" != textBox1.Text) //Content of textbox1 is validated
{
MessageBox.Show("Invalid");
}
}

Call a method inside an event handler function

I'm trying to implement an application in C# which generates me a QR Code. I've managed to do this, but I don't know how to call CreateQRImage(string inputData) inside the genButton_Click(object sender, EventArgs e).
I inside the windows form I have a textbox and a button, and I think that the function CreateQRImage must be called with the name of the textbox
Here is the code:
private void genButton_Click(object sender, EventArgs e)
{
}
public void CreateQRImage(string inputData)
{
if (inputData.Trim() == String.Empty)
{
System.Windows.Forms.MessageBox.Show("Data must not be empty.");
}
BarcodeWriter qrcoder = new ZXing.BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.QrCode.QrCodeEncodingOptions
{
ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
Height = 250,
Width = 250
}
};
string tempFileName = System.IO.Path.GetTempPath() + inputData + ".png";
Image image;
String data = inputData;
var result = qrcoder.Write(inputData);
image = new Bitmap(result);
image.Save(tempFileName);
System.Diagnostics.Process.Start(tempFileName);
}
This should do the trick:
private void genButton_Click(object sender, EventArgs e)
{
// Assuming your text box name. Also assuming UI disables button until text is entered.
this.CreateQRImage(myTextBox.Text);
}

the total price in the datagrid when I passed it round that price

my English is not good because I'm Spanish so I'm using a translator if you do not understand something ask me.
my problem is that I'm doing a program with two windows in main window I have a datagrid in the second window I pass information with textbox, the problem is that by passing the total price by multiplying the amount I get a dessert for the price of a dessert, the total price in the datagrid when I passed it round that price, if the price happened 1.20 the program will change to 1.
gives me no error so I'll have to spend the entire program code sorry.
This is the second window
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (Application.Current.Properties["seleccionado"] == null)
{
textBox1.IsEnabled = false;
Postresinfo = new TabladePostre();
}
else
{
Postresinfo = (TabladePostre) (Application.Current.Properties["seleccionado"]);
textBox1.IsEnabled=false;
textBox1.Text = Convert.ToString(Postresinfo.refPostre);
textBox2.Text = Postresinfo.NombrePostre;
textBox3.Text = Convert.ToString(Postresinfo.cantidad);
textBox4.Text = Convert.ToString(Postresinfo.precio);
textBox5.Text = Convert.ToString(Postresinfo.preciototal);
}
LinqdePostresDataContext BasedeDatos;
string filename = "";
private void button1_Click(object sender, RoutedEventArgs e)
{
BasedeDatos(LinqdePostresDataContext)Application.Current.Properties["basedeDatos"];
Postresinfo.NombrePostre = textBox2.Text;
Postresinfo.cantidad = Convert.ToInt32(textBox3.Text);
Postresinfo.precio = Convert.ToDecimal(textBox4.Text);
Postresinfo.preciototal = Convert.ToDecimal(textBox5.Text);
Postresinfo.imagen = filename;
if (Application.Current.Properties["seleccionado"] != null)
{
Postresinfo.refPostre=Convert.ToInt32(textBox1.Text);
}
else
{
BasedeDatos.TabladePostres.InsertOnSubmit(Postresinfo);
}
BasedeDatos.SubmitChanges();
this.Close();
}
decimal precio = 0;
private void button2_Click(object sender, RoutedEventArgs e)
{
precio = Convert.ToDecimal(textBox4.Text);
textBox5.Text = Convert.ToString(precio * Convert.ToDecimal(textBox3.Text));
}
private void button9_Click(object sender, RoutedEventArgs e)
{
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".jpg"; // Default file extension
dlg.Filter = "Text documents (.jpg)|*.jpg"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
filename = dlg.FileName;
ImageSourceConverter conversor = new ImageSourceConverter();
image1.Source = (ImageSource)conversor.ConvertFromString(filename);
}
}
this is the main window:
LinqdePostresDataContext BasedeDatos = new LinqdePostresDataContext();
private void activar(object sender, RoutedEventArgs e)
{
Cargartabla();
}
private void Cargartabla()
{
var postre = (from n in BasedeDatos.TabladePostres
select n);
dataGrid1.ItemsSource = postre;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Application.Current.Properties["seleccionado"] = null;
Ventana2 Ventana2 = new Ventana2();
Ventana2.Show();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
BasedeDatos.TabladePostres.DeleteOnSubmit((TabladePostre)dataGrid1.SelectedItem);
BasedeDatos.SubmitChanges();
Cargartabla();
}
private void Activar2(object sender, EventArgs e)
{
Cargartabla();
}
private void button3_Click(object sender, RoutedEventArgs e)
{
Application.Current.Properties["seleccionado((TabladePostre)dataGrid1.SelectedItem);
Application.Current.Properties["basedeDatos"] = BasedeDatos;
Ventana2 ventana2 = new Ventana2();
ventana2.Show();
}
If you need to know also I have a database with int price, int quantity in the total price in decimal.
thanks for reply, I tried both options have given me but does not work, these are the faults:
Postresinfo.refPostre = float.Parse (textBox1.Text) gives me no errors, the program runs normally and nothing changes
float.TryParse (textBox1.Text, out Postresinfo.refPostre) has these faults:
Error 1 A property, indexer or dynamic member access May not be passed as an out or ref parameter.
Error 2 The best overloaded method match for 'float.TryParse (string, out float)' has some invalid arguments
Error 3 Argument 2: can not convert from 'out int' to 'float out'
I tried the other code and nothing changes, the program runs normally
shane now, I tried this code:
Convert.ToDecimal (textBox1.Text);
but it changes nothing and runs normally.
I've also tried the other code, but nothing changes and the program runs normally
the fault is not textbox1, I think it's because it's in that TextBox5 textbox where I enter the price in decimal and passes it to the datagrid and is the rounded
I'll also attach the column fails me:
<DataGridTextColumn Binding="{Binding Path=preciototal}" Header="Precio Total"/>
thanks.
you got a lot of code here and i'm not sure what is the problem. i understand that you get round value but it'll be helpful to mention the name of the textBox that it happens in it.
i did saw this code:
Postresinfo.refPostre=Convert.ToInt32(textBox1.Text);
in button1_Click which will cause rounding if the value in textBox1.Text is float.
you should do
Postresinfo.refPostre=float.Parse(textBox1.Text);
or
float.TryParse(textBox1.Text, out Postresinfo.refPostre);
because it's a textbox and you might get a value which isn't a number.
if you decide to use Parse then you should do
try
{
Postresinfo.refPostre=float.Parse(textBox1.Text);
}
catch
{
// Show a message or write to log or simething
}
Your problem is that you are converting a price like "1.20" to an int with Convert.ToInt32(textBox1.Text);.
Try change Postresinfo.refPostre to a decimal and use Convert.ToDecimal(textBox1.Text); so use something like this as a FormatException could be thrown:
try
{
Convert.ToDecimal(textBox1.Text);
}
catch (Exception)
{
//Deal with Error
}

Categories

Resources