如何替换DataSet中的DataTable,以便DataGridView显示新的DataTable内容?

时间:2012-03-08 06:31:51

标签: c# datatable dataset

  • 要替换的DataSet与原始DataTable具有相同的TableName。
  • 我尝试过DataSet.Tables.Clear()以及DataSet.Tables.Remove(...)
  • DataSet中的DataTable似乎被替换 - 但是,DataGridView继续显示旧的DataTable内容。
  • 无法合并 - 需要完全替换新DataTable的内容。
  • 只要新的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;
    }
    

    }

0 个答案:

没有答案