添加数据表行和列并更新datagridview

时间:2014-03-15 16:25:36

标签: c# database

            string conString = "Server=192.168.1.100;Database=product;Uid=newuser;Pwd=password";
            MySqlConnection conn = new MySqlConnection(conString);
            DataTable dt = new DataTable();
            DataRow row = dt.NewRow();
            conn.Open();
            //cmd = conn.CreateCommand();
            //cmd.CommandText = "Select * From tblindividualproduct";
            if (e.KeyCode == Keys.Enter)
            {
                if (txtBarcode.Text == "")
                {
                    MessageBox.Show("Please Fill the correct ProductID");
                }
                else
                {
                    string sql = "Select * From tblindividualproduct where ProductID = @ProductIdText";

                    using (var adapt = new MySqlDataAdapter(sql, conn))
                    using (var cmd = new MySqlCommandBuilder(adapt)) //Not sure what you need this for unless you are going to update the database later.
                    {
                        adapt.SelectCommand.Parameters.AddWithValue("@ProductIdText", txtBarcode.Text);
                        BindingSource bs = new BindingSource();
                        adapt.Fill(dt);
                        bs.DataSource = dt;
                        dgItems.ReadOnly = true;
                        dgItems.DataSource = bs;
                    }
                }
            }

如何添加结果,而不仅仅是替换最后的结果。这是所要求的整个代码。我只是不知道它是否需要手动添加行或有一个简单的方法来实现它。提前谢谢

1 个答案:

答案 0 :(得分:1)

首先,您应该使用Parameterized SQL to avoid SQL Injection

然后你只需要将你拥有的代码放在某种事件处理程序中。我认为用户可能会点击输入键或TextBox中的某些内容。

只要您不清除DataTable,它就会在每次运行查询时不断添加行。如果您想在代码中的其他位置清除表格,请拨打dt.Clear()

这样的东西应该得到你想要的东西,并且注射安全:

    private void txtBarCode_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            if(String.IsNullOrEmpty(txtBarcode.Text)) 
            {
                MessageBox.Show("Please Fill the correct ProductID");
            } 
            else 
            {
                 string sql = "Select * From tblindividualproduct where ProductID = @ProductIdText";

                 using (var adapt = new MySqlDataAdapter(sql, conn))
                 using (var cmd = new MySqlCommandBuilder(adapt)) //Not sure what you need this for unless you are going to update the database later.
                 {
                     adapt.SelectCommand.Parameters.AddWithValue("@ProductIdText", txtBarCode.Text);
                     BindingSource bs = new BindingSource();
                     adapt.Fill(dt);
                     bs.DataSource = dt;
                     dgItems.ReadOnly = true;
                     dgItems.DataSource = bs;
                 }
            }
        }
    }

然后确保您已将此活动附加到TextBoxForm中的this.txtBarCode.KeyUP += txtBarCode_KeyUp; ,如下所示:

DataGridView

现在,当用户在框中输入并按下输入时,查询将运行,结果将显示在adapt.Fill(dt);中。无需手动添加列和行,{{1}}将为您执行此操作。