开发者

C# dataset clear method

I'm new to C#. I want to create a windows form with a combobox and a dataGridView. I fill the dataGridView based on the selected value from the combobox. So far so good. But when I change the value of the combobox, and try to reload the dataGridView's contents like so:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboB开发者_运维技巧ox1.SelectedValue != null) 
    { 
        if (ds.Tables.Contains("Leagues"))
        { 
            ds.Tables["Leagues"].Clear(); // <-- error happens here 
        }
        leagues_adapter.SelectCommand.Parameters[0].Value = comboBox1.SelectedValue;
        main.InsertCommand.Parameters[0].Value = comboBox1.SelectedValue; 
        leagues_adapter.Fill(ds, "Leagues"); 
    } 
}

When myDataSet.Tables["myTable"].Clear() is called, I get on a DataGridView Default Error Dialog the following:

System.IndexOutOfRangeException: Index 0 does not have a value at System.Windows.Forms.ConcurrencyManager.get_Item(Int32 index) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 rowIndex). To replace this default dialog please handle the DataError event.

I also have an OK button.

This happens only when I want to change the contents of the combobox from a certain value to some other value. However, if I hit the OK button lots of times, I see that with every hit, an element from a row and a column is removed one by one, and when I consume all the elements with the OK button, I finally get what I wanted: the dataGridView with the new data in it. Please help me, any answer is appreciated. Thanks in advance.


Clear the binding and re-set it after reloading the data:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    dataGridView.DataSource = null;

    // Reload data with the code in your question.

    dataGridView.DataSource = // same code as you are using right 
                              // now for setting the binding
}


You cannot clear the dataTable if this is used as a data source of dataGridView.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