简体   繁体   中英

C#: Choose XML file to open in a DataGridView for DataBinding

I would like to load a DataGridView from an XML file.
I put the 'load' code in a Button event like this:

 private void metroButton13_Click(object sender, EventArgs e) 
 {
     // load
     DataSet dataSet = new DataSet();
     dataSet.ReadXml(@"C:\temp\xml.xml");
     dataGridView1.DataSource = dataSet.Tables[0];
 }

And it loads correctly what I want using a const UniCode-String.
What I need now is a PopUp Window in which I can choose the file to be bound to the DataSource instead of the const "C:\\temp\\xml.xml" string.

Yes I know there is a lot of topic I try, but so far I'm unable to do this in my project.

You can use OpenFileDialog to select the file and pass this to ReadXml . Something like the below lines would solve your problem.

private void metroButton13_Click(object sender, EventArgs e) 
{
    DialogResult result = openFileDialog1.ShowDialog();
    int size =0;
    string file = string.empty;
    if (result == DialogResult.OK) // Test result.
    {
       string file = openFileDialog1.FileName;
       try
       {
          string text = File.ReadAllText(file);
          size = text.Length;
       }
       catch (IOException)
       {
       }
    }
    if(size >0) 
    {
        DataSet dataSet = new DataSet();
        dataSet.ReadXml(file);
        dataGridView1.DataSource = dataSet.Tables[0];
    }
    else 
    {
      msgbox ("blank file");
    }
}
  DataSet dataSet = new DataSet();
            OpenFileDialog sfd = new OpenFileDialog();
            sfd.Filter = "XML|*.xml";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string file = sfd.FileName;
                try
                {

                    dt.ReadXml(file);

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

Actually this code solve my problem but you give me something to think just. Anyway thank you!

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