简体   繁体   中英

How do you get the ID of a control in ASP.NET

I am attempting to loop through an array of numbers, match them to the checkbox they they are associated with, and checkmark that box.

My checkbox is set up like:

<input type="checkbox" runat="server" id="someID" name="somename" value="1234" />

My code when the page loads currently looks like:

foreach (string interest in interests_Var){
   foreach (var c in Page.Controls)
   {
   }
}

interests_Var is my array containing different numbers. We'll assume one of them is 1234 . While looping through the page controls, I want to compare the value of the control to my number. If it equals my number, I want to then apply the attribute checked="checked" . I'm assuming I have to find the ID of the control I am using, then use that ID to add a new attribute. Or is there a way I can add the attribute using the c variable?

I'm not dead set on this setup, so if you know a better way, I'm all ears. Thanks for any help and suggestions.

Thanks

Lots of good suggestions. I will try these in a bit. Got side-tracked on another project.

Solved

Ok, so here's my end code. Thanks for the help James.

foreach (string interest in interests_Var)
{
       foreach (var chkCtrl in Panel1.Controls.OfType<CheckBox>())
       {
           if (chkCtrl.Attributes["value"].ToString() == interest.ToString())
          {
               chkCtrl.Checked = true;
          }
     }
}

I assume you are using multiple checkboxes and have multiple values stored. It is best to use the Asp:Checkbox, rather thatn simply assigning the runat="server" attribute to your input-control.

Let's assume you have a datasource like this:

public class MyClass
{
   public String Name {get;set;}
   public int Number {get;set;}
}

Use this server-control:

<asp:CheckBoxList ID="cblMyList" runat="server" DataTextField="Name" DataValueField="Number">

The Name property will be used as a displaystring, where as the Number is the value that actually is part of the HTTP Post.

In the OnInit-Eventhandler you would probably bind like this:

List<MyClass> values = //...
cblMyList.DataSource = values;
cblMyList.DataBind();
foreach (ListItem item in this.cblMyList.Items)
{
   if(interests.Contains(item.Value))
   {
    item.Selected = true;
   }
}

Getting all selected values would be done with this piece of code:

List<int> selectedValues = cblMyList.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => int.Parse(x.Value)).ToList();

I chose int as the datatype for the DataValueField. Of course you can use other types, just replace the int with the datatype of your choice.

If you assign your check boxes an ID like "interest" + value , then you can use FindControl to look up your check box by interest:

foreach (string interest in interests_Var)
{
    HtmlInputCheckBox checkBox = (HtmlInputCheckBox)this.FindControl("interest" + interest);
    if (checkBox == null)
        throw new InvalidOperationException("Missing check box for " + interest);
    checkBox.Checked = true;
}

You would be best served putting the CheckBox controls into a Panel or a PlaceHolder , because then you won't have to worry about recursive logic to traverse the control hierarchy.

<asp:Panel ID="Panel1" runat="server">
    <asp:CheckBox ID="CheckBox1" runat="server" Text="Testing" value="1234" />
    ...
</asp:Panel>

By putting the controls into a container, you can just loop through the child controls of that element:

foreach (string interest in interests_Var)
{
    foreach (var chkCtrl in Panel1.Controls.OfType<CheckBox>())
    {
        chkCtrl.Checked = chkCtrl.Attributes["value"].Contains(interest.ToString());
    }
}

Assuming interests_Var is a List , here's a shorter way to do it using LINQ:

interests_Var.ForEach(str => plcInvoiceDetail.Controls.OfType<CheckBox>()
    .Select(chk => chk.Checked = chk.Attributes["value"] == str));

If this is a Web Forms app, and you aren't dead set on doing it how you described, you can change your markup to this instead:

<asp:CheckBox id="someID" runat="server" />

Then it will be defined in the.designer.cs file. That way, you can simply reference it in your code like this:

if ( someID.Checked )
{
    // do whatever
}

Note that if it is a control that is dynamically added, you'll still have to use the FindControl() method mentioned by others, because Visual Studio won't have added it to the.designer.cs file for you.

You may use the Array of Controls as described at the following articles:-
http://msdn.microsoft.com/en-us/library/aa289500%28v=VS.71%29.aspx
http://www.codeproject.com/Articles/21159/How-to-Create-a-Control-Array-in-C
For traversing values from the controls you may use the following for reference:-
Add array of controls to an aspx page

And I would recommend you to use ASP.NET Checkbox instead of HTML < input type="checkbox">.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM