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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With