views:

169

answers:

2

My gridview has a template field with a label in it. I want to label the field using the QuestionID so that it doesn't create duplicate id's.

I tried doing the following:

<asp:TemplateField HeaderText="No">
    <InsertItemTemplate>
        <label id='<%# (string.Format("Label_{0}", 
                                DataBinder.Eval(Container.DataItem,"QuestionID"))) %>'
                   runat="server"></asp:Label>  
    </InsertItemTemplate>
</asp:TemplateField>

But I got an error saying

The ID property of a control can only be set using the ID attribute in the tag and a simple value.

Does anyone know how to make it so that I can assign an id without it creating duplicate id's? I would like a way of accessing each one using javascript.

Thanks,
Matt

A: 

First of all, you're not getting this error because of the duplicate IDs. Whatever you give to your server control as ID, asp.net generates a new ID and renders it. Your exception is about evaluating the value into ID property I think.

IMO, let the asp.net generate the ID's for your labels. Add a class to your labels, and use JQuery to get all instances of your labels.

As an alternative, asp:Labels rendering spans as output, so you can change your code like that :

<asp:TemplateField HeaderText="No">
    <InsertItemTemplate>
        <span id='<%= (string.Format("Label_{0}", 
                                DataBinder.Eval(Container.DataItem,"QuestionID"))) %>'>
        </span>
    </InsertItemTemplate>
</asp:TemplateField>
Canavar
A: 

Check out this question. It will put in your Ids in a manner easily retrieved by Javascript.

Dillie-O