简体   繁体   中英

Adding new Row [at RunTime] in DataGridView replaces the previous added Row

I want (When Button Clicked) previous row still exist in datagridview while adding new row (such that user can add as many rows as he/she want at runtime in datagridview).

I found many questions on stackoverflow.com regarding rows of datagridview but i cannot figure out them according to my problem. Second, i am new in Dapper and all answers using ADO.NET.

I have an idea that there should be an easy way of such problem.

I bind my datagridview to Orders Class.

Here is my Orders class...

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

Select Button Click Event is..

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

        }
    }

When I enter ItemName as 'bread' then GUI is..

当输入ItemName作为“面包”时

But when I enter ItemName as 'bjn' then first row replaces with newest row..

当输入ItemName作为'bjn'时

The main reason behind your problem lies within your button click event handler , You are binding DataSource every time the user clicks the button which gives you one record as expected. Instead of assigning DataSource , write a insert statement which inserts record within your grid. By doing this, your issue will be surely resolved.

I'm not giving solution with code because I don't have my pc right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM