Click here to Skip to main content
15,883,901 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
My question may be a little stupid for you, but I'm a beginner at C# programming. I don't really know what to search on google. I have this problem with my code:
C#
private void button2_Click_1(object sender, EventArgs e)
       {
           double amtpd, ttalamt, change;

           amtpd = Convert.ToDouble(pos_amtpd.Text);
           ttalamt = Convert.ToDouble(txtTotalAmt.Text);

           if (amtpd >= ttalamt)
           {
               change = amtpd - ttalamt;

               pos_chnge.Text = Convert.ToString(change);

                SqlConnection conn = new SqlConnection(@"server =.\SQLEXPRESS; database = database; Trusted_Connection = yes");
           conn.Open();

           foreach (DataGridViewRow data in dataGridView2.Rows)
           {
               if (!data.IsNewRow)
           {
               using (SqlCommand cmd = new SqlCommand("INSERT INTO Invoice (StockCode, Descr, Price, Qty, TotalAmt, AmtPaid, Date, Time, Cashier) VALUES(@c0,@c1,@c2,@c3,@c4, '" + this.pos_amtpd.Text + "', '" + Date.Value.Date + "', '" + Time.Value.TimeOfDay + "', '" + this.pos_cshr.Text + "')", conn))
               {

                   cmd.Parameters.AddWithValue("@C0", data.Cells[0].Value);
                   cmd.Parameters.AddWithValue("@C1", data.Cells[1].Value);
                   cmd.Parameters.AddWithValue("@C2", data.Cells[2].Value);
                   cmd.Parameters.AddWithValue("@C3", data.Cells[3].Value);
                   cmd.Parameters.AddWithValue("@C4", data.Cells[4].Value);

                   SqlDataReader myReader;

                   try
                   {
                       myReader = cmd.ExecuteReader();
                       MessageBox.Show("Transaction Saved!");
                       pos_amtpd.Clear();
                   pos_chnge.Clear();
                   txtTotalAmt.Clear();
                   textBox1.Clear();
                   textBox2.Clear();
                   textBox3.Clear();
                   textBox5.Clear();
                   srch_prdcod.Clear();
                   srch_prddesc.Clear();
                   this.dataGridView1.DataSource = null;
                   this.dataGridView1.Rows.Clear();
                   this.dataGridView2.Rows.Clear();

                   while (myReader.Read())
                   {
                   }
               }

               catch (Exception ex)
               {
                   MessageBox.Show(ex.Message);

               }

               {
                   StringBuilder MessageText = new StringBuilder();
                   MessageText.AppendLine(string.Format("Product Code: {0}", textBox1.Text));
                   MessageText.AppendLine(string.Format("Product Name: {0}", textBox2.Text));
                   MessageText.AppendLine(string.Format("Price: {0}", textBox3.Text));
                   MessageBox.Show(MessageText.ToString());

               }
           }
           else
           {
               MessageBox.Show("Insufficient payment!");
           }

I can't seem to use the else after using 2 ifs. What should I do? When I click the button, it does show that the transaction has insufficient payment but it still saves data to the db.
Posted
Updated 19-Oct-13 20:52pm
v3
Comments
StM0n 20-Oct-13 3:30am    
Try to strip your code down to the essential parts... from the first look it seems some of the brackets don't fit.

Oh, good grief...
The first thing to do is sort out your indentation, so you can see what goes where. That's pretty easy: in VS, hold down CTRL and press K then D. If nothing happens, fix your compilation errors first, then do it again. But... this isn't going to work without some serious thinking on your part first.
You have a foreach loop working on dataGridView2.Rows to loop through each row. Inside the loop, you use:
C#
this.dataGridView2.Rows.Clear();
Which is not allowed - you can't change a list of anything inside a loop which is running on it!

What I would suggest is that you do a number of things:
1) Back up this version.
2) Throw it away. It's confused, wrong and badly layid out, and shows too many signs of being hacked because it didn't quite work, but nearly...
3) Start again, and do it in a modular fashion.
3.1) Stop using Convert.ToDouble to read your textbox values. If your user makes a tiny mistake, your program will crash. Instead, either use a NumericUpDown control which won't let them make a mistake and provides a value directly, or use Double.TryParse instead. That will return a "It worked" / "it didn't work" bool so you can report problems to your user instead of crashing.
3.2) Change your initial if:
C#
double amtpd, ttalamt, change;
if (!Double.TryParse(pos_amtpd.Text, out amtpd) || !Double.TryParse(txtTotalAmt.Text, out ttalamt))
    {
    MessageBox.Show("Please enter numbers!");
    return;
    }
if (amtpd < ttalamt)
    {
    MessageBox.Show("Insufficient payment!");
    return;
    }
Now the rest of your code doesn't have to worry about bad values at all.
3.3) Add your loop, but don't fill it in yet - just leave placeholders for the content:
C#
foreach (DataGridViewRow data in dataGridView2.Rows)
    {
    if (!data.IsNewRow)
        {
        //TODO: Save rows
        }
    }

3.4) After the loop, clear out the data as required ready for next time.
C#
MessageBox.Show("Transaction Saved!");
pos_amtpd.Clear();
pos_chnge.Clear();
txtTotalAmt.Clear();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox5.Clear();
srch_prdcod.Clear();
srch_prddesc.Clear();
dataGridView1.DataSource = null;
dataGridView1.Rows.Clear();
dataGridView2.Rows.Clear();

Now compile it. Fix any errors.
Now you are ready to work on the inner bit you left: which is pretty simple, if you just look at it.
I'm not going to do it for you now - I want you to think about it, and sort a few things out first (it's your homework, after all!)
But a couple of pointers:
1) You are correctly using parameters for some of your values. So what the heck did you decide to concatenate strings for the really dangerous ones? Never, ever concatenate textbox contents into SQL commands - it is the easiest way to introduce an SQL Injection attack and destroy your database.
2) Why would an INSERT command return any records? So what do you need an SqlDataReader for? Do you need to use ExecuteReader? Or is there a better method?
3) Please don't mix variable styles, and don't abbreviate names. Change your textBox1, textBox2, dataGridView1, etc. to names which describe what they do... Use camelCase instead of underlines - it is expected in C# applications!

Try that lot, and see where you get: then show me and we'll move on a bit, OK?
 
Share this answer
 
You can use else after two ifs. It's really important to get the braces correct, these will determine which of the ifs the else applies to*.

The code you have pasted is invalid. It contains 13 open braces {, and only 9 close braces } - so it is impossible to properly see the problem.

* This is actually a really interesting facet of computer language design, and the one case where nearly all languages deviate from a pure unambiguous grammar.

By convention, the code:
if
if
else

will associate the else with the inner most if. However, the mathematical grammar does not explicitly define this, and either interpretation would be equally valid.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900