Validate 5 digits in the textbox - c#

I am trying to make the textbox valid when just the user writes 5 digits but the problem is if I for example input (11111) it will be correct, the program will not show an error message. But if the id was for example (12345) the message box will show how I can solve it?
namespace black_clover_project2
{
public partial class Add_student : Form
{
public Add_student()
{
InitializeComponent();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
student s = new student();
Regex regex = new Regex(#"^[0-4]{5}$");
if (regex.IsMatch(s.id = tbid.Text))
{
s.id = tbid.Text;
}
else { MessageBox.Show("invalid id"); } // 5 dig condtion for id
if (String.IsNullOrEmpty(tbname.Text))
{
MessageBox.Show("please write the first name");
}
else { s.name = tbname.Text; } // name condtion
s.lastname = tblastname.Text;
s.email= tbemail.Text;
s.dob = tbdob.Text;
s.dos = tbdos.Text;
}
private void button3_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
this.Hide();
f1.ShowDialog();
this.Close();
}
private void tbid_TextChanged(object sender, EventArgs e)
{
}
}
}

The issue is with your if statement:
if (regex.IsMatch(s.id = tbid.Text))
{
s.id = tbid.Text;
}
Change to
if (regex.IsMatch(tbid.Text))
{
s.id = tbid.Text;
}
You need to check the input against the regex condition, and then if it is valid, pass the value to object id.

You don't need to use regex. To verify you can test if the length of the string if equal to 5 and then test if it is an integer. Also in my opinion you should be checking as the user types and not after he is finished so that if there are 5 digits entered then an "OK" or "DoSomething" button is enabled.
private void OnTextChanged(object sender, EventArgs e)
{
bool isOK = false;
if (textbox1.Text.Length == 5)
{
int i = 0;
if (Int32.TryParse(textbox1.Text, out i))
isOK = true;
}
button1.Enabled = isOK;
}

Related

The name "svar" does not exist in the current context

I'm very new to programming and I am writing a short hangman game for my programming class, I have two private voids, one when you change the text in the textbox for the correct answer and one for when you guess a character. I need to transfer the variable "svar" from the first instance to the other, when I try to use the variable "svar" in the second instance I get the error message "The name "svar" does not exist in the current context"
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void TbxSvar_TextChanged(object sender, EventArgs e)
{
if (tbxSvar.TextLength == 6)
{
pbxGubbe.Top = 6;
tbxVisa.Text = "??????";
tbxGissa.Enabled = true;
string svar = tbxSvar.Text;
tbxSvar.Text = "";
}
else
{
tbxVisa.Text = "";
}
}
private void TbxGissa_TextChanged(object sender, EventArgs e)
{
if (tbxGissa.Text == "") return;
string gissning = tbxGissa.Text;
int index = svar.indexOf(gissning);
}
}
You have defined svar as a variable in a method so it won't be visible elsewhere (unless you pass it as a method argument). Instead define it as a field in your class.
public partial class Form1 : Form
{
string svar; // <----------- place here. Now it is a 'field'
public Form1()
{
InitializeComponent();
}
private void TbxSvar_TextChanged(object sender, EventArgs e)
{
if (tbxSvar.TextLength == 6)
{
pbxGubbe.Top = 6;
tbxVisa.Text = "??????";
tbxGissa.Enabled = true;
svar = tbxSvar.Text; // <---------- use svar here
tbxSvar.Text = "";
}
else
{
tbxVisa.Text = "";
}
}
private void TbxGissa_TextChanged(object sender, EventArgs e)
{
if (tbxGissa.Text == "") return;
string gissning = tbxGissa.Text;
int index = svar.indexOf(gissning); // <---------- ...and here
}
}

System.FormatException: 'The format of the input string is incorrect.'

