Home > other >  How can I control my textboxes' display using Me.Controls in Vb.net?
How can I control my textboxes' display using Me.Controls in Vb.net?

Time:01-18

I have about four or more textboxes on my screen but I set false to visible. 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)>>

CodePudding user response:

Ok, unlike say VBA/VB6 - maybe vb.net desktop?

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

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

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. Not required. (so, with above both RowCount1 and RowCount2 would have same value and same result)

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

CodePudding user response:

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
  •  Tags:  
  • Related