通过C#在ASP中填充gridview从xml获取记录信息

时间:2018-11-07 12:02:50

标签: c# asp.net xml

我正在尝试使选定的记录显示在gridview中,但是选定的记录在XML文件中,该文件正在填充下拉框-下拉框是我要在其中显示的记录的选择器gridview,我有一个不错的开始,但是我一生都无法弄清楚如何显示完整记录。它可能很小,但过去6个小时我一直在搜索和搜索。

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loaddropdown();
        }
    }

    private void loaddropdown()
    {
        DataSet ds = new DataSet();
        ds.ReadXml("http://localhost:63707/registrations.xml");
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "id";
        DropDownList1.DataValueField = "id";
        DropDownList1.DataBind();
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = DropDownList1.SelectedIndex;
        GridView1.DataBind();

    }
}

xml记录是

   <registrations>
  <Registration>
     <id>1</id>
     <fullName>Keiran Bernal</fullName>
     <emailAddress>k.bernal@gmail.com</emailAddress>
     <registrationType>conference only</registrationType>
     <attendingSocialEvent>1</attendingSocialEvent>
  </Registration>
  <Registration>
     <id>2</id>
     <fullName>Cordelia Pierce</fullName>
     <emailAddress>c.pierce@outlook.com</emailAddress>
     <registrationType>conference and workshops</registrationType>
     <attendingSocialEvent>0</attendingSocialEvent>
  </Registration>

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

我喜欢创建一个数据表,然后绑定到该数据表

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication78
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(string));
            dt.Columns.Add("fullname", typeof(string));
            dt.Columns.Add("email", typeof(string));
            dt.Columns.Add("registrationType", typeof(string));
            dt.Columns.Add("attending", typeof(string));

            XDocument doc = XDocument.Load(FILENAME);

            foreach(XElement registration in doc.Descendants("Registration"))
            {
                DataRow newRow = dt.Rows.Add( new object[] {
                    (string)registration.Element("id"),
                    (string)registration.Element("fullName"),
                    (string)registration.Element("emailAddress"),
                    (string)registration.Element("registrationType"),
                    (string)registration.Element("attendingSocialEvent")
                });


            }

        }
    }
}