[英]How can I control my textboxes' display using Me.Controls in Vb.net?
I have about four or more textboxes on my screen but I set false to visible.我的屏幕上有大约四个或更多文本框,但我将 false 设置为可见。 As the result (count) of my database table, I want to show the textboxes.
作为我的数据库表的结果(计数),我想显示文本框。 Here is my code.
这是我的代码。
//my datatable list
Dim dl As List(Of String) = dt.Rows.Cast(Of DataRow).Select(Function(dr) dr(0).ToString).ToList
For i As Integer = 1 To dl.Count
Me.Controls("txtSrc" & i.ToString).Visible = True
Next
Then, I have this kind of error.然后,我有这种错误。
InvalidCastException: String The conversion from "lblSrc1" to type'Integer' is invalid.
How can I fix that error?我该如何解决这个错误?
Note;笔记; I am using VS 2019<<ASP.NET webform (using VB.NET)>>
我正在使用 VS 2019<<ASP.NET 网络表单(使用 VB.NET)>>
Ok, unlike say VBA/VB6 - maybe vb.net desktop?好的,不像说 VBA/VB6 - 也许 vb.net 桌面?
You get getting a type conversion error because你得到一个类型转换错误,因为
Me.Controls()
Wants a number (index value) into the controls collection.想要一个数字(索引值)到控件集合中。
So, you can't use a string or "variable" to reference the controls the same way you can say in VBA/Access/VB6因此,您不能像在 VBA/Access/VB6 中所说的那样使用字符串或“变量”来引用控件
So, your example code would become this:因此,您的示例代码将变为:
For i As Integer = 1 To dt.Rows.Count
Dim Tbox As TextBox
Tbox = Me.FindControl("TextBox" & i)
Tbox.Visible = False
Next
Also, there is little (no reason) to convert the data table into a list to get the row count, since a data table as above shows.Rows.Count is the same value此外,几乎没有(没有理由)将数据表转换为列表来获取行数,因为上面的数据表显示.Rows.Count 是相同的值
So所以
Dim dl As List(Of String) = dt.Rows.Cast(Of DataRow).Select(Function(dr) dr(0).ToString).ToList
dim MyRowCount1 as integer = dl.Count
dim MyRowCount2 as integer = dt.Rows.Count
BOTH above will result in the SAME row count value - so you can dump that messy first line of code to convert the dt to a list.上述两者都将产生相同的行计数值 - 因此您可以转储该凌乱的第一行代码以将 dt 转换为列表。 Not required.
不需要。 (so, with above both RowCount1 and RowCount2 would have same value and same result)
(因此,上面的 RowCount1 和 RowCount2 将具有相同的值和相同的结果)
So this should do the trick:所以这应该可以解决问题:
For i As Integer = 1 To dt.Rows.Count
Dim Tbox As TextBox
Tbox = Me.FindControl("TextBox" & i)
Tbox.Visible = False
Next
Firstly, I am sorry that I forgot to say I have a Master page.首先,很抱歉我忘了说我有一个母版页。 So I tried that way and it did work for me.
所以我尝试了这种方式,它确实对我有用。 Thanks.
谢谢。
For i As Integer = 1 To dl.Count
Dim mpContentPlaceHolder As ContentPlaceHolder = CType(Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)
Dim txt As TextBox = CType(mpContentPlaceHolder.FindControl("TextBox" & i), TextBox)
txt.Visible = True
Next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.