Andrew Truckle
Andrew Truckle

Reputation: 19207

DataGridView DataSource contents duplicated

If I go to select a new XML file and attach it as a datasource to the DataGridView it doesn't replace the grid contents but appends to it:

private void buttonSelectXML_Click(object sender, EventArgs e)
{
    OpenFileDialog dlgFile = new OpenFileDialog();

    dlgFile.Title = "Select XML file";
    dlgFile.Filter = "XML files (*.xml)|*.xml";
    dlgFile.FilterIndex = 0;
    dlgFile.Multiselect = false;
    dlgFile.InitialDirectory = Path.GetDirectoryName(textBoxXML.Text);
    dlgFile.FileName = textBoxXML.Text;

    if (dlgFile.ShowDialog() == DialogResult.OK)
    {
        Properties.Settings.Default.XMLPath = dlgFile.FileName;
        textBoxXML.Text = dlgFile.FileName;

        dataSet.ReadXml(textBoxXML.Text);
        dataGridView.DataSource = dataSet.Tables[0];
    }
}

What is the right way to replace the current grid content with the new XML datasource rather than append?

Thanks.

Upvotes: 0

Views: 129

Answers (2)

Matteo1010
Matteo1010

Reputation: 361

I think you should call

dataGridView.DataBind()

Upvotes: 0

Rahul
Rahul

Reputation: 77926

Either way it shouldn't be the case and your grid data should get refreshed since you are rebinding it. As an alternative, try setting the datasource to null like

    dataSet.ReadXml(textBoxXML.Text);
    dataGridView.DataSource = null;
    dataGridView.DataSource = dataSet.Tables[0];

Upvotes: 1

Related Questions