2
votes

how would i bind a comma separated string such as: monday,tuesday to a list box control as these items being selected when the list box is already populated as such? sunday monday tuesday wednesday thursday friday saturday

I started with the following code:

string days = null;
List<string> lstdays = new List<string>();

//I get the values from a table such as:

foreach (DataRow dr in dt.Rows) {
//other items
days = dr(7).ToString();
}


if (days.Contains(",")) {
//days =  Tuesday,Thursday

}
else
{
  //days = Monday
 lstbxDays.SelectedValue = days;  //means there is a single day
}
4
I find your question quite suspicios. What are you trying to achieve (the greater goal)? - Santhos
want to bind a comma separate list to a listbox and show those items as being selected - user3642720

4 Answers

3
votes

You can use Split() method for strings:

string[] newDays=days.Split(',');

foreach (string d in newDays)
{
 lstDays.Add(d);  //add single day to days List
}

If you have also defined a listBox , say listbox1, you can say:

listbox1.DataSource=lstDays;

if you have bind the days to your listbox then on the event that the user selects a day ( I don't know how you set it in your program, through button , grid etc) you can set:

listbox1.SelectedValue = day; //where day is the var user selects
1
votes

If you are getting the data from a DataTable, then something like

void BindDayList( ListBox lb , DataTable dt , string textColumnName , string valueColumnName )
{
  lb.DataSource     = dt              ;
  lb.DataTextField  = textColumnName  ;
  lb.DataValueField = valueColumnName ;
  lb.DataBind()     ;
  return ;
}

If you've got a flat string then something like the following would probably work:

void BindDayList( ListBox lb , string listOfDays )
{
  int i = 0 ;
  lb.DataSource = days
                  .Split(',')
                  .Select( x => new ListItem( (++i).ToString() , x.Trim() ) )
                  ;
  lb.DataBind() ;
  return ;
}
0
votes

You can do this

lstbxDays.DataSource = days.Split(','); 

considering days is your comma separated string
Hope this helps!

0
votes

thanks everyone as the examples helped - got it working with this code to select multiple days:

//days = tuesday,thursday

string[] s = days.Split(new char[] { ',' });

foreach (string lst in s)
{
 lstbxDays.Items.FindByText(lst.ToString()).Selected = true;
}