C# Winform DataGridView inline add New row

谁说我不能喝 提交于 2019-12-25 03:55:36

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7092391/c-sharp-winform-datagridview-inline-add-new-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!