Show an xml in a Datagridview

0

I'm trying to open XML in a datagridview, what I have is this, I open xml expensive and longer but one created by me does not open it and says "Object reference not established as an instance of an object"

            private void button1_Click(object sender, EventArgs e)
    {
        using(OpenFileDialog ofd = new OpenFileDialog() { Filter= "Excel Workbook|*.xls", ValidateNames = true })
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
                IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs);
                reader.IsFirstRowAsColumnNames = true;
                result = reader.AsDataSet();
                cbohoja.Items.Clear();
                foreach (DataTable dt in result.Tables)
                    cbohoja.Items.Add(dt.TableName);
                reader.Close();
            }

        }
    }

    private void cbohoja_SelectedIndexChanged(object sender, EventArgs e)
    {
        dataGridView2.DataSource = result.Tables[cbohoja.SelectedIndex];
    }
    
asked by El Barto 15.06.2018 в 18:39
source

1 answer

0

I share my solution and the xml that I created:

My Code:

 private void button1_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "|*.xml", ValidateNames = true })
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string filePath = ofd.FileName;

                dataSet1.ReadXml(filePath);

                dataGridView1.DataSource = dataSet1;
                dataGridView1.DataMember = "Persona";
            }
        }
    }

The XML:

<Persona>  
<Dni>172-32-1176</Dni>  
<Nombre>Victor</Nombre>  
<Apellido>Lima</Apellido>  
<Tlf>408 496-7223</Tlf>  

I simply create a DataSet and this is in charge of reading the XML file from the route I indicated, then I add the DataSet to the DataGridView and I indicate that the XML list must use in this case "Person". Obviously it is not atomized since you would have to know the XML that you will read

Greetings, I hope the answer will help you and if so, mark your question as answered

    
answered by 24.06.2018 в 04:19