简体   繁体   中英

C# Winform DataGridView inline add New row

I want to add a new item into my datagridview. I know can achieve this using several TextBoxes and a Button. When the user clicks this button, it will add a new item into database and refresh my datagridview.

I wonder if I can use the last row of my datagridview to add a new item. How can I do that?

did you use the RAD-Databind (DataSource on your winforms)? If so it might be a bit tricky. You should load the data in a seperate layer (not in the code-behind if you can help it). Then it should be rather simple to add another row into your local data.

As you asked: here is a very simple sample. I use same generic data:

public struct SimpleData
{
    public int Id { get; set; }
    public string Text { get; set; }
}

And initialize a DataGridView named GridView via:

        var bindingSource = new BindingSource();
        bindingSource.Add(new SimpleData {Id = 1, Text = "Hello"});
        bindingSource.Add(new SimpleData {Id = 2, Text = "World"});
        GridView.DataSource = bindingSource;

then you can add another row simply by

        var data = GridView.DataSource as BindingSource;
        data.Add(new SimpleData{Id=3, Text="!!! added"});

In a real world example I would use some well known pattern: MVVM for Winforms or MVP for Winforms do seperate the View from the logic. But after all the important bit is using some kind of Bindingsource (that informs the Grid that data has changed) or reassing the changed data to the DataSource if you choose to use a shallow/simple datacontainer like List or similar.

Or,

You could bind your DataGridView to a Generic.List of WrapperObject (or whatever you want to call the class), where each instance of WrapperObject can either represent one of the records already in the database and expose its properties, or represent a 'blank record'.

In the EditingControlShowing event handler for the DataGridView, you can determine whether the user is typing over the last row (as it is the only row which contains the blank part) and do whatever you need to do to add a part to the database.

When you want to update the contents on the DataGridView, simply re-create a new list of WrapperObjects from the records you want to display, and add one to represent the blank record at the end, so it will show up at the bottom, then set the DataGridView's datasource to the new list.

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