I am new with C# and I built a very basic calculator that allows a user to enter two numbers into two textboxes and an operator via buttons. When the user clicks result, the calculator computes the result.
For getting user input, I have: firstnumber = Double.Parse(fnum.Text);. The program compiles but throws the exception System.FormatException: 'The format of the input string is incorrect.'.
I have also tried firstnumber = Convert.ToDouble(fnum.Text); but got the same exception.
Here is my code:
namespace Bear3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private double firstnumber;
private double secondnumber;
private double resultt=0;
private bool plusch = false;
private bool minusch = false;
private bool multiplicationch = false;
private bool divisionch = false;
private void Button1_Click(object sender, EventArgs e)
{
Operator.Text="+";
plusch = true;
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Fnum_TextChanged(object sender, EventArgs e)
{
firstnumber = Convert.ToDouble(fnum.Text);
}
private void Label2_Click(object sender, EventArgs e)
{
}
private void Minus_Click(object sender, EventArgs e)
{
Operator.Text = "-";
minusch = true;
}
private void Multiplication_Click(object sender, EventArgs e)
{
Operator.Text = "*";
multiplicationch = true;
}
private void Division_Click(object sender, EventArgs e)
{
Operator.Text = "/";
divisionch = true;
}
private void Result_Click(object sender, EventArgs e)
{
if (plusch == true)
{
resultt = firstnumber + secondnumber;
}
else if (minusch == true)
{
resultt = firstnumber - secondnumber;
}
else if (multiplicationch == true)
{
resultt = firstnumber * secondnumber;
}
else if (divisionch == true)
{
resultt = firstnumber / secondnumber;
}
ResultShow.Text = Convert.ToString(resultt);
}
private void Snum_TextChanged(object sender, EventArgs e)
{
secondnumber = Double.Parse(snum.Text);
}
private void Clear_Click(object sender, EventArgs e)
{
plusch = false;
minusch = false;
multiplicationch = false;
divisionch = false;
ResultShow.Text = "";
Operator.Text = "";
fnum.Text = "";
snum.Text = "";
}
}
}
Rather than getting the variables on TextChanged which can fire more often than you expect, do it on the Result click action.
Move these lines to the top of the Result_Click and remove them from their current spot.
firstnumber = Convert.ToDouble(fnum.Text);
secondnumber =Convert.ToDouble(snum.Text);
I do recommend you check to see if the data is actually a Double so you don't get an error.
Update your Fnum_TextChanged and Snum_TextChanged methods to validate the text when parsing:
private void Fnum_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(fnum.Text))
{
if (double.TryParse(fnum.Text, out firstnumber) == false){
// notify user in message box or throw error
}
}
}
After this runs, if there is no error that means fnum.Text parsed and is now stored in your firstnumber variable.

C# ListBox syncing with each other

