Reputation: 1171
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?
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.
Upvotes: 1
Views: 257
Reputation: 7092
I think this is not a bug. But unfortunately I can't explain :)
Just use the Controls.Add(..)
DataGridView dgv = new DataGridView();
private void button1_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("C_" + table.Columns.Count);
table.Rows.Add("R1");
table.Rows.Add("R2");
dgv.DataSource = table;
DataGridViewButtonColumn oCol = new DataGridViewButtonColumn();
oCol.Name = "Buttons";
oCol.Text = "(...)";
oCol.UseColumnTextForButtonValue = true;
dgv.Columns.Add(oCol);
Controls.Add(dgv); //<--Try to check this.
}
private void button2_Click(object sender, EventArgs e)
{
dgv.Columns.Clear();
}
Upvotes: 0
Reputation: 17680
dataGridView1.DataSource = null;
or you could opt to clear the columns/rows.
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
Upvotes: 1