What is DataGridView.Rows.Clear()?

2020-05-07 06:13发布

问题:

I'm adding programatically some rows in a datagridview every certain time. I want to view in the datagridview the status of certain github repositories, such as if are online, how much commits are in the repos at certain time, etc.

So, when there is timeout, i clear the rows with DataGridView.Rows.Clear() and then i add again the repositories with the updated info.

My code is here:

 Dim ok As Integer = 0
    DataGridView1.Rows.Clear()
    For Each r As RepoURL In _impControllerBpi.GetReposApi
        DataGridView1.Rows.Add(DateTimeOffset.Now, "https://github.com/" + r.GetUsr + "/" + r.GetNomRep, "-", "-", "-")
    Next
    Dim counter = 1
    For Each r As RepoURL In _impControllerBpi.GetReposApi
        DataGridView1.Rows.Item(counter - 1).Cells.Item(0).Value = DateTimeOffset.Now
        DataGridView1.Rows.Item(counter - 1).Cells.Item(2).Value = "Conectando con GitHub"
        ok = Await _impController.getRepoGitHub(r, counter)
        If ok = 1 Then
            DataGridView1.Rows.Item(counter - 1).Cells.Item(0).Value = DateTimeOffset.Now
            DataGridView1.Rows.Item(counter - 1).Cells.Item(2).Value = "Conectado"
        Else
            DataGridView1.Rows.Item(counter - 1).Cells.Item(0).Value = DateTimeOffset.Now
            DataGridView1.Rows.Item(counter - 1).Cells.Item(2).Value = "Repositorio no disponible en GitHub"
        End If
        counter = counter + 1
    Next

    Dim wreturnCode As Integer = System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf RepeatAction), cancellation.Token)

    ok = 0

All works fine without Clear(). But when i clear the rows, in some iteration, when i add the first row, the system throws me a

System.NullReferenceException

Some help? Clear() frees the memory allocated for the collection of rows?

回答1:

There are serial ways for choice when you really want to clear the data of DataGridView Control.

1.Use for loop to clear the row data one by one.

 for (int i = 0; i < dataGridView1.RowCount; i++)
        {
            dataGridView1.Rows.Remove(dataGridView1.Rows[0]);

        } 

2.Set DataSource property to NULL directly.

 DataGridView.DataSource=null;

If you want to bind DataSet to this control, you’d better setting DataSet to NULL first.

DataSet DataSet1=new DataSet();
DataSet1.clear();

3.Above way may remove all of Tables inside in specified DataSet,so you'd better removing its Table separately.

DataSet ds = new DataSet();

DataTable dt = new DataTable();

dt.Columns.Add("val", typeof(int));

dt.Columns.Add("name", typeof(string));

dt.Rows.Add(1, "good");

ds.Tables.Add(dt);

dt.TableName = "test";

dataGridView1.DataSource = ds.Tables[0];

Hence, you can use following code to clear specified table.

ds.Tables[0].Clear();