I am trying to make a program that has 3 listBoxes an I need to alphabetize 1 of them but the and the other 2 listboxes info needs to still match the first listBox. As of now I don't have any code for that to show, but I do have my add item code to give a general idea of what I am looking for.
private void addButton_Click(object sender, EventArgs e)
{
if (itemTextBox.Text == "")
MessageBox.Show("Please enter an item to add");
else
groceryListBox.Items.Add(itemTextBox.Text);
itemTextBox.Clear();
countTextBox.Text = groceryListBox.Items.Count.ToString();
//if (quanityListBox.Text == "")
// MessageBox.Show("Please enter an item to add");
//else
quanityListBox.Items.Add(quanityTextBox.Text);
quanityTextBox.Clear();
// countTextBox.Text = quanityListBox.Items.Count.ToString();
//if (priceListBox.Text == "")
// MessageBox.Show("Please enter an item to add");
//else
priceListBox.Items.Add(priceTextBox.Text);
priceTextBox.Clear();
//countTextBox.Text = priceListBox.Items.Count.ToString();
itemTextBox.Focus();
}
private void removeSingleButton_Click(object sender, EventArgs e)
{
if (groceryListBox.SelectedIndex != -1)
{
while(groceryListBox.SelectedItems.Count != 0)
{
groceryListBox.Items.Remove(groceryListBox.SelectedItems[0]);
}
}
else
{
MessageBox.Show("Please Select an item(s) to remove");
}
}
private void saveButton_Click(object sender, EventArgs e)
{
Settings.Default["List1"] = groceryListBox.Items.ToString();
Settings.Default.Save();
}
private void Form1_Load(object sender, EventArgs e)
{
groceryListBox.Text = Settings.Default["List1"].ToString();
}
private void button1_Click(object sender, EventArgs e)
{
groceryListBox.Items.Clear();
}
private void button2_Click(object sender, EventArgs e)
{
groceryListBox.SelectedItems.Clear();
for (int i = groceryListBox.Items.Count - 1; i >= 0; i--)
if (groceryListBox.Items[i].ToString().ToLower().Equals(searchTextBox.Text.ToLower()))
groceryListBox.SetSelected(i, true);
}
private void colorButton_Click(object sender, EventArgs e)
{
groceryListBox.BackColor = Color.DeepSkyBlue;
}
private void containsToolStripMenuItem_Click(object sender, EventArgs e)
{
{
groceryListBox.SelectedItems.Clear();
for (int i = groceryListBox.Items.Count - 1; i >= 0; i--)
if (groceryListBox.Items[i].ToString().ToLower().Contains(searchTextBox.Text.ToLower()))
groceryListBox.SetSelected(i, true);
}
}
private void startsWithToolStripMenuItem_Click(object sender, EventArgs e)
{
{
groceryListBox.SelectedItems.Clear();
for (int i = groceryListBox.Items.Count - 1; i >= 0; i--)
if (groceryListBox.Items[i].ToString().ToLower().StartsWith(searchTextBox.Text.ToLower()))
groceryListBox.SetSelected(i, true);
}
}
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
editTextBox.Text = groceryListBox.SelectedItem.ToString();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
editTextBox.Paste();
}
private void toolsToolStripMenuItem_Click(object sender, EventArgs e)
{
if (editTextBox.Text == "")
MessageBox.Show("Please enter an item to add");
else
groceryListBox.Items[groceryListBox.SelectedIndex] = editTextBox.Text;
editTextBox.Clear();
countTextBox.Text = groceryListBox.Items.Count.ToString();
}
Any help would be appreciated. Thank you.
Edit.... I figured out how to post screenshot....
At least they allow me a link for now, I guess until my reputation goes up. :-)
This is what I want it to do, if I add an item to the list with quantity and price, and I have multiple items in the list I still want the quantity and price to match that item across from it.
This might help too.....
With the items matching the price and quantity.
If I'm reading your question right, you're looking for an easy way to show the same info between multiple ListBoxs? If so you could try the following:
private List<string> testList = new List<string>();
private void BindTestListData()
{
listBox1.DataSource = null;
listBox1.DataSource = testList;
listBox2.DataSource = null;
listBox2.DataSource = testList;
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(InputTextBox.Text))
{
testList.Add(InputTextBox.Text);
InputTextBox.Clear();
BindTestListData();
}
}
Feed all your text from your text box into a list instead of adding it directly to the ListBox. Then bind the list to the datasource of your ListBox.
EDIT
Scratch what I had before. I think I better understand your problem now. try something like this:
private struct Item
{
public string Name { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
}
private List<Item> items = new List<Item>();
private void BindTestListData()
{
listBox1.DataSource = null;
listBox1.DataSource = items;
listBox1.DisplayMember = "Name";
listBox2.DataSource = null;
listBox2.DataSource = items;
listBox2.DisplayMember = "Quantity";
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(InputTextBox.Text))
{
Item newItem = new Item()
{
Name = InputTextBox.Text,
Quantity = "1",
Price = "$10"
};
items.Add(newItem);
InputTextBox.Clear();
BindTestListData();
}
}
Obviously, the numbers in the button1_click() method are just place holders, but something like this should work.

c# - Cannot convert from void to list

