【问题标题】:C#: Choose XML file to open in a DataGridView for DataBindingC#:选择要在 DataGridView 中打开的 XML 文件以进行 DataBinding
【发布时间】:2017-03-28 07:05:44
【问题描述】:

我想从 XML 文件加载 DataGridView
我将“加载”代码放在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];
 }

它使用 const UniCode-String 正确加载我想要的内容。
我现在需要的是一个 PopUp 窗口,我可以在其中选择要绑定到 DataSource 的文件,而不是 const "C:\temp\xml.xml " 字符串。

是的,我知道我尝试了很多主题,但到目前为止我无法在我的项目中执行此操作。

【问题讨论】:

  • 我(希望)通过重新表述澄清了这个问题。

标签: c# xml winforms datagridview


【解决方案1】:

您可以使用OpenFileDialog 选择文件并将其传递给ReadXml。类似下面几行的内容可以解决您的问题。

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");
    }
}

【讨论】:

    【解决方案2】:
      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);
                    }
                }
    

    实际上这段代码解决了我的问题,但你给了我一些思考。无论如何,谢谢!

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 2021-12-11
      相关资源
      最近更新 更多