using a try catch statement to keep a text box cleared - c#

I am making a windows form application that takes various game entries (title,genre,price) and then stores them in an array with a maximum of four entries.
The error I am having is that if there are no values entered in my text boxes, I want a message box to appear to force the user to enter values. This happens.
The problem is that after this, it does not give the user another try. It just stops the program. I have tried using a try catch statement to do this but I am not quite sure how to use this. Would this be the correct solution?
namespace gameForm
{
public partial class gameEntryForm : Form
{
public gameEntryForm()
{
InitializeComponent();
}
struct Game
{
public string Title;
public string Genre;
public decimal Price;
}
static Game[] aNewGame = new Game[4]; //max size of the array is 4
static int newGameEntryIndex = 1;
private void gameEntryForm_Load(object sender, EventArgs e)
{
aNewGame[0].Title = "golf tour"; //this is a game already stored in the database
aNewGame[0].Genre = "sports";
aNewGame[0].Price = 1.99m;
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
}
//catch()
//{
//}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
private void btnShow_Click(object sender, EventArgs e)
{
rtbShow.Text = "Game Details \n\nGame 1 \n" + aNewGame[0].Title + "\n" + aNewGame[0].Genre + "\n" + aNewGame[0].Price + "\n\n" + "Game 2 \n" + aNewGame[1].Title + "\n" + aNewGame[1].Genre + "\n" + aNewGame[1].Price + "\n\n" + "Game 3 \n" + aNewGame[2].Title + "\n" + aNewGame[2].Genre + "\n" + aNewGame[2].Price + "\n\n" + "Game 4 \n" + aNewGame[3].Title + "\n" + aNewGame[3].Genre + "\n" + aNewGame[3].Price; ;
}
//clears the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
rtbShow.Clear();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}

Add a return, no try/catch required:
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
return; // Exit current function
}
Try/catch is for when you have exceptions.

Try-Catch is of no use to you.
What you should do is in the btnSave_Click method return when the textboxes are not populated:
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text)
{
MessageBox.Show("Please enter a game genre, game title and game price.");
return;
}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
...
There is another solution you could do. Only activate the Save-button if all three textboxes has values in them.
Something like:
private void ValidateGameData(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text))
{
btnSave.Enabled = false;
}
else
{
btnSave.Enabled = true;
}
}
tbGenre.TextChanged += ValidateGameData;
tbTitle.TextChanged += ValidateGameData;
tbPrice.TextChanged += ValidateGameData;

In your code for btnSave_Click you are testing the value of the various TextBoxes and displaying a message if they are NULL or empty.
However, you continue execution of your code even if they are NULL or empty.
You should stop processing more code if the conditions fail so that you don't try to use the NULL\empty values.
Something like:
private void btnSave_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
else if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
else if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
else
{
// You forgot to create the new game at this index
aNewGame[newGameEntryIndex] = new Game();
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
}
I've also added a line:
aNewGame[newGameEntryIndex] = new Game();
As I couldn't see anywhere that you created the new Game object before trying to set it's properties.

Related

I have a validation that stops the user navigating to the next window but when all fields are cleared goes to the next window

I am working on a project and I am trying to get my Navigation button to recognise when values already stored are cleared from the clear all fields button made. Its fine when I do not enter any values the first time but if I type them in and store them then clear all fields I press the navigation button then I progress onto the window without entering any details. Is there a way to solve this?
here is my code:
thank you.
private void clear_Click(object sender, RoutedEventArgs e)
{
//clears all fields to start again on enetring your details
if (SCNResult.Text == String.Empty || Nameresult.Text == String.Empty)
{
MessageBox.Show("You need to enter your details and store them before pressing this button");
return;
}
Nameresult.Text = " ";
box.Text = "";
namebox.Text = "";
SCNResult.Text = " ";
error.Text = " ";
//
}
/////END OF BUTTON////
private void comp_Click(object sender, RoutedEventArgs e)
{
// This instruction stops the user from continuing if they have not entered their details.
if (SCNResult.Text == String.Empty || Nameresult.Text == String.Empty)
{
MessageBox.Show("You need to enter your details before progressing to the next window");
return;
}
else
{
computing Nav1 = new computing();
Nav1.Show();
this.Close();
}
//end of instruction
//navigates to the next window
//
}
When you clear the fields:
Nameresult.Text = " "; //here is the problem
box.Text = "";
namebox.Text = "";
SCNResult.Text = " "; //here is the problem
error.Text = " ";
" " is not an empty string, that's why your if always return false

c# Populating a ListView from an XML File

