在使用else之前我可以使用两次吗? [英] Can I use If twice before using else?

查看:110
本文介绍了在使用else之前我可以使用两次吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题对你来说可能有点愚蠢,但我是C#编程的初学者。我真的不知道在谷歌搜索什么。我的代码存在这个问题:

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:

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!");
           }



使用2 ifs后我似乎无法使用else。我该怎么办?当我点击按钮时,它确实显示交易没有足够的付款,但它仍然将数据保存到数据库。


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.

推荐答案

哦,好悲伤...

要做的第一件事就是弄清楚你的缩进,这样你就可以看到它在哪里。这很简单:在VS中,按住CTRL并按K然后按D.如果没有任何反应,请先修复编译错误,然后重新执行。但是......如果没有首先认真思考,这是行不通的。

你有一个foreach循环工作 dataGridView2.Rows 遍历每一行。在循环中,您使用:

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:
this.dataGridView2.Rows.Clear();

这是不允许的 - 您无法更改在其上运行的循环内的任何内容列表!



我建议你做很多事情:

1)备份这个版本。

2)扔掉它。这是混乱,错误和严重的瘫痪,并显示太多被黑客攻击的迹象,因为它不起作用,但几乎......

3)重新开始,并以模块化方式进行。

3.1)停止使用 Convert.ToDouble 来读取文本框值。如果您的用户犯了一个小错误,您的程序将崩溃。相反,要么使用NumericUpDown控件,它不会让它们出错并直接提供值,或者使用Double.TryParse。这将返回它工作/它没有工作bool所以你可以向你的用户报告问题而不是崩溃。

3.2)改变你的初始如果:

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:

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;
    }

现在你的其余代码根本不用担心坏的值。

3.3)添加循环,但不要填写它 - 只留下占位符的内容:

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:

foreach (DataGridViewRow data in dataGridView2.Rows)
    {
    if (!data.IsNewRow)
        {
        //TODO: Save rows
        }
    }



3.4)循环后,根据需要清除数据,准备下次。


3.4) After the loop, clear out the data as required ready for next time.

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();



现在编译它。修复任何错误。

现在你准备好处理你留下的内部位:如果你只是看它就很简单。

我不会去现在为你做这件事 - 我想让你考虑一下,先把一些东西分开(毕竟这是你的功课!)

但是有几点指示:

1)您正在为某些值使用参数。那么你决定连接真正危险的字符串到底是什么?永远不要将文本框内容连接到SQL命令 - 这是引入SQL注入攻击并销毁数据库的最简单方法。

2)为什么INSERT命令会返回任何记录?那么你需要一个SqlDataReader呢?你需要使用ExecuteReader吗?或者有更好的方法吗?

3)请不要混合使用变量样式,也不要缩写名称。将textBox1,textBox2,dataGridView1等更改为描述它们所做的名称...使用camelCase而不是下划线 - 它应该在C#应用程序中使用!



尝试那个地段,看看你得到了什么:然后告诉我,我们会继续前进,好吗?


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?


你可以在两个ifs之后使用else。获得正确的括号非常重要,这些将决定其他ifs适用于哪个*。



您粘贴的代码无效。它包含13个开口括号{,只有9个闭括号} - 因此无法正确查看问题。



*这实际上是一个非常有趣的计算机方面语言设计,以及几乎所有语言都偏离纯粹的明确语法的情况。



按惯例,代码:

如果

如果

else



会将else关联到最内层if。但是,数学语法没有明确地定义这一点,任何一种解释都同样有效。
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.


这篇关于在使用else之前我可以使用两次吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