我正在创建一个应用程序,它使用DataGridView创建和修改稍后将导入系统的本地List。它应该由用户编辑(在DGV中单击和写入),它还应该支持从csv导入,这意味着我需要DGV和数据源之间的双向同步。
我已将DGV的DataSource设置为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中手动创建行。如何在链接到空数据源时显示“新项目”?我发现的所有示例都使用非空数据源。
AllowUserToAddRows
和AllowUserToDeleteRows
设置为true
。
这张照片显示了我的问题。使用数据源时缺少“第一行”。输入DGV无法添加数据。
答案 0 :(得分:9)
在查看MSDN时,我发现了这一点:
如果DataGridView绑定到数据,则如果此属性和数据源的 IBindingList.AllowNew 属性都设置为true,则允许用户添加行。
默认情况下,BindingList
似乎将此属性设置为false
,因此这个小技巧修复了它:
public BindingList<Client> clientDataSource = new BindingList<Client>() { AllowNew = true };
答案 1 :(得分:2)
我猜您错过了DataPropertyName设置。
首先,您必须向数据网格添加列。转到添加列选项并使用向导添加所需的列。
其次,您必须在向导模式下编辑每一列并设置DataPropertyName
。基本上,对于您创建的每个网格列,您需要提供Client类的精确绑定属性名称。
Displaying Empty Row
将空列表绑定到DGV时,将删除默认行。如果你需要显示一个空行,那么就这样做,
//Adding a client object to the collection so that an empty row will be inserted to DGV
clientDataSource.Add(new Client());
clientDataGridView.DataSource = clientDataSource;
答案 2 :(得分:0)
try
{
int id =Convert.ToInt32( textBox1.Text);
string query = "SELECT * FROM ngo.inser WHERE ID LIKE '%" + id + "%'";
command = new MySqlCommand(query, connection);
adapter = new MySqlDataAdapter(command);
table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
转到datagridview编辑列设置。在具有DataPropertyName的DATA菜单中,将非属性更改为实际的数据库列名。然后它会显示该列信息。如果您有多列,则设置所有类似的信息。