C#Winform DataGridView内联添加新行 [英] C# Winform DataGridView inline add New row

查看:352
本文介绍了C#Winform DataGridView内联添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的datagridview中添加一个新项目。我知道可以使用几个TextBoxes和一个Button来实现。当用户单击此按钮时,它将向数据库中添加一个新项目并刷新我的datagridview。

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.

我想知道是否可以使用datagridview的最后一行添加一个新物品。我该怎么办?

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

推荐答案

您是否使用了RAD-Databind(winforms上的数据源)?如果是这样,可能会有些棘手。
应该将数据加载到一个单独的层中(如果可以的话,请不要加载到后面的代码中)。然后,在本地数据中添加另一行应该很简单。

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

并通过以下方式初始化名为GridView的DataGridView:

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;

然后您可以简单地通过

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

在一个真实的示例中,我将使用一些众所周知的模式:
用于Winforms的MVVM
用于Winforms的MVP
确实将View与逻辑分开了。但是毕竟重要的一点是使用某种BindingSource(通知Grid数据已更改),或者如果您选择使用浅表/简单数据容器(如List或类似的容器),则将更改后的数据重新声明给DataSource。

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.

这篇关于C#Winform DataGridView内联添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