I have a Windows Form with dgv. For now it’s just for presentational purposes so I use dummy data to populate one row with data. I also have a button named Add New Row which for just have to add new empty row in the dataGridView every time it’s clicked. For the initial populating of the dgv I use the load event of the form like this :
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
MyData td13 = new MyData();
td13.colorCombinationColumn = "aff";
td13.remarksColumn = "abcdddd";
td13.prodColumn = true;
td13.LastModifiedColumn = "ab";
td13.ByColumn = "abc";
MyData[] arr = new MyData[2];
arr[0] = td13;
dataGridView1.DataSource = arr;
}
Where MyData is this class :
public class MyData
{
private int mId;
private string mCombination;
private string mremarks;
private bool mprod;
private string mLastModified;
private string mBefore;
public int Id
{
get
{
return mId;
}
set
{
...
So far so good, but then I add my button and handle his click event:
private void btnAddRow_Click(object sender, EventArgs e)
{
SoleData[] arr = new SoleData[1];
dataGridView1.DataSource = arr;
}
And here is where the things go wrong. If I just dataGridView1.Rows.Add(1); is says Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.. As you see I tried some other approaches but so far no success.
Try to use a
BindingList<MyData>instead of theMyData[] arr.Any modifications you do to the list will be reflected in the DGV, no further code necessary.
(Also, declare the list as a private field of the form.)