Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an element by ID in C# [closed]

Tags:

c#

.net

asp.net

I want to do something like this in C#

var id = "myID";
id.innerText = "Hello World";

I am a newbie and I'm sure this is pretty simple to do.

like image 849
Dah Problum Avatar asked Jan 15 '13 23:01

Dah Problum


2 Answers

In ASP.NET, this is almost never necessary. For example, if you have a textbox called "txtMyTextBox", you can simply do txtMyTextBox.Text = "Hello World";. You can do this for any element that has the runat="server" attribute.

If you need to find it from a string, you can use FindControl("txtMyTextBox"), but note that this does not search recursively. It will only find direct children of the control you call it on. (You can use a recursive algorithm to find controls recursively).

Finally, if you want to specifically refer to an element by it's HTML ID, you cannot do this. C# runs on the server and does not have direct access to the page.

like image 168
Jonathan Wood Avatar answered Sep 26 '22 03:09

Jonathan Wood


There are loads of ways of doing that

XmlDocument() doc = new XmlDocument();
doc.LoadXml(@"<SomeNodeName id = "myID">Hello World</SomeNodeName>";

Well you fooled me with the mention of innerText there.

I personally wouldn't do this unless I really really had to.

int positionInArray = myGame.IndexOf("MyDiv" + id.ToString());

There are a shed load of assumptions in the above. Finding out what could go wrong with it would be a very good learning exercise.

The answer that mentioned dictionary, that got removed after someone downvoted it would be a better approach

public class SomeObject
{
   private Dictionary<int, String> myGames;
   public SomeObject()
   {
      myGames = new Dictionary<int, string>();
   }
   public AddGame(int id, string desc)
   {
       myGames.Add(id,desc);
   }
   public string FindGameById(int id)
   {
      if(myGames.ContainsKey(id))
      {
         return myGames[id];
      }
      return null;
   }
}
like image 30
Tony Hopkinson Avatar answered Sep 23 '22 03:09

Tony Hopkinson