-1

I am new at C# and I would like to ask how is it possible to get a value of the reader (XML file) to a table column. I want the reader value to be a string. I tried to get the value to a listbox1 and it works, but that's not what I need. Thank you.

private void button1_Click(object sender, EventArgs e)
    {
        string file;
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) ;
        file= ofd.FileName;


        XmlTextReader reader = new XmlTextReader(file);
        XmlNodeType type;

        DataSet dsload = new DataSet();
        dsload.ReadXml(file);

        while (reader.Read())
        {
            if (reader.Name == "name")
            {
                reader.Read();
                listBox1.Items.Add(reader.Value);
                DataTable dt = new DataTable("MyTable");
                dt.Columns.Add(new DataColumn("Name", typeof(string)));
                data.DataSource = dsload.Tables[0];
            }

        }
Joshua
  • 40,822
  • 8
  • 72
  • 132
acrylicfrog
  • 11
  • 1
  • 3
  • You can't add the same column twice into the datatable. The dt.Columns.Add() can only be added when reading the first row from the reader. The data.DataSource code whould be removed it is doing nothing and will cause errors. The DataTable dt can only be done once and shouldn't be in the while loop. It is not needed since you arre putting the data into a listbox. – jdweng May 27 '16 at 11:50

1 Answers1

0
  while (reader.Read())
        {
            if (reader.Name == "name")
            {
                reader.Read();
                listBox1.Items.Add(reader.Value);               
            }    
        }
 DataTable dt = new DataTable("MyTable");
 dt.Columns.Add(new DataColumn("Name", typeof(string)));
 foreach (string value in listbox1.Items)
 {
    dr = dt.NewRow();
    dr[0] = value;               
    dt.Rows.Add(dr);
  }
  data.DataSource=dt;
apomene
  • 14,282
  • 9
  • 46
  • 72