2011-03-02 73 views
0

我通过遍历数组:如何在ASP.NET中动态构造控件名称?

Dim dbConfig As New pbu_housingEntities 
    Dim possible() As String = {"FROD", "FRCD", "SOOD", "SOCD", "JROD", "JRCD", "SROD", "SRCD", "SR5OD", "SR5CD"} 
    For Each value As String In possible 
     Dim current_value = value 
     Dim exists = From p In dbConfig.Configs _ 
        Where p.Description = current_value 
        Select p 

     If exists.Count.Equals(0) Then 
      Dim create As New Config 
      create.Description = current_value 
      dbConfig.Configs.AddObject(create) 
      dbConfig.SaveChanges() 
     Else 
      Dim update_query = (From p In dbConfig.Configs _ 
           Where p.Description = current_value _ 
           Select p) 
      update_query.First.Description = current_value 
      update_query.First.dateValue = 
     End If 
    Next 

迈向数组的结尾可以看到update_query.First.dateValue =,我想要做这样的事情:

update_query.First.dateValue = "txt" + current_value + ".Text" 

但我不希望它返回文本txtcurrent_value.Text,而是返回txtcurrent_value.Text的文本值。这是很容易做到,如果你知道每个控件的名字 - 但在这种情况下,我迭代,否则我可以这样做:

update_query.First.dateValue = txtNameofControl.Text 

回答

2

获取像这样控制一个参考:

TextBox tb = Page.FindControl("txt" + current_value) as TextBox; 
update_query.First.dateValue = tb.Text; 
+0

我使用这段代码,但遇到了一个问题...... tb值总是变成“Nothing” - 尽管我知道一个控件存在“txt”+ current_value作为它的名字! – davemackey 2011-03-03 16:12:55

+0

如果您使用的是MasterPage,找到控件的路径有点不同。我不知道它在我头顶,但我会说只是不断尝试去实现它。尝试MasterPage.Page.Controls.FindControl或其变种。 – TheGeekYouNeed 2011-03-03 17:25:58