Saturday, March 24, 2012

ListBox

Hello,

I have a problem with a List Box, and I don't know why.

I just want to know which index is selected, when I click on an image button.
I wrote this:

private void ibAdd_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{

// lbAgent is the List Box

Response.Write ("Selected Agent: " + lbAgent.SelectedIndex.Value.ToString());
Response.End();

}

But the problem is that it always says that the selected index is "-1".
I'm not sure how to get that value.

What am I doing wrong?

Thanks.Hi,

Where are you populating the ListBox. If you are doing it in the Page_Load event, you need to put it between the following code:-

If Not IsPostBack

populate your listbox here

End If

The reason for the problem you face is that the button click makes a postback and the page reloads and your listbox might be repopulated, making the selected value as the first item irrespective of what u selected before clicking the button.

thanks.
FYI...EasyListBox will persist your selections even if you databind. In fact, it doesn't even need ViewState at all.
You mean populate by witing for example:

string itemSel;

If(! Page.IsPostBak) {

itemSel = Request.Querystring["ddlAgent"] == null ?"": Request.Querystring["ddlAgent"].ToString();

}

I'm not sure how to get the value,do I have to use a Querystring using the name of the ListBox ?

But there's something I don't understand.

I create new "test" page and I put there a ListBox and a button.
I "manualy" add a few items

<asp:ListItem value="1">Value 1</asp:ListItem

When I click the button, I write the selected index, and it worked perfectly.

But ! , if instead of adding the items manually, I use a dataset for doing that, it doesn't work.
I set :


//ds is the data set.

lbAgent.DataValueField = ds.Tables[0].Columns[0].ToString();
lbAgent.DataTextField = ds.Tables[0].Columns[1].ToString();
lbAgent.DataBind();

If I try to do the same that I did before, it doesn't work.

What could be happen ?
In most ASP.NET forms, you'll probably be using Request.Form rather than Request.Querystring (if there are no parameters in the URL, then it's Request.Form).

The code you wrote above will only set itemSel if you're NOT on a postback, which won't help at all, since (usually) you only get form data on a postback.

I suggest making sure that your databinding code *only* executes if !Page.IsPostBack.

0 comments:

Post a Comment