Gridview尝试添加新记录时删除先前的记录

时间:2019-03-22 07:53:00

标签: c# winforms datagridview

我有1个带有1个文本框的Windows窗体,用户将在其中键入ProductId,然后按Enter键,然后基于该窗口我想将记录添加到我的gridview中。

现在的问题是,当我搜索新产品ID时,旧记录会被删除,因此基于上一次搜索,我的网格视图中始终只有1条记录。

因此,例如:如果用户首次搜索产品ID = 1,则将其添加到网格。现在,当用户尝试添加另一个产品产品ID = 2时id = 1已删除,现在我在gridview中仅看到Product ID = 2记录

代码:

public partial class ProductScan : Form
{
    private BindingSource grdProductListBindingSource = new BindingSource();
    public ProductScan()
    {
        InitializeComponent();
    }

    private void ProductScan_Load(object sender, EventArgs e)
    {
        grdProductList.DataSource =  grdProductListBindingSource;
    }

    private void txtProductId_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            string pathName = txtFilePath.Text;
            string fileName = System.IO.Path.GetFileNameWithoutExtension(txtFilePath.Text);
            DataTable tbContainer = new DataTable();
            string strConn = string.Empty;
            string sheetName = fileName;

            FileInfo file = new FileInfo(pathName);
            if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
            string extension = file.Extension;

            switch (extension)
            {
                case ".xls":
                        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                        break;
                case ".xlsx":
                        strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                        break;
                default:
                        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                        break;
            }
            string fieldSelector = "[ProductID], [ProductName], [MRP] ";
            string query = $"SELECT {fieldSelector} FROM [{sheetName}$A1:F15535] WHERE [ProductID] = {Convert.ToInt32(txtProductId.Text)}";
            using (OleDbConnection cnnxls = new OleDbConnection(strConn))
                using (OleDbDataAdapter oda = new OleDbDataAdapter(query, cnnxls))
                {
                    oda.Fill(tbContainer);
                    grdProductListBindingSource.DataSource = tbContainer;
                    grdProductList.AutoResizeColumns(
                            DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
                }
            e.Handled = true;
        }
    }

我已从此处引用:https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-bind-data-to-the-windows-forms-datagridview-control

这是什么问题?

0 个答案:

没有答案