Pre-Populate Dropdownlist?

D

DOUGLAS HEESTAND

I have a simple web app I am building: a user fills out a simple form
(regform.aspx) and clicks "OK" and they get a confirmation page
(confirmation.aspx) that repeats back what they entered before they
move on. I want the user to be able to go back to the first page from
the confirmation page and change values if they want. Seems simple,
no? I was going to use session state to pre-fill in the values on the
simple form on page_load if they are returning to it from the
confirmation page. I can do this for textboxes but when I try it for
a dropdown list I get ""Object reference not set to an instance of an
object." Here is a simplified version of my code. Thanks for any
help in advance:

RegForm.aspx
-------------
<%@ Page Language="VB" Inherits="RegFormCodeBehind"
Src="RegForm.aspx.vb" %>
<form name="RegForm" method="post" action="RegForm.aspx"
runat="server">
<asp:textbox ID="txtName" runat="server" /><br>
<asp:dropdownlist ID="ddlAge" runat="server">
<asp:listitem>Choose one...</asp:listitem>
<asp:listitem Value="25">25</asp:listitem>
<asp:listitem Value="26">27</asp:listitem>
</asp:dropdownlist>
....

RegForm.aspx
-------------
Public Class RegFormCodeBehind
Inherits System.Web.UI.Page

Public txtName as Textbox
Public ddlYear as Dropdownlist

Public Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
txtName.Text = "test value"
ddlAge.SelectedIndex = 1
End Sub
End Class

How do you set dropdownlists from code?

Thanks in advance!
-----------------
 
A

Alvin Bruney [MVP]

Your dropdownlist has no items in it so it will blow up if you try to set
the index to 1 since the items are probably zero. The common approach is to
save the items in an array and cache the array. Then cache the selected
index that the user chose
Consider:

ArrayList arr = new ArrayList();
arr.Add(new listitem("item1","val1"));
arr.Add(new listitem("item2","val2"));
arr.Add(new listitem("item3","val3"));
Session["Items"] = arr;

[snip]
dropdownlist1.DataSource = arr;
dropdownlist1.DataBind();

//user selects item 1
Session["Selection"] = dropdownlist1.SelectedIndex.ToString();

[snip]
//coming back to the page
ArrayList arr = Session["Items"] as ArrayList;
if(arr!= null)
{
dropdownlist1.DataSource = arr;
dropdownlist1.DataBind();
if(Session["Selection"] != null)
{
int i = Int32.Parse(Session["Selection"].ToString());
if (i > Dropdownlist1.items.count)
Dropdownlist1.selectedindex = i;
}
}

roughly
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top