Performing multiple validations on one field C# - c#

I have to validate the textboxes to check if they are a number and if they are in the database. Only problem is I can only seem to get it to check for validity or if they are numeric. How can change this to get both validations?
it validates to make sure there is something in the textboxes:
if (string.IsNullOrEmpty(employeeIDTextBox.Text) && (string.IsNullOrEmpty(JobIDTextBox.Text)))
Then it looks to see if the value is numeric, then if it does it checks to see if the person exists, then sets the values
else if (string.IsNullOrEmpty(JobIDTextBox.Text))
{
if (!Int32.TryParse(JobIDTextBox.Text, out number1))
{
using (dbConn)
{
ReportGrid newGrid = new ReportGrid();
if (newGrid.isValidEmp(Int32TryParseSafe(employeeIDTextBox.Text)))
{
newGrid.startDate = startingdateTimePicker.Value;
newGrid.endDate = endingdateTimePicker.Value;
newGrid.EmployeeID = Int32TryParseSafe(employeeIDTextBox.Text);
newGrid.JobID = Int32TryParseSafe(JobIDTextBox.Text);
newGrid.ShowDialog();
}
else
{
MessageBox.Show("No ID found for the employee.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
Then it does the same for the other textbox
else if (string.IsNullOrEmpty(employeeIDTextBox.Text))
{
if (!Int32.TryParse(emplyeeIDLabel.Text, out number2))
{
using (dbConn)
{
ReportGrid newGrid = new ReportGrid();
if (newGrid.isValidJob(Int32TryParseSafe(JobIDTextBox.Text)))
{
newGrid.startDate = startingdateTimePicker.Value;
newGrid.endDate = endingdateTimePicker.Value;
newGrid.EmployeeID = Int32TryParseSafe(employeeIDTextBox.Text);
newGrid.JobID = Int32TryParseSafe(JobIDTextBox.Text);
newGrid.ShowDialog();
}
else
{
MessageBox.Show("No ID found for that job.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
MessageBox.Show("Must be a number.");
}
Here is the whole code
try
{
if (string.IsNullOrEmpty(employeeIDTextBox.Text) && (string.IsNullOrEmpty(JobIDTextBox.Text)))
{
MessageBox.Show("Please enter a EmployeeID or JobID.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (string.IsNullOrEmpty(JobIDTextBox.Text))
{
if (!Int32.TryParse(JobIDTextBox.Text, out number1))
{
using (dbConn)
{
ReportGrid newGrid = new ReportGrid();
if (newGrid.isValidEmp(Int32TryParseSafe(employeeIDTextBox.Text)))
{
newGrid.startDate = startingdateTimePicker.Value;
newGrid.endDate = endingdateTimePicker.Value;
newGrid.EmployeeID = Int32TryParseSafe(employeeIDTextBox.Text);
newGrid.JobID = Int32TryParseSafe(JobIDTextBox.Text);
newGrid.ShowDialog();
}
else
{
MessageBox.Show("No ID found for the employee.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
MessageBox.Show("Must be a number.");
if (startingdateTimePicker.Value > endingdateTimePicker.Value)
{
MessageBox.Show("Starting data can not be after than ending date.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else if (string.IsNullOrEmpty(employeeIDTextBox.Text))
{
if (!Int32.TryParse(emplyeeIDLabel.Text, out number2))
{
using (dbConn)
{
ReportGrid newGrid = new ReportGrid();
if (newGrid.isValidJob(Int32TryParseSafe(JobIDTextBox.Text)))
{
newGrid.startDate = startingdateTimePicker.Value;
newGrid.endDate = endingdateTimePicker.Value;
newGrid.EmployeeID = Int32TryParseSafe(employeeIDTextBox.Text);
newGrid.JobID = Int32TryParseSafe(JobIDTextBox.Text);
newGrid.ShowDialog();
}
else
{
MessageBox.Show("No ID found for that job.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
MessageBox.Show("Must be a number.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

I could be mistaken but is this line possibly the problem?
if (!Int32.TryParse(emplyeeIDLabel.Text, out number2))
The exclamation point reverses the bool so if the text successfully parses as a number the TryParse function returns true but by using the exclamation the if statement resolves to false. Therefore you are sending the code to else statement which states that it is not a number.
Also, try using "Return" to avoid nested ifs.
if (string.IsNullOrEmpty(employeeIDTextBox.Text) && (string.IsNullOrEmpty(JobIDTextBox.Text)))
{
MessageBox.Show("Please enter a EmployeeID or JobID.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Return;
}
There's no need for an else at this point because the if the if statement resolves to true you will return from the method.
Nested if statements are frequently necessary but they should be avoided when they can to make code clearer to read for maintenance.

Related

Why my methods interfering with each others and with if statements in C#?

I have a form to insert some data in sql database with some conditions , First I need to check for nulls and alert the user :
void CheckNulls() {
try {
if (txtcode.Text.Length == 0 || txtItem.Text.Length == 0 || txtWh.Text.Length == 0) {
MessageBox.Show("Fill Required Fields", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else {
checkExistAndDo();
}
}
catch(Exception Err) {
MessageBox.Show("This Error Occured :" + Err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Then I need to check if the user checked any checkbox :
void checkExistAndDo() {
if (chkProduct.Checked || chkMaterial.Checked)
{
if (chkProduct.Checked == true) {
if (!chkMaterial.Checked) {
da = new SqlDataAdapter("SELECT [ProductCode] FROM Products Where [ProductCode] = #prcode ", Cn);
da.SelectCommand.Parameters.AddWithValue("#prcode", txtcode.Text);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0) {
MessageBox.Show("Existing Code", "Error");
}
else {
TakeAction();
}
}
}
else {
da = new SqlDataAdapter("SELECT Code FROM Items Where Code = #prcode ", Cn);
da.SelectCommand.Parameters.AddWithValue("#prcode", txtcode.Text);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0) {
MessageBox.Show("Existing Code", "Error");
}
else {
TakeAction();
}
}
}
else {
MessageBox.Show("Check even one", "check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
So , I have 4 different combinations in total :
chkProduct.Checked : chkMaterial.Checked : Action
--------------------------------------------------------------
true : true : InsertSubProduct()
true : false : InsertProduct()
false : true : InsertMaterial()
false : false : Ask User to Check
Then I need to take action based on the combination :
private void TakeAction()
{
try
{
if (chkProduct.Checked == true && chkMaterial.Checked == false)
{
InsertProduct();
MessageBox.Show("Product Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (chkProduct.Checked == false && chkMaterial.Checked == true)
{
InsertMaterial();
MessageBox.Show("Material Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
InsertSubProduct();
MessageBox.Show("SubProduct Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception Err)
{
MessageBox.Show("This Error Occured :" + Err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
this.Close();
}
}
The problem is that this part doesn't do anything not showing my message , Not even an error message as if it doesn't exist in my code :
else
{
InsertSubProduct();
MessageBox.Show("SubProduct Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Sorry for long post but i tried my best and debugged the code many times and i can't get pass this , Thanks in advance and your help is deeply appreciated .
If the ThreeState property is set to true, the Checked property will return true for either a Checked or Indeterminate CheckState.
Check the ThreeState property for chkMaterial checkbox
Based on #Joel Coehoorn comments I tried different approach
I quote " Do separation of concerns better. CheckNulls() should only return a bool, and not show any messages to the user or call any other methods. checkExistAndDo() should not exist at all (that logic should be entirely in the database as part of InsertProduct/MaterialSubproduct()). "
It worked great , Thanks all for replying , I appreciate your guiding .

Get the name of a ComboBox in ComboBoxColumn

I came across the following problem:
I have a DataGridView with 5 Column where the first 3 are ComboBoxColumns. So i want that a User has to select the first ComboBox so that on the second will be loaded the data (SQL Query with value of first ComboBox). An so on also for the third one which is only working when the first two are set.
Now i have the problem. If I check if selected Index change via the code below. It gives an error because on the second ComboBox i dont need .SubString(). So i wanted to check the names of the ComboBoxes and make some if branches to check wether is the first, second or third ComboBox. But all of my tries give me an empty return.
Is there a possibility to solve my problem?
private void datagridview1_detailed_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
{
cb.SelectedIndexChanged += new EventHandler(selectionchange);
}
}
void selectionchange(object sender, EventArgs e)
{
try
{
ComboBox cb = (ComboBox)sender;
//To Test the output
Console.WriteLine("CB_NAME:" + ((ComboBox)sender).Tag);
Console.WriteLine("CB_NAME:" + ((ComboBox)sender).Name);
Console.WriteLine("CB_NAME:" + cb.Name);
if (cb.Name == "datagridview1_value1")
{
order_id = cb.Text.Substring(0, 6);
fill_second_combo();
}
else if (cb.Name == "datagridview1_value2")
{
fill_third_combo();
}
}
catch {
Console.WriteLine("Error");
}
}
Fill second ComboBox Code:
private void fill_second_combo()
{
string rcs = db_conn.connection();
using (var OraConn = new OracleConnection(rcs))
{
using (var OraCmd = OraConn.CreateCommand())
{
try
{
OraConn.Open();
OraCmd.BindByName = true;
OraCmd.CommandText = "select * from xxx where order_id" + order_id +";
OracleDataReader OraDataReader = OraCmd.ExecuteReader();
if (OraDataReader.Read() == false)
{
MessageBox.Show("No data!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
using (var OraDat = new OracleDataAdapter(OraCmd))
{
using (var combo2_table = new DataTable())
{
OraDat.Fill(combo2_table );
foreach (DataRow combo2_row in combo2_table .Rows)
{
foreach (DataColumn combo2 in combo2_table .Columns)
{
if (combo2_row[combo2 ] != null)
{
if (combo2.ColumnName == "Second Value")
{
secondComboBox.Items.Add(combo2_row[combo2.ColumnName].ToString());
}
}
}
}
}
}
}
}
catch (OracleException ex)
{
switch (ex.Number)
{
case 1:
MessageBox.Show("F1 -DB Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case 12560:
MessageBox.Show("F2 - DB Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
default:
MessageBox.Show("F3 - DB Error: " + ex.Message.ToString(), "Fehlermeldung", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
OraConn.Dispose();
}
}
}
}
All of the Test-Outputs are empty in my case.

How to fix this "for loop" what in if statement

I wrote nested if statement. One of them includes a loop. After this loop else statement does not work As if they did not exist. It goes to catch statement.
Although when I cancel this loop, else statement work.
How can I fix it?
This is visual studio and SQL Server 2005. I have tried to save the value what in the text box "txtCategoryName". In the first if statement I check that text box is not null. In the second "if statement" I check the value what in the text box duplicate or not. In the else statement, I save the value.
try
{
if (txtCategoryName.Text == string.Empty)
{
MessageBox.Show("Fill the textBox", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else if (txtCategoryName.Text != string.Empty)
{
for (int i = 0; i <= dgvCategory.Rows.Count; i++)
{
if (dgvCategory.Rows[i].Cells[1].Value.ToString() == txtCategoryName.Text)
{
MessageBox.Show("Choose another name", "", MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
return;
}
}
}
else
{
txtCategoryId.Text = clsCat.getCategoryId().Rows[0][0].ToString();
clsCat.addCategory(txtCategoryName.Text);
MessageBox.Show("Done", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCategoryId.Clear();
txtCategoryName.Clear();
dataPreview();
}
}
catch
{
MessageBox.Show("Erroe save in category", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
I expect to save "txtCategoryName.Text" in the database if it pass through the first "if statement" and the second "if statement" to do what in "else statement". But after the loop in the second "if statement" it goes to "catch" directly.
The problem is in int i = 0; i <= dgvCategory.Rows.Count; i++ because you are initializing the i with 0 and go through dgvCategory.Rows.Count.
It should be int i = 0; i < dgvCategory.Rows.Count; i++ more specifically i < dgvCategory.Rows.Count; instead of i <= dgvCategory.Rows.Count;
Just add one isElseLoop bool variable which will get updated once the else loop is executed. Refer the code below.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
bool isElseLoop = false;
if (txtCategoryName.Text == string.Empty)
{
MessageBox.Show("Fill the textBox", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else if (txtCategoryName.Text != string.Empty)
{
for (int i = 0; i < dgvCategory.Rows.Count; i++)
{
if (dgvCategory.Rows[i].Cells[1].Value.ToString() == txtCategoryName.Text)
{
MessageBox.Show("Choose another name", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
isElseLoop = true;
return;
}
}
}
if (!isElseLoop)
{
txtCategoryId.Text = clsCat.getCategoryId().Rows[0][0].ToString();
clsCat.addCategory(txtCategoryName.Text);
MessageBox.Show("Done", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCategoryId.Clear();
txtCategoryName.Clear();
dataPreview();
}
}
catch
{
MessageBox.Show("Erroe save in category", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}

prevent data from add to db after Message Box

I want after Message Box show
prevent data from insert to DB
int numberOfRecords = Convert.ToInt32(qotext.Text);
if (numberOfRecords == 9999)
{
MessageBox.Show("try other value", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
You need something like:
if (conditionToNotInsert) {
MessageBox.Show(...);
} else {
InsertStuffIntoDb();
}
The else block is only executed if the condition of the if is not true.

What is the best practice for try catch inside try catch?

My function is saving a customer data when there is a booking request. There are 2 conditions : force to save booking even if customer data is not filled yet or save booking with completed customer data.
I do the try catch and raise the exception to user in case that the program found that this customer doesn't exist to confirm that user wants to create new customer data or not. If yes, open new form and if not, force the program to save.
Inside forcing the program to save, I want to catch other exceptions if exist.
Currently, I'm doing like this.
try
{
booking = new Booking();
booking.RoomID = roomID;
booking.Tel = txtTel.Text;
booking.PersonalID = txtId.Text;
booking.Name = txtBookBy.Text;
booking.CheckinDate = dtpCheckin.Value;
booking.CheckoutDate = dtpCheckin.Value.AddDays(Convert.ToDouble(cbNight.SelectedItem));
mng.SaveBooking(booking, false);
if (MessageBox.Show("Data is saved") == DialogResult.OK)
{
this.Close();
}
}
catch (NewCustomerException ex)
{
DialogResult dialog = MessageBox.Show("Customer doesn't exist in database. Do you want to create new customer?", "Please confirm", MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
String param = txtBookBy.Text + "," + txtTel.Text + "," + txtId.Text;
CustomerForm oForm = new CustomerForm(param);
oForm.Show();
}
else if (dialog == DialogResult.No)
{
try
{
mng.SaveBooking(booking, true);
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
You never use exceptions to control the flow of your program.
The mng.SaveBooking(booking, false); should return true/false to signal the calling code that a customer doesn't exist.
Better to write a method that gives you back just this information and then use that info to write the following code
try
{
// Check if customer already registered
if(mng.CustomerExists(CustomerKey))
{
mng.SaveBooking(booking, false);
if (MessageBox.Show("Data is saved") == DialogResult.OK)
{
this.Close();
}
}
else
{
DialogResult dialog = MessageBox.Show("Customer doesn't exist in database. " +
"Do you want to create new customer?", "Please confirm", MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
.....
}
else
{
.....
}
}
}
catch(Exception ex)
{
... somthing unexpected here
}
Make separate try catch block so that every try catch block follow single responsibility. In catch block you can manage the statement for which it throw exception and you can use that manage statement result in the next try catch block.
try {
booking = new Booking();
booking.RoomID = roomID;
booking.Tel = txtTel.Text;
booking.PersonalID = txtId.Text;
booking.Name = txtBookBy.Text;
booking.CheckinDate = dtpCheckin.Value;
booking.CheckoutDate = dtpCheckin.Value.AddDays(Convert.ToDouble(cbNight.SelectedItem));
mng.SaveBooking(booking, false);
if (MessageBox.Show("Data is saved") == DialogResult.OK) {
this.Close();
}
}
catch (NewCustomerException ex) {
DialogResult dialog = MessageBox.Show("Customer doesn't exist in database. Do you want to create new customer?", "Please confirm", MessageBoxButtons.YesNo);
}
if (dialog == DialogResult.Yes) {
String param = txtBookBy.Text + "," + txtTel.Text + "," + txtId.Text;
CustomerForm oForm = new CustomerForm(param);
oForm.Show();
}
else if (dialog == DialogResult.No) {
try {
mng.SaveBooking(booking, true);
}
catch (Exception ex1) {
MessageBox.Show(ex1.Message);
}
}
}

Categories

Resources