DropDownList SelectedIndexChanged AutoPostBack C# ASP.NET

2 DropDownList Boxes (ddStates, ddCounties)
Both are AutoPostBack.
ddStates_SelectedIndexChange says to populate ddCounties.
ddCounties_SelectedIndexChanged says to populate some other DropDownList.

When I select any county other than the first county then everything posts back and counties get reset to the first county.

I understand that the problem should be in ddCounties_SelectedIndexChanged but the problem is cleared up if I use a file to populate counties from ddStates_SelectedIndexChanged opposed to using a DB.

Oddly enough though, if you look at the "This works" code in ddStates_SelectedIndexChanged and use that code instead of the "This doesn't work" code, it works.

What is the difference between using a file as opposed to using a DB?


default.aspx
<%@ Page Language="C#" AutoEventWireup="false" Codebehind="default.aspx.cs" Inherits="SmartQueryXML._default" ValidateRequest="false" %>
 
<asp:DropDownList ID="ddStates" runat="server" OnSelectedIndexChanged="ddStates_SelectedIndexChanged" AutoPostBack="True" Width="150px"></asp:DropDownList>
<asp:DropDownList ID="ddCounties" runat="server" Width="150px" OnSelectedIndexChanged="ddCounties_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
 
=================================================
default.aspx.cs
    protected void ddStates_SelectedIndexChanged(object sender, EventArgs e) {
      string ErrorMessage = "";
      string state = ddStates.SelectedItem.Value;
 
      // This doesn't work
      DataSet ds = new DataSet();
      ds = Helper.GetCounties(state, "%%", ref ErrorMessage);
 
      ddCounties.Items.Clear();
      ddCounties.Items.Add(new ListItem("Choose a County", ""));
 
      foreach(DataRow dr in ds.Tables[0].Rows) {
        ddCounties.Items.Add(new ListItem(dr["Name"].ToString(), state));
      }
 
      // This works
      //DataSet ds = new DataSet("Jurisdiction");
      //FileStream fs = new FileStream(Server.MapPath("Jurisdiction.xml"), FileMode.Open, FileAccess.Read);
      //StreamReader sr = new StreamReader(fs);
      //ds.ReadXml(sr);
      //fs.Close();
      //DataView dv = new DataView(ds.Tables[0]);
 
      //dv.Table = ds.Tables[0];
      //dv.RowFilter = "State = '" + state + "'";
      //ddCounties.DataSource = dv;
      //ddCounties.DataMember = "jurisdiction";
      //ddCounties.DataTextField = "county";
      //ddCounties.DataValueField = "county";
      //ddCounties.DataBind();
 
    }
 
    protected void ddCounties_SelectedIndexChanged(object sender, EventArgs e) {
      // Reset inputs when user selects a county
      //  Clean slate.
      string county = ddCounties.SelectedItem.Value;
    }

Open in new window

famosoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bob LearnedCommented:
I don't see how either of them work, because they both don't reset the selected value after clearing and readding counties.

Bob
0
famosoAuthor Commented:
I don't understand and really value your opinion and help.  The commented "This works" code in ddStates populates the ddCounties DDL and when I select one of the counties from that list it sticks even after it posts.  What is missing that you think should be there (maybe I'm missing a step that .NET is allowing) or maybe I left out code that should have been shown.  I do believe that I placed all the code in here.
0
digitalZoCommented:
If I'm understanding your problem correctly, this is giving the error right?:

<<<When I select any county other than the first county then everything posts back and counties get reset to the first county.>>>>

On Page_Load, call the event under If Not IsPostBack:

  if (!IsPostBack) {
        ddStates_SelectedIndexChanged(ddStates, null);
    }
0
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

famosoAuthor Commented:
I may not have been clear enough when I said before this statement:
"When I select any county other than the first county then everything posts back and counties get reset to the first county."

I stated:
"
ddStates_SelectedIndexChange says to populate ddCounties.
ddCounties_SelectedIndexChanged says to populate some other DropDownList.
"

... meaning first I select a state, ddStates does its event and populates ddCounties.  Then, when I select a county (say the second one but could be the first or third) then the page posts again and I get the correct state I selected but the county is reset to the first county as if I never selected one.

So, digitalZo, I think that having
ddStates_SelectedIndexChanged(ddStates, null);
will be too late because !IsPostBack happened when I called the page.  Then I select ddState, then the ddState event happens and it posts back (IsPostBack), then the state I selected it there and ddCounties is filled.  I select ddCounties and ddCounties event happens and it posts back again (IsPostBack) and the state that I selected is still there but the ddCounties is reset to the beginning and doesn't hold the county I selected.

Maybe there is confusion in my Page_Load()  (see code snippet)
I also added the functions I call from Page_Load() also (LoadStates() and ClearQuestions()).

