Monday, March 26, 2012

Populate data in ListBox for Multiple Selections (C#)

Hi there,
I am new in ASP.NET and wonder if somebody can help me with populating data in a ListBox from a database. Users should be able to choose multiple selections and pass the selected values for a search query. Please let me know if I miss anything.
Thanks a lot in advance!
// search.aspx
<asp:ListBox id="Community2" runat="server"></asp:ListBox>
//search.aspx.cs

if (!Community2.Items.FindByValue("-1").Selected)

{

for (int i=0 ; i<Community2.Items.Count ; i++)

{

if (Community2.ItemsIdea [I].Selected)

{

if (Community2 != "") Community2 += ",";

Community2 += Community2.ItemsIdea [I].Value;

}

}

}


//db.cs

publicvoid PopulateCommunities2(ListControl i_list,bool i_showalloption)

{

OleDbDataAdapter adapter =new OleDbDataAdapter("SELECT distinct community FROM properties", m_conn);

DataTable dt =new DataTable();

adapter.Fill(dt);

i_list.Items.Clear();

if (i_showalloption) i_list.Items.Add(new ListItem("All Communities", "-1"));

for (int i=0 ; i<dt.Rows.Count ; i++)

{

i_list.Items.Add(new ListItem(dt.RowsIdea [I]["community"])); //I am using pre-build code and have no idea what else I could do here.

}

}

For databind of a ListBox, you don't need to use loop to put data into the list. Just use ListBox1.DataSource field. For example:
ListBox1.DataSourse = GetCommunities();
ListBox1.DataValueField = "community";
ListBox1.DataTextField = "community";
ListBox1.DataBind;
GetCommunites method could be a DataSet, DataTable or DataView like:
Private DataTable GetCommunities()
{

OleDbDataAdapter adapter =new OleDbDataAdapter("SELECT distinct community FROM properties", m_conn);

DataTable dt =new DataTable();

adapter.Fill(dt);


return dt;
}

For your process of the user selected items from the ListBox, you can put a "," at the first or last. But, after that, you need to remove the first "," (if you put at first), or remove the last "," (if you put at the last).


Also, you're treating Community2 like a listbox, as in
Community2.Items.FindByValue("-1")
...but you're also treating it as a string, like this:
Community2 += ",";
...sometimes even in the same statement!

if (Community2 != "") Community2 += ",";

Community2 += Community2.Items[i ].Value;

}
You need to decide which one it is (I'm assuming the former).

0 comments:

Post a Comment