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.
Related
I'm trying to create a simple login screen, which has 2 textboxes and 1 button. When strings i've insterted in the first textbox (username) and the second textbox (password) matches the strings i've defined before, the buttons Enabled propertie should become True and when clicked, it should open another form, here's the code i've written so far:
public partial class LogInScreen : Form
{
public LogInScreen()
{
InitializeComponent();
string lietotajvards = "user";
string parole = "user";
if (textBox1.Text == lietotajvards && textBox2.Text == parole)
{
button1.Enabled = true;
}
else
{
button1.Enabled = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
this.Hide();
f1.Show();
}
}
The thing is that with my code it doesn't work as expected and the button is enabled all the time. Where's the problem?
Your code will only execute once when the form is initialized, you have to make use of a textchanged event on textbox1 and textbox2, thereafter you can use the code you wrote to check if the button needs to be enabled. In the else you must disable the button.
Text changed event handlers:
void textBox1_TextChanged(object sender, EventArgs e)
{
handleLoginButton();
}
void textBox2_TextChanged(object sender, EventArgs e)
{
handleLoginButton();
}
Enable/disable button:
private void handleLoginButton(){
string lietotajvards = "user";
string parole = "user";
if (textBox1.Text == lietotajvards && textBox2.Text == parole)
{
button1.Enabled = true;
}
else
{
button1.Enabled = false;
}
}
The constructor only runs once for the form, you need to handle the text changed events for the input controls and then re-evaluate your condition again.
Also it should go without saying (although it is being said here) that this is a terrible way to handle logging in to an application.
I am trying to validate windows form with try catch and so far I succeeded. My goal is when someone forgot to fill the gap or put in incorrect entry, catch returns messagebox with a warning. Now I also have Validating event on every control I want to validate so when somebody leave it empty or in incorrect format it will show the error next to the control. That seems ok so far (for me, at least) but my issue is, that if user doesn't even click to one box it only shows message box, but it won't highlight wrong controls.
Below is my code:
private void createButton_Click(object sender, EventArgs e)
{
try
{
Book newBook = new Book(titleBox.Text, authBox.Text, Convert.ToInt32(yearBox.Text), Convert.ToInt32(editBox.Text), pubComboBox.Text, descBox.Text);
bookList.Add(newBook);
booklistListBox.DataSource = bookList;
}
catch (FormatException)
{
MessageBox.Show("You probably missed a gap or put in incorrect form");
}
}
and those validating events:
private void titleBox_Validating(object sender, CancelEventArgs e)
{
if (titleBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(titleBox, "Title is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(titleBox, "");
}
}
private void authBox_Validating(object sender, CancelEventArgs e)
{
if (authBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(authBox, "Author is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(authBox, "");
}
}
private void yearBox_Validating(object sender, CancelEventArgs e)
{
if (yearBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(yearBox, "Year is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(yearBox, "");
}
}
private void editBox_Validating(object sender, CancelEventArgs e)
{
if (editBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(editBox, "Edition is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(editBox, "");
}
}
private void pubComboBox_Validating(object sender, CancelEventArgs e)
{
if (pubComboBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(pubComboBox, "Publisher is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(pubComboBox, "");
}
}
private void descBox_Validating(object sender, CancelEventArgs e)
{
if (descBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(descBox, "Description is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(descBox, "");
}
}
So is there way to, I don't know, change focus or something like that, forced with pressing the create button?
Thank You
Try using ValidateChildren():
private void createButton_Click(object sender, EventArgs e)
{
bool gotIssues = this.ValidateChildren();
if (gotIssues)
{
// someone didn't validate well...
}
}
So, the issue here is that you want to have it highlight in either of two scenarios:
1) When you leave the field and its contents are invalid (empty in this case)
2) When you click the create button and the field in question has invalid contents
And so I would create a single textBox_checkIfEmpty(object sender, EventArgs e) method:
private void textBox_checkIfEmpty(object sender, EventArgs e)
{
var asTb = sender as TextBox;
if (asTb != null && asTb.Text.Trim() == String.Empty)
{
errorProvider.SetError(asTb, "I'll leave it to you to abstract the error message appropriately");
e.Cancel = true;
}
else
{
errorProvider.SetError(asTb, "");
}
}
Then, you can set this method as the handler for your Validate event on your desired required controls, and you can also call the same method from the create button's handler, looping through the required TextBox instances and executing the method on each.
UPDATE
J. Hudler's ValidateChildren solution would be a more (developer) efficient tail to mine, as opposed to looping through the desired controls. That said, if the form has many children, and you only need to validate several, it might be helpful to loop still. Just depends on your specific scenario. My only other question is whether or not ValidateChildren is infinitely recursive, or if it only goes one level down (immediate children rather than all descendants).
the event validating for control call when the mouse click on the control and then leave it from the control. In your case when the user does not click on the control it will not trigger the validating event. U can do this by making your own function and call them on creat event.
private void button1_Click(object sender, EventArgs e)
{
textBox1_Validating(sender);
}
public void textBox1_Validating(object sender)
{
MessageBox.Show("validating");
errorProvider1.SetError(textBox1, "provide");
}
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
}
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.
I have two Forms in my application. They way I call Form 2 is like this:
Form 1:
private void btnTest_Click(object sender, EventArgs e)
{
DialogResult result = new System.Windows.Forms.DialogResult();
Add_Link addLink = new Add_Link();
result=addLink.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
//
}
}
Form 2:
private void btnAdd_Click(object sender, EventArgs e)
{
if(validURL(txtSubLink.Text))
{
HyperLink add = new HyperLink(txtSubLink.Text,txtSubText.Text,"URL");
this.build = add;
}
else
{
MessageBox.Show("Valid URL Needed! " + txtSubLink.Text, "ERROR");
}
}
My problem is if the user clicks the Add button, the error message shows(because the data is invalid or the textboxes are empty) BUT it closes the form. I only want the user to close the form and pass the data back if the two textboxes contain the proper data. If the two textboxes don't contain the proper data OR is empty, when the user clicks Add, the error message should show, and the Form 2 should remain open, How do I get that to happen...?
I suspect your btnAdd has its DialogResult property set to OK. Unset that, and then add this.DialogResult = DialogResult.OK in your event handler when you're satisfied with the input.
private void btnAdd_Click(object sender, EventArgs e)
{
if(validURL(txtSubLink.Text))
{
HyperLink add = new HyperLink(txtSubLink.Text,txtSubText.Text,"URL");
this.build = add;
this.DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("Valid URL Needed! " + txtSubLink.Text, "ERROR");
}
}