只要新的DataTable TableName与要替换的DataTable的表名不同,我就可以替换和反映DataGridView中的更改。
public partial class Form1 : Form
{
private DataSet _ds;
public Form1()
{
InitializeComponent();
_ds = new DataSet("DS");
dataGridView1.DataSource = _ds;
addTableOne();
}
private void addTableOne()
{
DataTable dtOne = new DataTable("Original");
DataColumn auto = new DataColumn("AutoID", typeof(System.Int32));
dtOne.Columns.Add(auto);
DataColumn name = new DataColumn("Name", typeof(string));
dtOne.Columns.Add(name);
DataRow row = null;
for (int i = 0; i < 5; i++)
{
row = dtOne.NewRow();
row["AutoID"] = i + 1;
row["Name"] = i + " - Original";
dtOne.Rows.Add(row);
}
_ds.Tables.Add(dtOne);
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "DataSet count: " + _ds.Tables.Count;
dataGridView1.DataMember = "Original";
}
private DataTable getAltTable()
{
DataTable dtOne = new DataTable("Original");
DataColumn auto = new DataColumn("AutoID", typeof(System.Int32));
dtOne.Columns.Add(auto);
DataColumn name = new DataColumn("Name", typeof(string));
dtOne.Columns.Add(name);
DataRow row = null;
for (int i = 0; i < 10; i++)
{
row = dtOne.NewRow();
row["AutoID"] = i + 1;
row["Name"] = i + " - Alt";
dtOne.Rows.Add(row);
}
return dtOne;
}
private void button3_Click(object sender, EventArgs e)
{
DataTable temp = _ds.Tables["Original"];
string tTable = Convert.ToString(DateTime.Now.Ticks); ;
temp.TableName = tTable;
_ds.Tables.Remove(tTable);
// tried
//_ds.Tables.Clear();
// tried following
//temp.Dispose();
//temp = null;
label1.Text = "DataSet count: " + _ds.Tables.Count;
timer1.Enabled = true;
}
// here is where the old datatable contents still show in DataGridView
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
DataTable dt = getAltTable();
_ds.Tables.Add(dt);
dataGridView1.DataMember = "Original";
label1.Text = "DataSet count: " + _ds.Tables.Count;
}
}