how to save an ID if the you leave the name empty? - c#

I'm Working in this program for two days and i can not find out where I'm doing Wrong.If you could help me I really appreciate it .The Problem is when I enter 11111 for my the curator ID and leave the name Box Empty,it is not suppose to saved the curator ID .After if I put something in the box and i enter 11111 for the Curator ID it says "ID already exist please try again".
private void SaveCuratorBtn_Click(object sender, RoutedEventArgs e)
{
curator Curator = new curator();
try
{
Curator.ID = CuratorIDbox.Text;
bool sameid = false;
for (int i = 0; i < curatorlist.Count; i++)
{
if (curatorlist[i].ID == Curator.ID)
{
sameid = true;
break;
}
}
if (sameid)
MessageBox.Show("ID already exist please try again !");
else
{
curatorlist.add(Curator);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
try
{
bool checkingname = false;
Curator.NAME = CuratorNamebox.Text;
checkingname = true;
if (checkingname)
{
MessageBox.Show("Curator Saved");
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}

if (sameid)
{
MessageBox.Show("ID already exist please try again !");
}
else
{
curatorlist.add(Curator);
}
This code block is doing the following:
If the ID already exists, show an error (good!)
If the ID doesn't exist, add the whole Curator to curatorlist.
What you need is another step of validation in your code to make sure that box the name textbox and the ID textbox contain information. You could achieve this like so (replace the names of course):
else
{
if(string.IsNullOrEmpty(NameTextbox.Text) || string.IsNullOrEmpty(IdTextbox.Text)
{
MessageBox.Show("Uh oh!")
} else {
curatorlist.add(Curator);
}
Here you're checking if the textboxes are empty before even thinking about adding the Curator to curatorlist. If you need to make other checks (such as no numbers [1,2,3,4] in your NameTextbox), there are multiple ways of doing so.

You say that "when I enter 11111 for my the curator ID and leave the name Box Empty,it is not suppose to saved the curator ID"; but there is nothing in the sample code that you have provided which prevents this. That might be what you want; but you haven't coded it that way: the "curatorlist.add(Curator);" will add the curator to the collection regardless of what is in the Name box.
P.S. consider using a Dictionary, as the lookup will be faster.

Related

btnSubmit_Click skipping try and going straight to catch (Exception ex)

I have two near identical forms on the site and only one of them works. On firing button click they're supposed to collect text from checkbox fields and email that information on. One of the forms try is completely ignored and the error message in catch is displayed
Using the working form on the new page still won't work makes me think there may be issues with the page, but deleting the aspx and aspx.cs pages and rewriting them when it may not be that serious is not something I want to do if it's not necessary. I've tried removing 'if (IsPostBack)' and 'if (LiabilityCheckBox.Checked == true)' on the form with issues among other things, but nothing seems to help.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
if (LiabilityCheckBox.Checked == true)
{
// validate the Captcha to check we're not dealing with a bot
bool isHuman = ExampleCaptcha.Validate(CaptchaCodeTextBox.Text);
CaptchaCodeTextBox.Text = null; // clear previous user input
if (!isHuman)
{
lblCaptchaError.Visible = true;
lblCaptchaError.Text = "Incorrect Code. Please try again!";
}
else
{
try
{
//some code
lblRegMessage.Text =
("Registration Successful. Thank you for entering."
+ "Please click button below to finalise Payment and Registration.");
// Clear the textbox values
//Show Continue Button.
ContinueButton.Visible = true;
}
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
}
}
else
{
lblMessage.Text = ("You must check the Liability check box to continue");
}
}
}
I am expecting the result of filling out the form to be the mail is sent and a message appears telling the user "Registration Successful. Thank you for entering."
What I am getting is this:
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
As I checked, your code missing some closing brackets. Please check the brackets are properly closed and in the series.

Searching for an item within a ListBox using a TextBox and a Button

I am creating a system that includes a ListBox of integers inserted by the user. I have contained a search button and a search TextBox for the user to input the integer they want to search for within the ListBox. Once the user has inputted the integer, I want a message box to be displayed either informing the user that there is e.g. 1 integer of value '3' in the list box, or an error message box informing the user that the integer does not exist within the list box.
private void buttonSearch_Click(object sender, EventArgs e)
{
listBoxAddedIntegers.SelectedItems.Clear();
for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;
{
if (listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())) ;
{
listBoxAddedIntegers.SetSelected(i, true);
}
}
// ...
}
I am not really sure on the code that I am meant to include here, and the code that I have already inserted suggests that 'i' does not exist in the current content.
Can anyone help please?
the code that I have already inserted suggests that 'i' does not exist in the current content
As #FrankM already mentioned in the comments. You have a trailing ; after your for-loop.
for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;
This will prevent the for-loop to execute your code within the { ... }. This can be transcribed to
for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--)
{
// Do nothing.
}
{
// now your code
}
This means also that your code within the last curly braces will be in its own scope and so that all your defined variables will be unavailable to the following code.
Answering your actual question:
As you already do for selecting the matching items. You can extent this looping by counting up a counter. And later on show the results with a MessageBox.
With the following snippet of your code
listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower()))
you are currently checking if an item of your list contains the entered TextBox.Text.
So if the user has entered 3, 4, 5, ..., 13, 23 in the ListBox and searches for 3. He will get 3 matches. If you want only 1 match you should use String.Equals(). I used StringComparison.InvariantCultureIgnoreCase to avoid calling ToLower().
private void buttonSearch_Click(object sender, EventArgs e)
{
var counter = 0;
for (int i = 0; i < this.listBoxAddedIntegers.Items.Count; i++)
{
var item = this.listBoxAddedIntegers.Items[i];
if (string.Equals(item.ToString(), this.textBoxSearch.Text, StringComparison.InvariantCultureIgnoreCase))
{
this.listBoxAddedIntegers.SelectedItems.Add(item);
counter++;
}
}
if (counter == 0)
{
MessageBox.Show($"No matches for \"{this.textBoxSearch.Text}\" found!", "Search Results",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show($"{counter} items found for \"{this.textBoxSearch.Text}\"!", "Search Results",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Hint:
Since C#6 you can use string interpolation instead of String.Format() or string concatenation (+).
private void buttonSearch_Click(object sender, EventArgs e)
{
listBoxAddedIntegers.SelectedItems.Clear();
var itemsFound = listBoxAddedIntegers.Items.Where(i=>i.ToString().ToLower().Contains(textBoxSearch.Text.ToLower())).ToList();
if(itemsFound == null)
{
MessageBox.Show("No matches found.");
}
else
{
MessageBox.Show("Found " + itemsFound.Count + " matches.");
}
}
You have to do this:
int count=0;
for(int i=0;i<listBoxAddedIntegers.Items.Count;i++)
{
if(listBoxAddedIntegers.Items[i].Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())
{
count+=1;
}
}
if(count>0)
{
//display your message here after the loop with the count
}
else
{
//display your message with error
}

errorprovider or message box?

I have a simplr windows form input(student name,studentid) to display to a listbox.
I need to check for duplicate student id in listbox before i add a value.
Can I use error provider on student id text box to do this?
any help much appreciated
please check last bit of my code below -is for/foreach loop required?
Thanks
private void txtSid_Validating(object sender, CancelEventArgs e)
{
bool can = false;
int sid = 0;
if (string.IsNullOrEmpty(txtSid.Text))
{
ep1.SetError(txtSid, "Please Enter Student ID");
can = true;
}
else if (!int.TryParse(txtSid.Text, out sid))
{
ep1.SetError(txtSid, "Student ID must be a number");
can = true;
}
else
for (int i = 0; i < lstDisplay.Items.Count; i++)
{
if (lstDisplay.Items[i].ToString().Contains(txtSid.Text))
{
ep1.SetError(txtSid, "Student ID already added");
can = true;
}
{
}
e.Cancel = can;
}
Yes, you can use Error Provider. In fact, for in-place validation such as you are doing, I tend to prefer them. I try to limit pop-up boxes, as they can be annoying to the user. Error providers, coupled with disabling a Save button, for instance, can provide a block to continuing as well as information as to why, all without annoying pop-ups.
As for checking against items already in the list box, yes, I would loop over them checking one at a time. If there are a lot of them, or if performance is highly critical, then you could implement a custom comparer for the items you add to the list box. They could also be of a custom class to facilitate the mechanics of it all.

Form Validation Before Storing to SQLite DB in C#

I have a save button. When a user clicks it. The data-input in the the form will be validated before it will be send to the db. How can I achieve it?
Here's the code of my save button.
private void save_Click(object sender, EventArgs e)
{
try
{
int civil_caseI = int.Parse(civil_case.Text);
}
catch (Exception cc)
{
MessageBox.Show("Enter Number Only on CIVIL CASE");
}
string areaI = area.Text;
if (areaI.Length <= 0)
{
MessageBox.Show("Area Field must not be Empty");
}
string addressI = address.Text;
if (addressI.Length <= 0)
{
MessageBox.Show("Address Field must not be Empty");
}
// HERE WILL BE THE QUERY TO INSERT THE DATA AFTER THE FORM IS VALIDATED.
}
You are not returning from your method if there is an error in validation. return early from your method if there is an exception/failure in rule validation. You can just add return; statement after showing the error message.
A better way would be to use int.TryParse to parse int values instead of try-catch. Remember exceptions are expensive. You can also use string.IsNullOrWhiteSpace instead of addressI.Length <= 0 which will consider white space as invalid values (if you are using .Net framework 4.0 or higher, otherwise use `string.IsNullOrEmpty).
private void save_Click(object sender, EventArgs e)
{
int civil_caseI;
if (!int.TryParse(civil_case.Text, out civil_caseI))
{
MessageBox.Show("Enter Number Only on CIVIL CASE");
return; //add that - early return
}
string areaI = area.Text;
if (string.IsNullOrEmpty(areaI.Trim()))
{
MessageBox.Show("Area Field must not be Empty");
return;
}
string addressI = address.Text;
if (string.IsNullOrEmpty(addressI.Trim())) //or addressI.Trim().Length <= 0
{
MessageBox.Show("Address Field must not be Empty");
return;
}
//HERE WILL BE THE QUERY TO INSERT THE DATA AFTER THE FORM IS VALIDATED.
}
You can also extract out the logic of your validation in a separate method returning bool and then call that method for validation.

Cant find the issue in this loop

I have a form that the user inputs values that i save in an array but when the user wants to cancel i want the user to be asked a final time if the user wants to go ahead and cancel a reservation. If the user declines this final time i want the program to go back to the GUI and focus on the textbox with all the rows of reservations and not do the cancelation but i show u the code i have written and it asks the user if they are sure and if not it still deletes the reservation and then focus on the textbox. What is wrong in my code?
public void Cancelreservation()
{
int index = lstReservations.SelectedIndex;
bool checkedindex = m_seatMngr.CheckIndex(index);
if (checkedindex)
{
if (!m_seatMngr.CancelSeat(index))
{
if (lstReservations.SelectedIndex == -1)
{
MessageBox.Show("You need to select a row.", "Error!",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
lstReservations.Focus();
}
else
{
MessageBox.Show("The seat is not reserved! No need to cancel
reservation.", "Important Query",
MessageBoxButtons.OK);
lstReservations.Focus();
}
}
else
{
if (MessageBox.Show("Continue to cancel the reservation?",
"Important Query", MessageBoxButtons.YesNo)
== DialogResult.No)
{
lstReservations.Focus();
}
else
{
m_seatMngr.CancelSeat(index);
}
}
}
m_seatMngr
public bool CancelSeat(int index)
{
if (m_vacantList[index] == "Reserved")
{
m_nameList[index] = " - ";
m_priceList[index] = 0;
m_vacantList[index] = "Vacant";
return true;
}
else
{
return false;
}
}
Assuming that m_seatMngr.CancelSeat(index) is the method that actually cancels the seat, you are calling the method twice. The second if statement, half a dozen lines into your code, is this:
if (!m_seatMngr.CancelSeat(index))
... and it seems likely (given the above assumption) that this line will cancel the seat before you even display the MessageBox.
if (!m_seatMngr.CancelSeat(index))
{
// the rest of your code, which displays the messageboxes
}
This is always calling m_seatMngr.CancelSeat, before you've even displayed any messageboxes.

Categories

Resources