I have a DataGridView that is bound to a DataTable.
I later add a new button column directly to the DGV. The next time I refresh the table I want to clear all the previous data from the DGV.
For the table I just do var table = new DataTable();
but doing this with the DataGridView when the DGV is defined as a local inside the method causes it to never display on the form.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//dataGridView1 = new DataGridView(); //<-- uncommenting this line breaks the form's dgv from displaying anything
DataTable table = new DataTable();
table.Columns.Add("C_" + table.Columns.Count);
table.Rows.Add("R1");
table.Rows.Add("R2");
dataGridView1.DataSource = table;
DataGridViewButtonColumn oCol = new DataGridViewButtonColumn();
oCol.Name = "Buttons";
oCol.Text = "(...)";
oCol.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(oCol);
}
}
}
Is this a bug or how should I refresh/reset/clear a dgv properly?
EDIT:
Code snippet above has been edited from the original. Uncomment the line in the code to see the different behaviour of button1 when in RunMode.
or you could opt to clear the columns/rows.