【问题标题】:Adding new Row [at RunTime] in DataGridView replaces the previous added Row在 DataGridView [at RunTime] 中添加新行替换之前添加的行
【发布时间】:2017-10-16 01:31:41
【问题描述】:

我希望(单击按钮时)前一行仍然存在于 datagridview 中,同时添加新行(这样用户可以在运行时在 datagridview 中添加任意数量的行)。

我在stackoverflow.com 上发现了很多关于datagridview 行的问题,但我无法根据我的问题弄清楚它们。其次,我是 Dapper 的新手,所有答案都使用 ADO.NET。

我有一个想法,应该有一个简单的方法来解决这个问题。

我将我的 datagridview 绑定到 Orders 类。

这是我的 Orders 类...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    public class Orders
    {
        public int    ItemId      { get; set; }
        public string ItemName    { get; set; }
        public string Brand       { get; set; }
        public string Category    { get; set; }
        public int    Quantity    { get; set; }
        public int    Price       { get; set; }
    }
}

选择按钮点击事件是..

private void btn_select_Click(object sender, EventArgs e)
    {

        using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
        {
            if (db.State == ConnectionState.Closed)
                db.Open();
            string query = "SELECT *FROM tbl_ItemDetail WHERE ItemName=@ItemName";
            ordersBindingSource.DataSource = db.Query<Orders>(query, new { ItemName = txt_sell_item.Text });

        }
    }

当我输入 ItemName 作为“面包”时,GUI 是..

但是当我将 ItemName 输入为 'bjn' 时,第一行将替换为最新行..

【问题讨论】:

    标签: c# sql-server winforms dapper


    【解决方案1】:

    您的问题背后的主要原因在于您的button click event handler,每次用户单击按预期为您提供一条记录的按钮时,您都会绑定DataSource。不要分配DataSource,而是编写一个插入语句,在您的网格中插入记录。这样做,您的问题一定会得到解决。

    我没有提供代码解决方案,因为我现在没有电脑。

    【讨论】:

    • 我的应用程序要求我应该使用 DataSource。
    • 您的DataSource的使用在您的点击内无效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 2020-02-01
    • 1970-01-01
    相关资源
    最近更新 更多