SantyEssac
SantyEssac

Reputation: 809

Binding Listbox value and Text in c# in aspx

I have a ListBox and want to bind value and text to it.

The Value and Text are taken from query string and they are comma separated.

My code goes as follows:

var pIDs = Request.QueryString["pIds"];
var pIDsText = Request.QueryString["pText"];
var SeparatedIds = pIDs.Split(',').Distinct().ToArray();
var SeparatedPIdsText = pIDsText.Split(',').Distinct().ToArray();

System.Web.UI.WebControls.ListBox ls = (System.Web.UI.WebControls.ListBox)User_Control_ListBox1.FindControl("lstShowPrograms");

 for (int i = 0; i < SeparatedPIdsText.Length; i++)
 {
      if (!string.IsNullOrEmpty(SeparatedPIdsText[i])) 
          {

                ls.Items.Add(SeparatedPIdsText[i]);
          }

 }

The above code is adding only text.I want to set both value and text. Text to display and value(ID) for background.

Upvotes: 0

Views: 491

Answers (1)

Evan Huang
Evan Huang

Reputation: 1275

Add ListItem to the ls.Items instead of string

ls.Items.Add(new ListItem(SeparatedPIdsText[i], SeparatedIds[i]));

Just make sure SeparatedIds and SeparatedPIdsText have the same length or there will be IndexOutOfRangeException

Upvotes: 1

Related Questions