【问题标题】:My code is not working after dataGridView1.Rows.Clear() until end我的代码在 dataGridView1.Rows.Clear() 之后直到结束都不起作用
【发布时间】:2020-06-04 15:32:08
【问题描述】:

我的代码没有像我预期的那样工作,我把问题放在最后几天,但我只在 2 天后检查过,我想我的机会已经被回答了。如果那是错误的,我第二次被问到对不起。

我的 Visual Studio Pro 对我的代码进行了奇怪的处理。没有断开循环的错误消息。看来我放弃检查我的销售点项目的所有文件有什么问题。

我已经给了 updateb() 和 invoice()。所以最好像我的特定文件中的所有代码一样。就这样吧。

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace superpos3
{
    public partial class salesn : Form
    {
        public salesn()
        {
            InitializeComponent();
        }

       public static int totalPrice = 0;
        public static int payment = 0;
        public static int balance = 0;

        MySqlConnection con = new MySqlConnection("server= localhost; database =superpos;  username= root; password=; ");


        public void invoice()
        {

            con.Open();
            string query = "select max(id) from salesmain ";
            MySqlCommand cmd2 = new MySqlCommand(query, con);
            MySqlDataReader dr;
            dr = cmd2.ExecuteReader();
            if (dr.Read())
            {
                string val = dr[0].ToString();
                if (val == "")
                {
                    lbinvoice.Text = "1";

                }
                else
                {
                    int a;

                    a = int.Parse(dr[0].ToString());
                    a = a + 1;
                    lbinvoice.Text = a.ToString();



                }
                con.Close();
            }

        }





        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtno_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtqty.Enabled = true;
                txtqty.Focus();
            }
        }

        private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {

                try
                {

                    string txt = "select * from products where id='" + txtno.Text + "'";
                    MySqlCommand cmd = new MySqlCommand(txt, con);
                    con.Open();
                    MySqlDataReader r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        int price = int.Parse(txtqty.Text.ToString()) * int.Parse(r[4].ToString());
                        totalPrice = totalPrice + price;
                        //discount
                        // totalPrice = totalPrice - totalPrice* Payment.discount/100;

                        dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);

                    }
                    lbitems.Text = " " + (dataGridView1.RowCount - 1) + "";
                    lbtotal.Text = " " + totalPrice + " ";

                    con.Close();

                }






                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "Error From Database");
                }

                txtno.Focus();
                txtno.Clear();

                txtqty.Enabled = false;
                txtqty.Clear();

            }

        }


        private void txtqty_TextChanged(object sender, EventArgs e)
        {

        }
        private string name;

        public string Staffname
        {
            get { return name; }
            set { name = value; }

        }



      public void updatedb()
        {

            for (int row = 0; row < dataGridView1.Rows.Count; row++)
            {


                string itmno = dataGridView1.Rows[row].Cells[1].Value.ToString();
                string itmqty = dataGridView1.Rows[row].Cells[3].Value.ToString();

                string t = "select * from products where id= '"+ itmno + "'";

                string oldqty = "", newqty = "";


                Connnew.DbSearch(t);


                while (Connnew.dr.Read())
                {

                    oldqty = Connnew.dr[5].ToString();
                    newqty = (int.Parse(oldqty) - int.Parse(itmqty)).ToString();
                }

                string t2 = "update products SET qty = '" + newqty + "' WHERE id = '" + itmno + "'";
                //t2 = t2.Replace("{0}", itmno);
                //t2 = t2.Replace("{2}", newqty);
                Connnew.DbUpdate(t2);
            }


        }


        private void salesn_Load(object sender, EventArgs e)
        {
            label6.Text = Staffname;
            lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            lbltime.Text = DateTime.Now.ToShortTimeString();

            invoice();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);


                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                   int x = cmd.ExecuteNonQuery();
                   int y = cmd1.ExecuteNonQuery();

                    MessageBox.Show("Record added ..........");
                    updatedb();

             //until here everything worked fine but if additionally given below codes not wroking 
               even the updatedb().

                    dataGridView1.Rows.Clear();
                    lbtotal.Text = "0";
                    lbitems.Text = "0";
                    txtno.Focus();
                    totalPrice = 0;

                    con.Close();
                    invoice();

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

            finally
            {
                con.Close();
            }
           }

        private void button2_Click(object sender, EventArgs e)
        {
            pay p = new pay();
            p.Show();
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }
    }   
}

我看到一切都很好,但仍然没有找到问题。

和上面与 Connnew.DbSearch(t) 相关的连接,“Connnew”是这样的:

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace superpos3
{
    class Connnew
    {

        public static MySqlConnection con = new MySqlConnection("server= localhost; database =superpos; username= root; password=; ");
        public static MySqlCommand poscmd = new MySqlCommand();
        public static MySqlDataReader dr;

        public static void DbSearch(string txt)
        {

            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            dr = poscmd.ExecuteReader();
        }

        public static void DbUpdate(string txt)
        {
            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            poscmd.ExecuteNonQuery();
        }
    }
}