So, I got kind of stuck over my head while I tried to program something new.
I'm trying to add objectBeer_pluche or objectBeer_Elektro to my OBJberenlijst on the Beren Main form from the details Form, so I can add both instances of 2 classes to the same list.
I'm not even sure this is possible by the way. So, I would like feedback if what I am trying to do is possible to start with. I already figured VOID is not right but I am really clueless here.
This is my main beren.cs form with an OBJberenlist, that's where I try to add objectBeer_pluche or objectBeer_Elektro into it:
public partial class Beren : Form
{
public interface Berenlijst { }
public List<Berenlijst> OBJberenLijst = new List<Berenlijst>();
public Beren()
{
InitializeComponent();
}
private void Beren_Load(object sender, EventArgs e)
{
}
private void BTNToevoegen_Click(object sender, EventArgs e)
{
this.Hide();
Details Details = new Details();
if (Details.ShowDialog(this) == DialogResult.OK)
{
OBJberenLijst.Add(Details.getdetails());
}
Details.Close();
Details.Dispose();
}
public void LijstLaden()
{
foreach(Beer berenobject in OBJberenLijst)
{
LST_beren.Items.Add(berenobject.Naam);
}
}
}
}
from this form called details.cs
public partial class Details : Form
{
public Details()
{
InitializeComponent();
BTN_toevoegen.DialogResult = DialogResult.OK;
BTN_cancel.DialogResult = DialogResult.Cancel;
}
private void Details_Load(object sender, EventArgs e)
{
RDB_pluche.Checked = true;
BTN_ok.Enabled = false;
}
private void RDB_pluche_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = true;
PANEL_elektro.Visible = false;
}
private void RDB_elektro_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = false;
PANEL_elektro.Visible = true;
}
private void BTN_toevoegen_Click(object sender, EventArgs e)
{
open_foto.Filter = "jpg (*.jpg)|*.jpg|bmp(*.bmp)|*.bmp|png(*.png)|*.png";
if (open_foto.ShowDialog() == System.Windows.Forms.DialogResult.OK && open_foto.FileName.Length > 0)
{
TXT_adres.Text = open_foto.FileName;
PIC_beer.Image = Image.FromFile(open_foto.FileName);
}
}
private void BTN_ok_Click(object sender, EventArgs e)
{
}
public void getdetails()
{
if (RDB_pluche.Enabled == true)
{
Pluche_Beer objectBeer_pluche = new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
else
{
Elektronische_Beer objectBeer_Elektro = new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
}
private void Details_MouseMove(object sender, MouseEventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox textBox = c as TextBox;
if (textBox.Text != string.Empty)
{
BTN_ok.Enabled = true;
}
}
}
}
}
}
The problem is between this line...
OBJberenLijst.Add(Details.getdetails());
...and this line.
public void getdetails()
List.Add() requires an object to add, but getdetails() returns void. You probably want to change getdetails() to something like the following:
public Berenlijst getdetails()
{
if (RDB_pluche.Enabled == true)
{
return new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
return new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
Hopefully Pluche_Beer and Elektronisch_Beer inherent from Berenlijst. Otherwise you'll have to revise your logic in a broader way.

C# How to auto okay from RFID scanning?

I have a program wherein the user taps an RFID card on a reader and the program will input this data. In this program, there is a prompt wherein I have to click OK. How do I remove the OK button and make it an auto-OK program once the RFID card is tapped?
Here are the parts of the program:
delegate void Function();
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string sdsd = serialPort1.ReadLine();
string Hexed = new LasalleRFIDComputerRentals.BLL.DAL.Utils().HexIt(sdsd);
SetRFIDText(Hexed);
}
protected void SetRFIDText(string input)
{
this.Invoke(new Function(delegate()
{
txtRFID.Text = input;
}));
CustomerInfo customer = new Customer().GetCustomerByRFID(txtRFID.Text);
}
private void btnOk_Click(object sender, EventArgs e)
{
if (txtRFID.Text.Trim() == "")
{
MessageBox.Show(this, "Please supply the RFID.", "RFID Reader", MessageBoxButtons.OK);
txtRFID.Focus();
return;
}
CustomerInfo customer = new Customer().GetCustomerByRFID(txtRFID.Text);
if (customer.CustomerID <= 0)
{
MessageBox.Show("Invalid RFID", "Validation");
this.Close();
return;
}
if (_parentForm == "StandBy")
{
Utils.CurrentCustomer.CustomerInfo = customer;
frmStandBy form = (frmStandBy)this.Owner;
form.xResult = "OK";
}
this.Close();
}
Simply separate the logic of the OK button
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string sdsd = serialPort1.ReadLine();
string Hexed = new LasalleRFIDComputerRentals.BLL.DAL.Utils().HexIt(sdsd);
SetRFIDText(Hexed);
}
protected void SetRFIDText(string input)
{
this.Invoke(new Function(delegate()
{
txtRFID.Text = input;
}));
// what is it for?
//CustomerInfo customer = new Customer().GetCustomerByRFID(txtRFID.Text);
SearchCustomer();
}
private void btnOk_Click(object sender, EventArgs e)
{
SearchCustomer();
}
private void SearchCustomer()
{
if (txtRFID.Text.Trim() == "")
{
MessageBox.Show(this, "Please supply the RFID.", "RFID Reader", MessageBoxButtons.OK);
txtRFID.Focus();
return;
}
CustomerInfo customer = new Customer().GetCustomerByRFID(txtRFID.Text);
if (customer.CustomerID <= 0)
{
MessageBox.Show("Invalid RFID", "Validation");
this.Close();
return;
}
if (_parentForm == "StandBy")
{
Utils.CurrentCustomer.CustomerInfo = customer;
frmStandBy form = (frmStandBy)this.Owner;
form.xResult = "OK";
}
// what is it for?
//this.Close();
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string sdsd = serialPort1.ReadLine();
string Hexed = new LasalleRFIDComputerRentals.BLL.DAL.Utils().HexIt(sdsd);
SetRFIDText(Hexed);
btnOK_click(sender, e);
}
This doesn't answer the question "how do I remove the OK button" since you didn't show how it was created in the first place - I suspect you need to edit the form definition for that. In that case change the code for btnOK_click from an event handler to a "regular" function (which would be a good idea anyway).

Categories