【发布时间】:2013-01-11 21:58:49
【问题描述】:
我有一个绑定到 DataTable 的 DataGridView。
我稍后将新按钮列直接添加到 DGV。下次我刷新表时,我想从 DGV 中清除所有以前的数据。
对于这张桌子我只做var table = new DataTable();
但是当 DGV 被定义为方法内的本地时,使用 DataGridView 执行此操作会导致它永远不会显示在表单上。
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);
}
}
}
这是一个错误还是我应该如何正确刷新/重置/清除 dgv?
编辑:
上面的代码 sn-p 已从原始代码中编辑。取消注释代码中的行以查看 button1 在 RunMode 时的不同行为。
【问题讨论】:
-
我试过你的代码并打电话给
dataGridView1.Columns.Clear();,一切都很好。 -
@spajce 问题是我试图使用“new DataGridView”命令清除 dgv,但这不起作用。 dgv 无法显示单元格,即使它拥有 单元格。这就是我提到的bug。解决方案是使用'dataGridView1.Columns.Clear();'而不是按照 Scartag 的建议尝试制作新的 dgv。
标签: c# datagridview datatable