I am still learning my way around c# and am trying to populate my ListView from an XML file.
Below is a picture of my ListView:
ListView
When I click a button on my UI, it reads the XML file using this code (Configuration.cs) here:
public static void LoadConfiguration(MainUI UIForm)
{
XDocument doc = XDocument.Load("E:\\InnerSpace" + "\\Scripts\\BJScripts\\MySettings.xml");
MainUI uI = new MainUI();
UIForm.addItemsToActionsListView(doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Position_X").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Position_Y").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("RGB").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Is_Colour").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Target").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Press_Button").Value);
}
Then it calls a method in my MainUI.cs and passes the relevant information I need to it.
public partial class MainUI : Form
{
public MainUI()
{
InitializeComponent();
}
private void MainUI_FormClosing(object sender, FormClosingEventArgs e)
{
Program._bMustShutdown = true;
}
public void NewActionsConsoleMessage(string Input)
{
ActionsConsole.Items.Add(DateTime.Now.ToString("h:mm:ss tt") + ": " + Input);
ActionsConsole.SelectedIndex = (ActionsConsole.Items.Count - 1);
}
private void btnAddAction_Click(object sender, EventArgs e)
{
if (txtboxLocationX.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Position X and try again.");
MessageBox.Show("Enter a value for Position X and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtboxLocationY.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Position Y and try again.");
MessageBox.Show("Enter a value for Position Y and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtboxColourRGB.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Pixel RGB and try again.");
MessageBox.Show("Enter a value for Pixel RGB and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!radionbtnIsColour.Checked && !radionbtnIsNotColour.Checked)
{
NewActionsConsoleMessage("ERROR: Select either tracking by colour or tracking my not colour and try again.");
MessageBox.Show("Select either tracking by colour or tracking my not colour and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (cboxTarget.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Select a target and try again.");
MessageBox.Show("Select a target and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtboxActionBtn.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Action to Take Button Press and try again.");
MessageBox.Show("Enter a value for Action to Take Button Press and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
ListViewItem addActionsItem = new ListViewItem(txtboxLocationX.Text);
addActionsItem.SubItems.Add(txtboxLocationY.Text);
addActionsItem.SubItems.Add(txtboxColourRGB.Text);
addActionsItem.SubItems.Add(radionbtnIsColour.Checked.ToString());
addActionsItem.SubItems.Add(cboxTarget.Text);
addActionsItem.SubItems.Add(txtboxActionBtn.Text);
lvActionsList.Items.Add(addActionsItem);
}
private void btnSetPixelLocationColour_Click(object sender, EventArgs e)
{
var pixelColourPickerUI = new PixelColourPickerUI();
pixelColourPickerUI.ShowDialog();
txtboxLocationX.Text = pixelColourPickerUI._SelectedPixelMouseLocX;
txtboxLocationY.Text = pixelColourPickerUI._SelectedPixelMouseLocY;
txtboxColourRGB.Text = pixelColourPickerUI._SelectedPixelColor_R + "," + pixelColourPickerUI._SelectedPixelColor_G + "," + pixelColourPickerUI._SelectedPixelColor_B;
pnlConfigurePixelColour.BackColor = Color.FromArgb(pixelColourPickerUI._SelectedPixelColor_A, pixelColourPickerUI._SelectedPixelColor_R, pixelColourPickerUI._SelectedPixelColor_G, pixelColourPickerUI._SelectedPixelColor_B);
}
public ListView.ListViewItemCollection listViewItemCollection
{
get { return lvActionsList.Items; }
}
public void addItemsToActionsListView(string _LocX, string _LocY, string _RGB, string _IsColour, string _Target, string _ButtonPress)
{
Debug.WriteLine("_LocX: " + _LocX + "_LocY" + _LocY + "_RGB" + _RGB + "_IsColour" + _IsColour + "_Target" + _Target + "_ButtonPress" + _ButtonPress);
ListViewItem addActionsItem = new ListViewItem(_LocX);
addActionsItem.SubItems.Add(_LocY);
addActionsItem.SubItems.Add(_RGB);
addActionsItem.SubItems.Add(_IsColour);
addActionsItem.SubItems.Add(_Target);
addActionsItem.SubItems.Add(_ButtonPress);
Debug.WriteLine("Count: " + addActionsItem.SubItems.Count);
lvActionsList.Items.Add(addActionsItem);
}
private void btnSaveActionsList_Click(object sender, EventArgs e)
{
Configuration.Configuration.SaveConfiguration(items: lvActionsList.Items);
}
private void btnLoadProfile_Click(object sender, EventArgs e)
{
Configuration.Configuration.LoadConfiguration(this);
}
}
The first Debug.WriteLine returns the proper passed variables from Configuration.cs and the second Debug.WriteLine returns the proper count of 6 SubItems.
However, when viewing my ListView, it is still empty. Previously, I was able to add the the ListView using identical code (with different variables) when I was making what eventually became the XML file information. What am I doing wrong when trying to load the information from the XML? Do you need to see more code?
Thanks in advance!
Pass in the MainUI as argument to your static method:
public static void LoadConfiguration(MainUI UiForm)
{
XDocument doc = XDocument.Load("E:\\InnerSpace" + "\\Scripts\\BJScripts\\MySettings.xml");
UiForm.addItemsToActionsListView(doc.Element("UABA" etc
}

How do you add items to a listbox on a second form?

Working on a project for school that has 2 forms. I want to add items to the listbox in the Display form when I click the show data button. It's showing the form but the form is blank. I think this is because the form object is being created 2x once when I click the add button and another when I click the show data button. How can I create a new object of the display form that can be used in any method in my main form?
Sorry there is a few things in here that I am still working on that were just ideas. I am a beginner so please keep the help in simple terms if at all possible. Thanks :)
private void addEmployee(Employee newEmployee)
{
//Get data from textboxes and use set methods in employee class
newEmployee.Name = EmployeeNameTextBox.Text;
newEmployee.BirthDate = EmployeeBirthDateTextBox.Text;
newEmployee.Dept = EmployeeDeptTextBox.Text;
newEmployee.HireDate = EmployeeHireDateTextBox.Text;
newEmployee.Salary = EmployeeSalaryTextBox.Text;
}
private void AddButton_Click(object sender, EventArgs e)
{
//New list for employee class objects - employeelist
List<Employee> employeeList = new List<Employee>();
//Create new instance of Employee class - newEmployee
Employee newEmployee = new Employee();
bool errorCheck = false;
CheckForms(ref errorCheck);
if (!errorCheck)
{
//Gather input from text boxes and pass newEmployee object
addEmployee(newEmployee);
//Add object to employeeList
employeeList.Add(newEmployee);
Display myDisplay = new Display();
myDisplay.OutputListBox.Items.Add(" Bob");
//" " + newEmployee.BirthDate + " " +
//newEmployee.Dept + " " + newEmployee.HireDate + " " + newEmployee.Salary);
You are creating two separate instances of mydisplay.Create a single instance when the Form Loads and refer to that when you call ShowDataButton_Click
namespace WK4
{
public partial class MainForm : Form
{
Display myDisplay;
public MainForm()
{
InitializeComponent();
}
//Method to clear form input boxes
private void ClearForm()
{
EmployeeNameTextBox.Text = "";
EmployeeBirthDateTextBox.Text = "";
EmployeeDeptTextBox.Text = "";
EmployeeHireDateTextBox.Text = "";
EmployeeSalaryTextBox.Text = "";
FooterLabel.Text = "";
}
//Method to check for blank input on textboxes
private void CheckForms(ref bool error)
{
if (EmployeeNameTextBox.Text == "" || EmployeeBirthDateTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else if (EmployeeDeptTextBox.Text == "" || EmployeeHireDateTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else if (EmployeeSalaryTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else
error = false;
}
private void addEmployee(Employee newEmployee)
{
//Get data from textboxes and use set methods in employee class
newEmployee.Name = EmployeeNameTextBox.Text;
newEmployee.BirthDate = EmployeeBirthDateTextBox.Text;
newEmployee.Dept = EmployeeDeptTextBox.Text;
newEmployee.HireDate = EmployeeHireDateTextBox.Text;
newEmployee.Salary = EmployeeSalaryTextBox.Text;
}
private void AddButton_Click(object sender, EventArgs e)
{
//New list for employee class objects - employeelist
List<Employee> employeeList = new List<Employee>();
//Create new instance of Employee class - newEmployee
Employee newEmployee = new Employee();
bool errorCheck = false;
CheckForms(ref errorCheck);
if (!errorCheck)
{
//Gather input from text boxes and pass newEmployee object
addEmployee(newEmployee);
//Add object to employeeList
employeeList.Add(newEmployee);
Display myDisplay = new Display();
myDisplay.OutputListBox.Items.Add(" Bob");
//" " + newEmployee.BirthDate + " " +
//newEmployee.Dept + " " + newEmployee.HireDate + " " + newEmployee.Salary);
//Clear Form after adding data
ClearForm();
//Print footer employee saved info
FooterLabel.Text = ("Employee " + newEmployee.Name + " saved.");
}
}
//Exit the form/program
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
//Method to clear the form and reset focus
private void ClearButton_Click(object sender, EventArgs e)
{
ClearForm();
EmployeeNameTextBox.Focus();
}
private void ShowDataButton_Click(object sender, EventArgs e)
{
myDisplay.ShowDialog();
}
private void MainForm_Load(object sender, EventArgs e)
{
myDisplay = new Display();
}
}
}
You are making 2 different instances of display class, in first instance you are adding data and you are displaying it using the second instance thats why you are getting a blank form
create a display class object on your MainForm_Load
private void MainForm_Load(object sender, EventArgs e)
{
Display myDisplay = new Display();
}
and the use this object (myDisplay) to add and display data in your AddButton_Click and ShowDataButton_Click methods respectively.

Add textbox data to an object after button click c#

I pass a custom Associate object into a field and I want to add user name and password to it after a button click event. The problem is I loose scope of the object in the button click event. How do I get around this? Here is the code I have so far...
public partial class frmCredentials : Form
{
public frmCredentials(Associate _associate)
{
InitializeComponent();
//Put in values for MES system and username
this.label1.Text = "Please enter your " + _associate.mesType + " password";
this.txtUsername.Text = _associate.userName;
//Change form color for MES system
if (_associate.mesType == "FactoryWorks")
{
this.BackColor = System.Drawing.Color.Aquamarine;
}
else
{
this.BackColor = System.Drawing.Color.Yellow;
}
}
private void btnOk_Click(object sender, EventArgs e)
{
//Make sure associate has filled in fields
if (this.txtUsername.Text == "" || this.txtPassword.Text == "")
{
MessageBox.Show("You must enter a Username and Password");
return;
}
this.Visible = false;
return ;
}
}
The solution is to create an instance field for your Associate object. And then set the instance field value in your constructor.
public partial class frmCredentials : Form
{
private Associate _associate;
public frmCredentials(Associate _associate)
{
InitializeComponent();
this._associate = _associate;
//Put in values for MES system and username
this.label1.Text = "Please enter your " + _associate.mesType + " password";
this.txtUsername.Text = _associate.userName;
//Change form color for MES system
if (_associate.mesType == "FactoryWorks")
{
this.BackColor = System.Drawing.Color.Aquamarine;
}
else
{
this.BackColor = System.Drawing.Color.Yellow;
}
}
private void btnOk_Click(object sender, EventArgs e)
{
// you can use _associate object in here since it's an instance field
//Make sure associate has filled in fields
if (this.txtUsername.Text == "" || this.txtPassword.Text == "")
{
MessageBox.Show("You must enter a Username and Password");
return;
}
this.Visible = false;
return ;
}
}

Retain the message in the textbox when the checkbox is still checked

I have 3 checkboxes with corresponding message in a textbox. My teacher wants the message to remain in the textbox when the checkbox is still checked and hide the text when it is unchecked. In my case when I checked the 3 checkboxes their 3 corresponding messages will appear but when I unchecked one of the checkboxes and the other two are still checked, all the message will disappear. My problem is when I unchecked one of the checkbox and and the other 2 are still checked the corresponding messages with the remaining two checked checkboxes will remain in their textboxes.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
if (chkCarWheels.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
if (chkCarAcceleration.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
if (chkCarBreakpad.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
Looks like you need to create message depending on checkboxes states. You can create method, which will do the job and call it when state of some checkbox changed.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
Or the better one - create one event handler for all checkboxes:
// use for chkCarWheels, chkCarAcceleration, chkCarBreakpad
private void chkCar_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void BuildMessage()
{
lblMessage.Text = "My " + txtName.Text + " Car";
if (chkCarWheels.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
if (chkCarAcceleration.Checked)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
if (chkCarBreakpad.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
}
You don't need to compare boolean values with true/false. Use those values directly if (chkCarWheels.Checked). And keep in mind that in C# we use CamelCase names form methods. Also consider to use StringBuilder to build whole message and then assign it to label:
private void BuildMessage()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("My {0} Car", txtName.Text);
if (chkCarWheels.Checked)
sb.Append(mycar.hasWheels(4));
if (chkCarAcceleration.Checked)
sb.Append(mycar.Accelerate());
if (chkCarBreakpad.Checked)
sb.Append((mycar.hasBreak());
lblMessage.Text = sb.ToString();
}
Try this:
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
chkCar()
}
private void chkCar()
{
string msg="";
if (chkCarWheels.Checked)
msg=msg+mycar.hasWheels(4);
if(chkCarAcceleration.Checked)
msg=msg+mycar.Accelerate();
if(chkCarBreakpad.Checked)
msg=msg+mycar.hasBreak();
lblMessage.Text=msg;
}

Categories