I'm creating an application which uses a DataGridView to create and modify a local List that will be imported into a system later. It should be editable by the user (clicking and writing in the DGV), and it should also support importing from csv which means I need 2-way sync between DGV and datasource.
I've set the DGV's DataSource to a BindingList<Client>
like this:
//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;
}
With this approach, the DGV is generated, but it is empty(only headers), so the user can't add a row by using the DGV. Without DataSource, it displays a blank row like a SQL editor so I can create rows manually in the DGV. How can I show the "new item"-row when linked to an empty data source? All examples I've found uses non-empty datasources.
AllowUserToAddRows
and AllowUserToDeleteRows
are set to true
.
This picture shows my problem. The "first row" is missing when using datasource. It's not possible to add data by typing in the DGV.
When looking at MSDN, I found this:
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.
It seems BindingList
has this property as false
by default, so this little trick fixed it:
public BindingList<Client> clientDataSource = new BindingList<Client>() { AllowNew = true };
I guess you are missing the DataPropertyName setting.
First you have to add columns to your data grid. Go to add columns option and add the required columns using the wizard.
Secondly you have to edit each column in the wizard mode and set the DataPropertyName
. Basically for each grid column you have created you need to give the exact bound property name of Client class.
Displaying Empty Row
When you bind a empty list to a DGV default row will be removed. If you need to display an empty row then do like this,
//Adding a client object to the collection so that an empty row will be inserted to DGV
clientDataSource.Add(new Client());
clientDataGridView.DataSource = clientDataSource;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With