Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trying to get ID from Selected Checkboxes on page

Status
Not open for further replies.

wadey

Programmer
Jun 6, 2006
54
GB
Hi,

Scenario:-

I have a web page with a listing of items. besides each item is a checkbox. At the top of the page is a delete button. User selects his items to delete and presses delete button.

Problem:-

My codebehind should cycle through each control on page, if its a checkbox and its checked get the ID of the checkbox.
However it doesn't work.

Code:-

private void isCheckedAndAdd(Control ctrl)
{



if (ctrl is CheckBox && ((CheckBox)ctrl).Checked)
{

///Do your stuff with a checked Checkbox.
string sAccomodationId = ctrl.ID.ToString();

}

foreach (Control c in ctrl.Controls)
{

isCheckedAndAdd(c);

}

}


protected void Delete_OnClick(object sender, EventArgs e)
{
isCheckedAndAdd(this);

}


Questions:-

1. Is this the best way to do this?
2. Any ideas why this doesn't work?

Regards
 
if you have a list of checkboxes use a checkboxklist and bind the value/text to the control, then cycle through the list items in that control
Code:
//page load
if(!ispostback)
{
  mycheckboxlist.DataSource = GetOptions();
  mycheckboxlist.DataBind();
}

//on button click
foreach(ListItem item in mycheckboxlist.Items)
{
   if(item.Selected)
   {
      DeleteRecordBy(item.Value);
   }
}

if you want to stick with your current setup, then you need to make the function recrusive
Code:
void ProcessCheckBox(Control control)
{
   CheckBox cb = control as CheckBox;
   if(cb != null)
   {
       if(cb.Checked)
         DeleteRecordBy(item.Value);
       return;
   }
   foreach(Control child in control.Controls)
   {
      ProcessCheckBox(child);
   }
}

//click event
ProcessCheckBox(this);

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top