如何在C#中通过ID查找元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14348823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:32:25  来源:igfitidea点击:

How to find an element by ID in C#

c#asp.net.net

提问by Dah Problum

I want to do something like this in C#

我想在 C# 中做这样的事情

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

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

我是新手,我相信这很简单。

回答by Jonathan Wood

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.

在 ASP.NET 中,这几乎从来没有必要。例如,如果您有一个名为“txtMyTextBox”的文本框,则只需执行txtMyTextBox.Text = "Hello World";. 您可以对任何具有该runat="server"属性的元素执行此操作。

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 algorithmto find controls recursively).

如果需要从字符串中查找,可以使用FindControl("txtMyTextBox"),但请注意,这不会递归搜索。它只会找到您调用它的控件的直接子级。(您可以使用递归算法递归方式查找控件)。

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.

最后,如果您想通过其 HTML ID 专门引用一个元素,则不能这样做。C# 在服务器上运行,不能直接访问页面。

回答by Tony Hopkinson

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.

好吧,你在那里提到了innerText 愚弄了我。

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;
   }
}