gpt4 book ai didi

c# - DataGridView 缺少数据源为空的新行

转载 作者:太空狗 更新时间:2023-10-29 22:22:41 25 4
gpt4 key购买 nike

我正在创建一个应用程序,它使用 DataGridView 创建和修改稍后将导入到系统中的本地列表。它应该可以由用户编辑(在 DGV 中单击和写入),并且它还应该支持从 csv 导入,这意味着我需要 DGV 和数据源之间的双向同步。

我已将 DGV 的数据源设置为 BindingList<Client>像这样:

//In my seperate Client class-file
public class Client
{
private string _name;
private string _mac;
private string _status;

public Client(string pcnavn, string MAC)
{
_pcnavn = pcnavn;
_mac = mac;
}

public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}

public string MAC
{
get
{
return _mac;
}
set
{
_mac = value;
}
}

public string Status
{
get
{
return _status;
}
set
{
_status = value;
}
}
}

//In my mainform class

public BindingList<Client> clientDataSource = new BindingList<Client>();

public MainForm()
{
InitializeComponent();
//clienDataGridView.AutoGenerateColumns = false; //The duplicate columns where fixed by setting DataPropertyName for all columns.
clientDataGridView.DataSource = clientDataSource;
}

使用这种方法,生成了 DGV,但它是空的(只有标题),因此用户无法使用 DGV 添加行。如果没有 DataSource,它会像 SQL 编辑器一样显示空白行,因此我可以在 DGV 中手动创建行。链接到空数据源时如何显示“新项目”行?我发现的所有示例都使用非空数据源。

AllowUserToAddRowsAllowUserToDeleteRows设置为 true .

这张图片显示了我的问题。使用数据源时缺少“第一行”。无法通过键入 DGV 来添加数据。 DGV

最佳答案

当查看 MSDN 时,我发现了这个:

If the DataGridView is bound to data, the user is allowed to add rows if both this property and the data source's IBindingList.AllowNew property are set to true.

似乎 BindingList 的这个属性默认为 false,所以这个小技巧修复了它:

public BindingList<Client> clientDataSource = new BindingList<Client>() { AllowNew = true };

关于c# - DataGridView 缺少数据源为空的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20589351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com