BCS
BCS

Reputation: 78635

How to use DataBinding to set the ID of asp:CheckBox controls

I have some ASP that I want to look kinda of like this:

<asp:DataGrid ID="dgEnum" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>
                <asp:CheckBox ID="<%# some big DataBinder expression %>" runat="server" />
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

but that gives me a:

Parser Error Message: The ID property of a control can only be set using the ID attribute in the tag and a simple value. Example: <asp:Button runat="server" id="Button1" />

Anyone have an idea how to hack around that?

Upvotes: 0

Views: 7077

Answers (2)

Mark Brackett
Mark Brackett

Reputation: 85665

Anyone have an idea how to hack around that?

You can't, and you don't. You can store the required data somewhere besides the ID. At the very least, a sibling HiddenField could be used.

<script runat="server">
    void Checkbox_CheckedChanged(object sender, EventArgs e) {
       var c = (Checkbox)sender;
       if (!c.Checked) {
           return;
       }
       var hfv = (HiddenField)c.Parent.FindControl("hfvMyData");
       var myData = hfv.Value;
       /* Do something with myData */
    }
</script>

<asp:DataGrid ID="dgEnum" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>
               <asp:CheckBox runat="server" OnCheckedChanged="Checkbox_CheckedChanged" />
               <asp:HiddenField id="hfvMyData" runat="server" Value='<%# Eval("MyData") %>' />
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>    

Other options could be DataKeys, a server side (perhaps cached or Session data) indexed list, or a ViewState indexed list.

If you really wanted to bastardize WebForms, you can put your data into CssClass...but that's just crazy. ;)

Upvotes: 2

David McEwing
David McEwing

Reputation: 3340

Not sure what you are intending to do here, but you can just go straight to the html controls ie <input type="checkbox" id="<%# some expresssion %>" />

Or you don't do this and query for it on the server side. I.e. find the row you want and then use FindControls() to get the checkbox for that row.

Upvotes: 0

Related Questions