Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
2 total  XML / RSS feed 

Selected items from a multiple select or checkboxes in VB.net

My co-worker found this code for VB.net that is used to access selected items from check boxes or multiple select boxes. If you've been wondering how to do this, this may help :)

The URL is http://dotnetjunkies.com/weblog/davetrux/archive/2003/11/14/3557.aspx

// The results of a mulitple-select list are also a NameValueCollection
Request.Form.GetValues(i)
// and the individual items are accessed like this:
Request.Form.GetValues(i)(j)

Selecting and checking items from HTML menus

This code allows you to pass in an HTML menu (select, radio, or checkbox) along with a single choice or an array of choices to be selected. The choice(s) should be contained literally in the value attribute.

This is handy for making persistent forms without polluting the HTML with PHP logic. For example, you could initialize all your menus to have nothing selected and then pass in GET or POST variables in case the form was not accepted, easily making form selections persistent.

/**
 * For select menus.
 */
function select_from_menu($menu,$choices,$deselect=true) {
  if ($deselect) $menu = preg_replace('/ selected(="selected")?/','',$menu);
  if(!is_array($choices)) {
    $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 selected=\"selected\"",$menu);
  } else foreach($choices as $value) {
    $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 selected=\"selected\"",$menu);
  }
  
  return $menu;
}

/**
 * For radio buttons and checkboxes.
 */
function check_from_menu($menu,$choices,$deselect=true) {
  if ($deselect) $menu = preg_replace('/ checked(="checked")?/','',$menu);
  if(!is_array($choices)) {
    $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 checked=\"checked\"",$menu);
  } else foreach($choices as $value) {
    $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 checked=\"checked\"",$menu);
  }

  return $menu;
}
« Newer Snippets
Older Snippets »
2 total  XML / RSS feed