Pergunta

I'm making a .NET 4.5 site that uses a dropdown list to pick the username and then the user types in their id code in a text box. The page then checks that both fields match values from an xml file and moves on to an account page. My problem is the dropdown list selection doesn't change from the first option loaded.
Here is the xml file that the page is populating the dropdown list from and also checking the information against.

    <?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata" generated="2014-05-09T14:35:34">
  <Staff>
    <IdCode>0200</IdCode>
    <Name id="0200">Doe, John</Name>
  </Staff>
  <Staff>
    <IdCode>0130</IdCode>
    <Name id="0130">Doe, Jane</Name>
  </Staff>
  <Staff>
    <IdCode>0000</IdCode>
    <Name id="0000">Admin, Admin</Name>
  </Staff>
</dataroot>

I populated the dropdown list using a modified version used here Populating dropdown from the XML in C#. Here's the code:

XDocument xdoc = XDocument.Load(Server.MapPath("Staff.xml"));
            var query = from xEle in xdoc.Descendants("Staff") select new ListItem(xEle.Element("Name").Value);

            DropDownList1.DataValueField = "value";
            DropDownList1.DataTextField = "text";
            DropDownList1.DataSource = query;
            DropDownList1.DataBind();

            userName = DropDownList1.SelectedItem.Text;

I then use "dropdownlist1.SelectedItem.Text" to get the selected username but it only returns the option at the top of the xml file, so it will only return Doe, John regardless of what I select.

Any help is appreciated, also let me know if I left something out, thanks.

Foi útil?

Solução

Seems you missing Page.IsPostBack

if(!IsPostBack)
{
      XDocument xdoc = XDocument.Load(Server.MapPath("Staff.xml"));
      var query = from xEle in xdoc.Descendants("Staff") select new ListItem(xEle.Element("Name").Value);   
      DropDownList1.DataValueField = "value";
      DropDownList1.DataTextField = "text";
      DropDownList1.DataSource = query;
      DropDownList1.DataBind();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top