Getting data from ms access database using reader properly - c#

Good day sir! I able to call a data from my database using reader and after getting a data in the database their will be a messageBox appear when I get my expected data. Here's my sample code:
if (textBox5.Text == "")
{ }
else
{
DialogResult ms = MessageBox.Show("Try Again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
if (ms == DialogResult.OK)
{
textBox5.Clear();
textBox1.Clear();
listBox5.Items.Clear();
textBox3.Clear();
listBox4.Items.Clear();
}
}
while (reader.Read())
{
listBox4.Items.Clear();
if (string.Compare(label1.Text, reader.GetString(0)) == 0)
{
for (int t = 1; t < 11; t++)
{
words.Add(reader.GetString(t));
}
}
words.Shuffle();
listBox4.Items.AddRange(words.ToArray());
}
reader.Close();
coon.Close();
My problem here is when I apply these codes, there are two messageBox will appear so I remove this codes :
textBox5.Clear();
textBox1.Clear();
listBox5.Items.Clear();
textBox3.Clear();
listBox4.Items.Clear();
all I want is I want to show the messageBox once. Can u help me with this?

You have not shown enough code, but I'm going to assume this function is inside a TextChanged event.
If that is the case, you're checking if TextBox5 has some text, then you're clearing a number of controls on the form. You haven't shown other events and what they do, so it would be hard to tell you more at this point.
Consider debugging your code and stepping through it line by line, that way you can follow the logic of the program flow and see where the hiccup occurs...
I'd also change the first 3 lines:
if (textBox5.Text == "")
{ }
else
with if (!string.IsNullOrEmpty(this.textBox5.Text.Trim())), which means, if string is not empty (null or empty to be precise).
Hope this helps.
Good luck

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.

If statement skips the elements except the first one in the for loop. How can I get the right solution for the other elements?

for (int i = 0; i < dt.Rows.Count; i++)
{
if (textBox1.Text == dt.Rows[i]["FIRSTNAME"].ToString().ToLower() && textBox2.Text == dt.Rows[i]["LASTNAME"].ToString().ToLower())
{
Main ss = new Main(); // Main is the another form which is seen after the successful enterance.
ss.Show();
break;
}
else {
MessageBox.Show("UserName or Password is Wrong");
}
}
I want to create a Windows form application using C# and PL/SQL database. I have a data information which consists of the FÄ°RSTNAME and LASTNAME of the two persons. Because of the for loop, I get both of the success and the failure messages at the same time for the second person's information. When for loop cannot match the second person's information with the first person's information, it shows the failure message. Then it sees right information. So, it returns the true message to me.
How can I return the beginning of the if statement to get the all solutions until the end of the database? I put the else statement's codes out of the for loop. I got always the failure message because of the non-existing the if statement to Control the failure.
Shortly, what do I need to do?
Lot of conceptual errors. The else statements is not out of the loop!
You need a flag to check if you have found or not the person in the loop. Then check this flag out of the loop.
bool found = false;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (textBox1.Text == dt.Rows[i]["FIRSTNAME"].ToString().ToLower() && textBox2.Text == dt.Rows[i]["LASTNAME"].ToString().ToLower())
{
found = true;
break;
}
}
if (found)
{
Main ss = new Main(); // Main is the another form which is seen after the successful enterance.
ss.Show();
}
else
{
MessageBox.Show("UserName or Password is Wrong");
}
You can change this to Linq:
if (dt.AsEnumerable().Any( // Check if there is any row meeting criteria
r => r.RowState != DataRowState.Deleted && // row should not be deleted
r.Field<string>("FIRSTNAME").Equals(textBox1.Text, StringComparison.CurrentCultureIgnoreCase) && // First name matches ignoring case
r.Field<string>("LASTNAME").Equals(textBox2.Text, StringComparison.CurrentCultureIgnoreCase))) // Last name matches ignoring case
{
Main ss = new Main(); // Main is the another form which is seen after the successful enterance.
ss.Show();
}
else
{
MessageBox.Show("UserName or Password is Wrong");
}

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

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.

How to take several numbers inputted from one textbox and add them together?

I know my question may be strange but I want to know. I'm building a program that does inventory. The user inputs numbers from their inventory list for several items in different textboxes and the program stores each input from the textboxes, when the add button is clicked. Then when the user done input numbers from the list. They click a button and it generated an excel file with all the numbers from the textboxes added up. So, far I have the final button event done and the input part done but I'm having trouble getting the inputs from one textbox to stores each one and add all of them up. I have try different method but I can't seem to get it.
My code:
int ALPTotal = 0;
int memory = 0;
private void btnSubmit_Click(object sender, EventArgs e)
{
if (txtALP.Text == "")
{
txtALP.Text = "0";
}
if (txtBookP.Text == "")
{
txtBookP.Text = "0";
}
string ALP2 = txtALP.Text;
int ALP = Convert.ToInt32(ALP2);
string BookP2 = txtBookP.Text;
int BookP = Convert.ToInt32(BookP2);
if (ALP >= 150)
{
MessageBox.Show("Please enter 150 or less", "Item Entered", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (BookP >= 150)
{
MessageBox.Show("Please enter 150 or less", "Item Entered", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
}
if (memory == 0)
{
memory = ALP;
}
else if (memory == ALP)
{
ALPTotal = memory + ALP + ALP;
MessageBox.Show("Information Added", "Added to List", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtALP.Clear();
txtBookP.Clear();
}
}
private void btnClearCells_Click(object sender, EventArgs e)
{
Excel.Application App;
Excel.Workbook workbook;
Excel.Worksheet worksheet;
App = new Excel.Application();
workbook = App.Workbooks.Add();
worksheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1);
worksheet.Cells[3, 2] = ALPTotal;
worksheet.Cells[4, 2] = txtBookP.Text;
}
}
Also the program should only be able to take up to 100 inputs from each textbox. So, the user shouldn't be able to add more than 100 inputs numbers from each textbox in the program.
So, after trying many different ways and methods, I would like to know: is what I'm asking possible or is it impossible?
P.S. - If more information is needed in order to come up with an answer. Please let me know and I will post more information. Thanks
UPDATE I forget to mention earlier that the "btnSubmit_Click" is the add button method and the "btnClearCells_Click" is the Submit/Total button method. Also I added an example of what I want to do in the comments. If anyone not sure what I'm asking here
FINAL UPDATE My case is now closed. I have solve my problem and the answer can be seen below. Thanks to everyone who helped!
I found out my answer. I was reading an question from Stackoverflow.com about "How to sum any amount of user inputted numbers". All I had to do was do add an:
memory = ALP;
ALPTotal += memory;
Once I added this change to my code and tested it. My program did what I wanted.
Also thanks to finding my answer, I don't need the 100 user input limit anymore because I thought at first I needed it because I thought I had to do
ALPTotal = memory + ALP + ALP + // ALP (97 more times)
to get my wanted results but I don't. So, I would like to thank everyone who try to help me solve my problem. Thank you so much.

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