在DataGridView中添加新行[在运行时]替换以前添加的行

问题描述:

我希望(按下按钮时)前一行仍然存在于datagridview中,同时添加新行(这样用户可以在运行时添加尽可能多的行在datagridview中)。在DataGridView中添加新行[在运行时]替换以前添加的行

我在*.com上发现了很多关于datagridview行的问题,但是根据我的问题我找不出来。其次,我是Dapper的新手,并且使用ADO.NET的所有答案。

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

我将我的datagridview绑定到订单类。

这里是我的订单班...

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; } 
    } 
} 

选择按钮的Click事件是..

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 [email protected]"; 
      ordersBindingSource.DataSource = db.Query<Orders>(query, new { ItemName = txt_sell_item.Text }); 

     } 
    } 

当我进入ITEMNAME为 '面包',那么GUI是..

When enter ItemName as 'bread'

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

When enter ItemName as 'bjn'

您的问题背后的主要原因在于你button click event handler内,你每次用户点击它给你一个创纪录的预期按钮时结合DataSource。而不是分配DataSource,写一个插入语句插入记录在您的网格。通过这样做,你的问题肯定会得到解决。

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

+0

这是我的应用程序的要求,我应该使用数据源。 –

+0

您的'DataSource'在您的点击中无效。 –