简体   繁体   中英

Updating DataGridView after changing data source during run-time

public void sortAssets(string assetType)
    {
        DataTable newDataTable = new DataTable();
        foreach(DataRow row in table.Rows)
        {
            if ((string)row["assetType"] == assetType)
            {
                string test = (string)row["assetType"];
                newDataTable.ImportRow(row);
            }
        }
        dataGridViewAssets.DataSource = null;
        dataGridViewAssets.DataSource = newDataTable;
        dataGridViewAssets.Refresh();
    }

Above is a piece of code extracted from a program I'm working on. I want to change the data-source to newDataTable at runtime. To do that, I have first cleared the the datagridview using dataGridViewAssets.DataSource = null; . Then, I changed the data source ( dataGridViewAssets.DataSource = newDataTable; ). At last, I refreshed the datagridview by dataGridViewAssets.Refresh(); .

However, the visual datagridview does not get updated. Instead, all data in it get erased and remains blank.

What is wrong here and what must be changed?

Unless you specifically need to clone rows, this would be a lot simpler:

public void FilterAssets(string assetType) {
  (dataGridViewAssets.DataSource as DataTable).DefaultView.RowFilter = "$[assetType] = '{assetType}'";
}

If you've made your DGV based on a bindingsource, it's

public void FilterAssets(string assetType) {
  (dataGridViewAssets.DataSource as BindingSource).Filter = "$[assetType] = '{assetType}'";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM