简体   繁体   English

C#:选择XML文件以在DataGridView中打开以进行DataBinding

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

I would like to load a DataGridView from an XML file. 我想从XML文件加载DataGridView
I put the 'load' code in a Button event like this: 我将“加载”代码放在如下的Button事件中:

 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. 并使用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. 现在,我需要一个弹出窗口,在其中可以选择要绑定到DataSource的文件,而不是const “ C:\\ temp \\ xml.xml”字符串。

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 . 您可以使用OpenFileDialog选择文件并将其传递给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! 反正谢谢你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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