如何将新行追加到datagridview并保留现有行?

时间:2017-12-26 05:34:57

标签: c# datagridview

我有实验室请求窗口,我可以稍后创建新请求,有时我需要更新此订单我做了更新窗口,我在datagrid视图中从数据库中读取订单详细信息,我需要添加新项目到datagridview,但是当我添加新行时删除现有行的错误并添加新行我的代码错误是什么,我正在添加新行。 如何添加新行并保留现有行,还要在按Enter键之前检查附加文件datagridview图像,然后在输入其添加新行后删除datagridview1图像并删除从数据库中提取的现有行。

private void textAmount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && textQty.Text != string.Empty && textAmount.Text != string.Empty)
            {
                if (chkcash1.Checked == true)
                {
                    textDiscount.Focus();
                }
                if (chkcash1.Checked == false)
                {
                    for (int i = 0; i < TestsDataGrid.Rows.Count - 1; i++)
                    {
                        if (TestsDataGrid.Rows[i].Cells[0].Value.ToString() == textTestId.Text)
                        {
                            MessageBox.Show("This test added already ", "Duplicate Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                    }
                    DataRow r = dt.NewRow();
                    r[0] = textTestId.Text;
                    r[1] = textName.Text;
                    r[2] = textPrice.Text;
                    r[3] = textQty.Text;
                    r[4] = textAmount.Text;
                    r[5] = textTotal.Text;


                    dt.Rows.Add(r);
                    TestsDataGrid.DataSource = dt;
                    textTestId.Clear();
                    textName.Clear();
                    textPrice.Clear();
                    textAmount.Clear();
                    textTotal.Clear();
                    btnSearch.Focus();

                    textOrderTotal.Text = (from DataGridViewRow row in TestsDataGrid.Rows
                                           where row.Cells[4].FormattedValue.ToString() != string.Empty
                                           select Convert.ToDouble(row.Cells[4].FormattedValue)).Sum().ToString();
                }[datagridviewimage][1]

2 个答案:

答案 0 :(得分:0)

这可能会有所帮助,这是一个简单的例子:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using System.Data.OleDb;

namespace Practice
{
    public partial class Form1 : Form
    {
        private DataTable retdt;
        SqlCeDataAdapter da;
        SqlCeCommandBuilder cbuild;
        SqlCeConnection con;
        public Form1()
        {
            InitializeComponent();
            fetchData();
        }
        private void fetchData()
        {
            retdt = new DataTable();
            SqlCeConnection con = null;
            try
            {
                con = new SqlCeConnection(@"Data Source=c:\users\mswami\documents\visual studio 2010\Projects\Practice\Practice\practice.sdf");
                da = new SqlCeDataAdapter();
                da.SelectCommand = new SqlCeCommand("select uid,amount from TestTable", con);
                cbuild = new SqlCeCommandBuilder(da);
                con.Open();
                da.Fill(retdt);
                DGPractice.DataSource = retdt.DefaultView;
                DGPractice.BindingContext = this.BindingContext;
            }
            catch (Exception exce)
            {
                MessageBox.Show(exce.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (maskedTextBox1.Text.Length > 0)
            {
                if (retdt.Select("amount=" + maskedTextBox1.Text).Length == 0)
                {
                    DataRow drow = retdt.NewRow();
                    // drow[0] left blank as it is primary key column with auto increment value
                    drow[1] = Math.Round(Double.Parse(maskedTextBox1.Text),2);
                    retdt.Rows.Add(drow);

                    //Update changes into database table
                    // First process deletes.  
                    da.Update(retdt.Select(null, null, DataViewRowState.Deleted));

                    // Next process updates.  
                    da.Update(retdt.Select(null, null,
                      DataViewRowState.ModifiedCurrent));

                    // Finally, process inserts.  
                    da.Update(retdt.Select(null, null, DataViewRowState.Added));

                    DGPractice.DataSource = null;
                    DGPractice.DataSource = retdt.DefaultView;
                    DGPractice.BindingContext = this.BindingContext;
                }
                else
                {
                    MessageBox.Show("Duplicate amount");
                }
            }
        }
    }

}

Preview

designer.cs代码(对于DataGrid列定义和绑定属性)

 // DGPractice
// 
this.DGPractice.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DGPractice.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.UID,
this.amtField});
this.DGPractice.Location = new System.Drawing.Point(2, 63);
this.DGPractice.Name = "DGPractice";
this.DGPractice.RowHeadersVisible = false;
this.DGPractice.Size = new System.Drawing.Size(373, 196);
this.DGPractice.TabIndex = 0;
// 
// UID
// 
this.UID.DataPropertyName = "uid";
this.UID.HeaderText = "UID";
this.UID.Name = "UID";
// 
// amtField
// 
this.amtField.DataPropertyName = "amount";
this.amtField.HeaderText = "Amount";
this.amtField.Name = "amtField";
  

DataPropertyName应与select name(表字段名称)中的字段名相同。

答案 1 :(得分:0)

谢谢你,Maddy解决了我的错误,它没有将数据保存在datagrid视图中,因为我从存储过程中读取并且在获取到数据表后没有保存数据

da.Fill(retdt);
DGPractice.DataSource = retdt.DefaultView;
DGPractice.BindingContext = this.BindingContext;