NLV
NLV

Reputation: 21641

Can I change the ID of a asp.net control programatically - ASP.NET

I've a control

<asp:Button ID="btnAjax" runat="server" Text="Ajaxified" OnClick="btnAjax_Click" />

Now from the code behind I want to change the ID of the button

btnAjax.ID = "newButtonID";

But it is now working. Is it possible at the first place?

EDIT

I've created the control in the HTML mark up and not through code.

Upvotes: 6

Views: 11762

Answers (3)

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

Yes you can that Property is both read and write [able].

I tried and yes the ID can be changed and its also reflected in rendered HTML.

Update

There is a ClientIDMode attribute which you can set to 'Static' that you can use to force asp.net into not changing the ID in rendered HTML.

 <asp:Button ID="Button1" runat="server" Text="Button" ClientIDMode="Static" />

Upvotes: 4

Phil
Phil

Reputation: 1061

The only reason I can imagine one would need to achieve something like this is to safely allow client script to interact with the button. If this is the case then I prefer to pass the control's clientID to the script:

var btnAjax = document.getElementById('<%=btnAjax.ClientID%>')

Or using jQuery:

$('#<%=btnAjax.ClientID%>')

Upvotes: 0

Peter Kelly
Peter Kelly

Reputation: 14391

Yes it is possible and your code you posted will work.

I have a button and a text field

<asp:Button ID="button" runat="server" />
<input type="text" id="result" name="result" runat="server" />

On page load I change the ID of the button and then output the result to the text field.

protected void Page_Load(object sender, EventArgs e)
{
    button.ID = "OtherButton";
    result.Value = button.ID;
}

The result in the text field is "OtherButton"

Upvotes: 7

Related Questions