[英]How do I find enabled/disabled controls using a foreach loop in VB.net?
I am creating a simple guessing game. 我正在创建一个简单的猜谜游戏。 Many of the controls are repetitive, so I'd like to loop through them to databind and search for enabled or disabled controls.
许多控件是重复的,因此我想遍历它们进行数据绑定并搜索启用或禁用的控件。 When I try to run the page after coding either foreach method in my code, I get an "object reference not set to an instance of an object" error.
当我在代码中编码了两种foreach方法后尝试运行页面时,出现“对象引用未设置为对象实例”错误。
How would I fix this without creating a new instance of my control? 如何在不创建控件新实例的情况下解决此问题? I've tried that already;
我已经尝试过了; it doesn't overwrite the existing control on my aspx page.
它不会覆盖我的aspx页面上的现有控件。 Obviously it is creating new ones somewhere, but I'm not sure where;
显然,它正在某个地方创建新的,但是我不确定在哪里。 I don't see well.
我不太清楚。 When I work on the computer I do it at 350% - 400% magnification.
当我在计算机上工作时,会以350%-400%的放大倍率进行操作。
Here is a sample of my aspx page: 这是我的aspx页面的示例:
<div class="Character">
<img src="Images/1.png" style="width: 100%;" /><br />
<asp:DropDownList ID="DDL1" runat="server" CssClass="BigText"></asp:DropDownList><br />
<asp:Button ID="BTN_SubmitGuess1" runat="server" CssClass="BigText Button2" Text="Submit Guess" />
</div>
Here is a sample of my codebehind. 这是我的代码隐藏示例。 I have written my code for both databinding and finding enabled or disabled controls in it:
我已经为数据绑定以及在其中查找启用或禁用的控件编写了代码:
Dim arr() As String = {"One", "Two", "Three", "Four", "Five"}
Dim ddlControls() As DropDownList = {DDL1, DDL2, DDL3, DDL4, DDL5}
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
'What I have now
DDL1.DataSource = arr
DDL1.DataBind()
...
'What I'd like to have
For Each ddl As DropDownList In ddlControls
ddl.DataSource = arr
ddl.DataBind()
End If
Dim remaining As Integer
For Each ddl As DropDownList In ddlControls
If ddl.Enabled = True Then
remaining += 1
End If
Next
LBL_Remaining.Text = CStr(remaining)
End Sub
You have to set the values of your ddlControls array while the page is loading once the DropDownList controls are already created : 一旦创建了DropDownList控件,就必须在页面加载时设置ddlControls数组的值:
Dim arr() As String = {"One", "Two", "Three", "Four", "Five"}
Dim ddlControls() As DropDownList
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlControls = {DDL1, DDL2, DDL3, DDL4, DDL5} ' <<======= HERE
DDL1.DataSource = arr
DDL1.DataBind()
For Each ddl As DropDownList In ddlControls
ddl.DataSource = arr
ddl.DataBind()
Next
End If
Dim remaining As Integer
For Each ddl As DropDownList In ddlControls
If ddl.Enabled = True Then
remaining += 1
End If
Next
Me.Title = CStr(remaining)
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.