Also, I restated the events to ddStates and ddCounties.
 

    protected void Page_Load(object sender, EventArgs e) {
      // Request inputs
      // Request SessionID
      // Request if got questions already
 
      if(!IsPostBack) {
        LoadStates("");
        chkDeed.Attributes.Add("onclick", "javascript:checkDeed()");
        chkMortgage.Attributes.Add("onclick", "javascript:checkMortgage()");
        chkRefi.Attributes.Add("onclick", "javascript:checkMortgageRefi()");
        chkAssignment.Attributes.Add("onclick", "javascript:checkAssignment()");
        chkRelease.Attributes.Add("onclick", "javascript:checkRelease()");
        chkNewPolicy.Attributes.Add("onclick", "javascript:checkTitle()");
        chkReissuePolicy.Attributes.Add("onclick", "javascript:checkTitleReissue()");
 
        // Set Sessions
        Session["State"] = null;
        Session["County"] = null;
        Session["City"] = null;
 
        DisplayControl.Display = 0;
        DisplayControl.SetPanels(ref pnlOffice, ref pnlDocTypes, ref pnlQuestions, ref pnlDetails, 1);
 
        ClearQuestions();
 
      } else { // Page Posted Back
      }
    }
 
    private void LoadStates(string pState) {
      DataSet ds = new DataSet();
      FileStream fs = new FileStream(Server.MapPath("State.xml"), FileMode.Open, FileAccess.Read);
      StreamReader sr = new StreamReader(fs);
      ds.ReadXml(sr);
      fs.Close();
      DataView dv = new DataView(ds.Tables[0]);
      ddStates.DataSource = dv;
      ddStates.DataMember = "state";
      ddStates.DataTextField = "display";
      ddStates.DataValueField = "value";
      ddStates.DataBind();
      ddStates.SelectedValue = pState;
    }
 
    protected void ClearQuestions() {
      Session["Q_WasAsked"] = null;
    }
 
    protected void ddStates_SelectedIndexChanged(object sender, EventArgs e) {
      string ErrorMessage = "";
 
      if(ddStates.SelectedIndex != 0) {
        imgStateSummary.Visible = true;
      } else {
        imgStateSummary.Visible = false;
        imgOfficeDetail.Visible = false;
      }
 
      string state = ddStates.SelectedItem.Value;
      Session["State"] = state;
 
      // This doesn't work
      DataSet ds = new DataSet();
      ds = Helper.GetCounties(state, "%%", ref ErrorMessage);
 
      ddCounties.Items.Clear();
      ddCounties.Items.Add(new ListItem("Choose a County", ""));
 
      foreach(DataRow dr in ds.Tables[0].Rows) {
        ddCounties.Items.Add(new ListItem(dr["Name"].ToString(), state));
      }
 
      // This works
      //DataSet ds = new DataSet("Jurisdiction");
      //FileStream fs = new FileStream(Server.MapPath("Jurisdiction.xml"), FileMode.Open, FileAccess.Read);
      //StreamReader sr = new StreamReader(fs);
      //ds.ReadXml(sr);
      //fs.Close();
      //DataView dv = new DataView(ds.Tables[0]);
 
      //dv.Table = ds.Tables[0];
      //dv.RowFilter = "State = '" + state + "'";
      //ddCounties.DataSource = dv;
      //ddCounties.DataMember = "jurisdiction";
      //ddCounties.DataTextField = "county";
      //ddCounties.DataValueField = "county";
      //ddCounties.DataBind();
 
      //***************
 
      if(ddCounties.SelectedItem == null) {
        imgOfficeDetail.Visible = false;
      } else {
        if(ddCounties.SelectedItem.Value != "Choose a County") {
          imgOfficeDetail.Visible = true;
        } else {
          imgOfficeDetail.Visible = false;
        }
      }
 
      //***************
      // Reset inputs when user selects a state
      //  Clean slate.
      ClearQuestions();
      litQuestions.Text = "";
      litError.Text = "";
      litInfo.Text = "";
    }
 
    protected void ddCounties_SelectedIndexChanged(object sender, EventArgs e) {
      if(ddCounties.SelectedIndex != 0) {
        imgOfficeDetail.Visible = true;
      } else {
        imgOfficeDetail.Visible = false;
      }
 
      // Reset inputs when user selects a county
      //  Clean slate.
      string county = ddCounties.SelectedItem.Text;
      Session["County"] = county;
 
      ClearQuestions();
      litQuestions.Text = "";
      litError.Text = "";
      litInfo.Text = "";
    }

Open in new window

0
famosoAuthor Commented:
Sorry, my stupidity.  The error was in my DropDownList creation line 69

      foreach(DataRow dr in ds.Tables[0].Rows) {
        ddCounties.Items.Add(new ListItem(dr["Name"].ToString(), state));
      }

The above needed to be changed to

      foreach(DataRow dr in ds.Tables[0].Rows) {
        ddCounties.Items.Add(new ListItem(dr["Name"].ToString(), dr["Name"].ToString()));
      }
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
famosoAuthor Commented:
I decided to view my html source to see what was coming back in the DDL.  What was coming back was:

            <option value="CA">Alameda</option>
            <option value="CA">Alpine</option>
            <option value="CA">Amador</option>
            <option value="CA">Butte</option>
            <option value="CA">Calaveras</option>
            <option value="CA">Colusa</option>
            <option value="CA">Contra Costa</option>

...which state was being selected and since they were all states it just showed the first each time.

I just needed to look at the problem differently.

Thanks all for being there.
0
digitalZoCommented:
Since the counties is the dropdown being resetted, insert the SelectedIndexChanged event of that dropdown too in Not IsPostBack:

  if (!IsPostBack) {
        ddStates_SelectedIndexChanged(ddStates, null);
        ddCounties_SelectedIndexChanged(ddCounties, null);
    }       

Try this and let me know if it works.

http://msdn2.microsoft.com/en-us/library/ms227621(VS.80).aspx
0
JNSTAUBCommented:
simple, a text file don't have index so the SelectedIndexChange is not fired!

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.