10

Is it possible to set the ClientID of any asp.net server control? How can I do this?

Ryan Gates
  • 4,501
  • 6
  • 50
  • 90
ebattulga
  • 10,774
  • 20
  • 78
  • 116

7 Answers7

20

The good news is that in VS 2010 .Net 4, you'll have complete control over Client IDs!

Still for the current versions of .Net, you can make due. I assume you need the ID for JavaScript. If so, just get the ID like so:

<script type="text/javascript">
    var myTextBox = $('#<%=TextBox1.ClientID%>');
</script>
Michael La Voie
  • 27,772
  • 14
  • 72
  • 92
4

I would advice against doing this unless you are sure you want to do it, but there is a way. You can override the ClientID property from within the server control.

public override string ClientID
{
    get { return "whatever"; }
}

But as others have noted, you can't do it from outside.

Chetan S
  • 23,637
  • 2
  • 63
  • 78
3

That's not possible. The ClientID is generated by ASP.NET. From MSDN:

The ClientID value is generated by concatenating the ID value of the control and the UniqueID value of its parent control. If the ID value of the control is not specified, an automatically generated value is used.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
1

Even i think it is not possible in Visual studio 2008 . Because Control.ClientID Property has only get method

Edit :But in Visual studio 2010(.Net 4.0) it is possible

anishMarokey
  • 11,279
  • 2
  • 34
  • 47
1

ASP.NET 4 has ClientIDMode property on each control for that. If you want to turn off ClientID completely you can use this trick - it works for any non-postback control

0

This is an ASP.NET 4.0 feature.

Ryan Hoffman
  • 1,146
  • 1
  • 10
  • 22
0

For VS 2010, .NET 4.0:

If you just try to set ctrl.ClientID="stringID" you will get an Error, saying that ClientID is read only. You can control the value of ClientID using ClientIDMode - which defines the algorithm with which ClientID is set:

ctrl.ID = "IDstring";
ctrl.ClientIDMode = ClientIDMode.Static;   //ClientID value is set to the value of ID

The html markup will mark your control's html with the control's ID. Thus you have some degree of control from the code-behind.

Rafael Emshoff
  • 2,541
  • 1
  • 35
  • 47