Reputation: 237
I'm adding data to my listbox using this code :
SqlCommand cmd1 = new SqlCommand("SELECT U_Naam, U_Voornaam, User_ID FROM Login ORDER BY U_Naam ASC", con);
dr = cmd1.ExecuteReader();
int teller = 0;
while (dr.Read())
{
hulp = dr["U_Naam"].ToString() + " " + dr["U_Voornaam"].ToString();
lbNiet.Items.Add(hulp);
lbNiet.Items[teller].Value = dr["User_ID"].ToString();
teller++;
}
When I run the program and select an item in the list I want to get it's value (Using selectedvalue). When I do this it allways gives a nullref (no value). I've read somewhere the selected item is lost after a postback ? How can I solve this ?
thanks !
Upvotes: 0
Views: 1250
Reputation: 405
you can use Request.Form to find the posted value
or I think if you use a scriptmanager and an updatepanel it refills the box after a postback
Upvotes: 0
Reputation: 52241
replace these lines
lbNiet.Items.Add(hulp);
lbNiet.Items[teller].Value = dr["User_ID"].ToString();
with
lbNiet.Items.Add(new ListItem(hulp,dr["User_ID"].ToString();));
Upvotes: 3
Reputation: 28355
Are you using the ViewState for your page?
If yes, check the IsPostBack property of the page, and don't populate your list after postback.
Upvotes: 0
Reputation: 849
I don't think the selected item is lost after PostBack under normal circumstances - my guess is that you are accidently populating the ListBox again after PostBack so that when you make a selection, the system hits the Page_Init / Page_Load (or whatever event you choose to populate the ListBox in) and recreates all the options. Doing this would overwrite the currently selected option.
If that's the case it's easily avoided by check for PostBack first before repopulating the list.
Upvotes: 2
Reputation: 15227
Are you running that code in the Load of your ASP.NET page without checking to see if it is a Postback? You should make sure to wrap your loading code in a if (!IsPostback) {}
block if you're doing it in the load of the page.
Upvotes: 1