我无法完整显示图片截图或者这里没有任何权限。请点击以下链接。

please watch the sales window here

then please watch this one to know whats not work

请让我知道这里的代码结构问题或真正出了什么问题......(这个问题已经结束并在下面更新了我的问题)

我检查了除了 form1.cs 文件之外的所有文件都与这里的问题无关。所以另外在这里:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace superpos3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            progressBar1.Value = progressBar1.Value + 1;
            if (progressBar1.Value >= 100)
            {
                Login In = new Login();
                this.Hide();
                In.Show();

                timer1.Enabled = true;
                progressBar1.Visible = false;
                timer1.Enabled = false;
            }
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }
    }
}

【问题讨论】:

  • 定义“不工作”。那里有一堆代码,没有问题
  • 如果问题在标题中,那么也添加xml代码
  • 你的 catch 块什么都不做。删除它或放置一个断点以查看是否有任何异常!
  • 重复stackoverflow.com/questions/62117741/…请不要多次打开同一个问题,它可能会被关闭,因为它违反了stackoverflow.com/help/duplicates的规则,而是尝试更新/增强您的原始问题
  • 好的,我知道了。我在想没有人看到我的帖子,因为我过了几天没有回答。非常明白!谢谢!

标签: c# .net visual-studio


【解决方案1】:

我刚刚删除了 catch 块并在下面一行看到了这个错误。

`string itmno = `dataGridView1.Rows[row].Cells[1].Value.ToString();` 

The error is:System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=superpos3
  StackTrace:
   at superpos3.salesn.updatedb() in D:\superpos3\superpos3\superpos3\salesn.cs:line 174
   at superpos3.salesn.button1_Click(Object sender, EventArgs e) in D:\superpos3\superpos3\superpos3\salesn.cs:line 258
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at superpos3.Program.Main() in D:\superpos3\superpos3\superpos3\Program.cs:line 19

对不起,我错过了这里的信息: Please watch the sales window here

then please watch this one to know whats not work

【讨论】:

  • 这是你的答案吗?如果这是对您的问题的更新,请更新问题! stackoverflow.com/help/privileges/edit
  • 感谢链接!对不起,我想让你知道你说什么来移除 catch 块。那么我添加另一个问题来添加另一个答案!所以我不知道这是一个问题或答案。请让我知道什么是更好的解决方案。
  • 根据我的测试,我建议你放置dataGridView1.Rows.Clear();在 for 循环之外。因为会清除所有的datagridview,所以可能会导致变量itmno为null。此外,如果您想更好地解决您的问题,最好将您的项目上传到这里。
  • 我已经更新了问题。所以我看到循环内部没有变量。但是,请您修改任何答案吗?而且我检查了我所有的文件,只发现与项目的有用连接只有 form1.cs 文件,错误消息在 (form mainForm) 的第 19 行。
  • @BilguunEnkhee,我建议你删除 updatedb 方法中的 for 语句,因为 updatedb 方法已经在 for 语句中。
【解决方案2】:

一般建议。请考虑在许多地方更改代码。并且不要将 MySqlConnection 包装到对象中,因为它已经是面向对象的。 您不应该像这样在每次迭代中添加参数和打开连接:

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);


                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();

如果应该这样做:

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = con;
                con.Open();

                cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                MySqlCommand cmd1 = new MySqlCommand();
                cmd1.Connection = con;
                cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";

                cmd.Parameters.Add ("@saleid", SqlDbType.Int);
                cmd.Parameters.Add ("@productname", SqlDbType.String);
                cmd.Parameters.Add ("@qty", ...);
                cmd.Parameters.Add ("@grosstotal", ...);


                cmd1.Parameters.Add("@id", ...);
                cmd1.Parameters.Add("@date", ...);
                cmd1.Parameters.Add("@time", ...);
                cmd1.Parameters.Add("@cashername", ...);
                cmd1.Parameters.Add("@qty", ...);



                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    cmd.Parameters["@saleid"] = lbinvoice.Text;
                    cmd.Parameters["@productname"] = dataGridView1.Rows[i].Cells[2].Value;
                    cmd.Parameters["@qty"] = dataGridView1.Rows[i].Cells[3].Value;
                ....
                }
                con.Close();

还可以考虑在程序开始时只打开一次连接,在结束时只关闭一次。

【讨论】:

    【解决方案3】:

    exception unhandled error message --> please click

    当 updateb() 方法中的 for 循环内部时,窗口显示如上图。 我正在寻找如何在 button1_Click void 内部或外部使用 updateb() 方法。因此,请通过代码示例为我提供最佳答案。或者如果询问一些代码或不清楚的信息,请告诉我。

    【讨论】:

      猜你喜欢
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      相关资源
      最近更新 更多