尝试动态访问表单字段名称 [英] Trying to access form field names dynamically
问题描述
大家好,
我正在尝试动态填充表单中的字段,其中代码会将字段名称与表单上的字段名称进行匹配(在表单上,该名称以txt开头.
因此,数据库中的字段为CustomerDescription,表单上的字段为txtCustomerDescription.
问题在于Fieldname.text无法正常工作.也许它将其视为文本,但是如何将其转换为字段对象?
我当前得到的错误是: System.Data.dll中出现类型为"System.InvalidOperationException"的第一次机会异常
Hi Everyone,
I am trying to dynamically fill fields in a form where the code will match the field name to the field name on the form (on the form the name is prepended with txt.
So my field in my database would be CustomerDescription and my feild on the form would be txtCustomerDescription.
The problem is that Fieldname.text isn''t working. Perhaps it see''s it as text but how do I convert it to a field object?
error I currently get is: A first chance exception of type ''System.InvalidOperationException'' occurred in System.Data.dll
For Each value As String In FieldNameArray
Try
Dim FieldName As Object
FieldName = "txt" & value
Console.WriteLine(FieldName)
FieldName.text = reader("" & value & "").ToString
Catch
End Try
Next
感谢任何可以提供帮助的人.
〜Jack
Thanks to Anyone who can help.
~Jack
推荐答案
此处要做的是构建一个名为"txt" +值的字符串,然后用退出阅读器的内容覆盖该字符串.
您不能将字符串转换为字段"对象.
除非这里有某些驱动程序阻止您这样做,否则为什么不遍历窗体上的控件集合呢?
对于表单中的每个控件,将其强制转换为文本框并检查是否为空.如果不为null,则检查名称是否包含数据库字段(或等于"txt" +字段名称),然后设置text属性.
一小段代码:
What you are doing here is building a string called "txt" + value and then overwriting that string with what you pull out of the reader.
You can''t convert a string to a "field" object.
Unless there is some driver here that prevents you from doing so, why not loop through the collection of controls on the form?
For each of the controls in the form, cast it to a textbox and check for null. If not null, then check to see if the name contains the database field (or if it equals "txt" + field name) and then set the text property.
a snippet of code:
For Each ctl In frm.Controls
' ...
Next ctl
现在,ctl是一个控件(如果需要的话,是一个字段对象),您可以检查它是否是文本框,然后在其上设置文本.
干杯.
Now, ctl is a control (a field object, if you will) and you can check to see if it is a textbox and then set the text on it.
Cheers.
这篇关于尝试动态访问表单字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!