GridView中的Asp.net VB Test值

时间:2013-01-16 06:42:49

标签: asp.net vb.net gridview

我已经在C#中找到了大量的解决方案但是当你处理FindControls并试图从GridView中取出一个值时,C#没有用,而且翻译的代码不起作用。

我有这个gridview:

<asp:GridView ID="WIPListGrid" runat="server" DataSourceID="WIPDataSource" 
CssClass="site" AutoGenerateColumns="False" 
Width="95%" DataKeyNames="Masterid_Action" onrowdatabound="WIPListGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Action Due Date" HeaderText="Action Due Date" 
SortExpression="Action Due Date" />
</Columns>
</asp:GridView>

我在vb中有这个:     受保护的子WIPListGrid_RowDataBound(发送者为对象,e为System.Web.UI.WebControls.GridViewRowEventArgs)处理WIPListGrid.RowDataBound

Dim DueDate As Label = DirectCast(e.Row.FindControl("Action Due Date"), Label)


'do what ever you want to do here using the value of your label
MsgBox("Due Date = " & DirectCast(e.Row.FindControl("Action Due Date"), Label))



End Sub

错误消息是操作员&amp;没有为类型'String'和'System.Web.UI.WebControls.Label'

定义

这是我真正想做的事情的补救例子。上面我只想显示DueDate中包含的内容,看看它是什么格式,这样我就可以针对其他值进行测试。但它不会起作用。似乎Action Due Date的内容不是字符串...所以,我错过了什么?

我试图将值设置为等于字符串但遇到同样的问题,Label不是字符串......

我如何找出其中的内容以进行评估?

2013年1月17日编辑:保持此活动,因为我仍然没有解决我的问题。

18/01/2013编辑: vb.net代码现在是

Protected Sub WIPListGrid_ROWDataBound(sender as Object, 
e As System.Web.UI.Webcontrols.GridViewRowEventArgs) Handles WIPListGrid.RowDataBound

Dim DueDate As Label = DirectCast(e.Row.FindControl("Action Due Date"), Label)

'do what ever you want to do here using the value of your label
MsgBox("Due Date = " & DueDate.Text)

End Sub

但现在我收到一个错误,即Object未实例化,并且它指向代码中的msgbox行。当我把它变成标签时,我以为我实例化了它......

官方错误是: “对象引用未设置为对象的实例。”

故障排除提示说 1)使用“new”关键字创建对象实例 2)在调用方法之前检查以确定对象是否为空

我尝试了“新”选项,并收到一条错误消息,指出该变量已被声明。 所以现在我想检查以确定对象是否为空并且无法弄清楚如何。

我已经尝试过测试:DirectCast(e.Row.FindControl(“动作截止日期”),标签)&lt;&gt; “” 但得到一个错误:重载决议失败,因为没有可访问的'&lt;&gt;'可以用这些参数调用。

如何测试对象是否为空?

该值不应为null(数据库不允许它为null),但这可能是我的问题的关键......

任何帮助?

2 个答案:

答案 0 :(得分:1)

使用控件时,您必须指出您希望控件中包含该值。

在你的情况下,你只是去标签控制本身(而不是里面的文字)。

例如:

Dim myControl As Label = DirectCast(e.Row.FindControl("myControl"), Label)

MsgBox("MyText = " & myControl.Text)

希望这有帮助。

答案 1 :(得分:0)

问题是您正在使用BoundField,因此无法找到控件。将其更改为模板字段,这将有效。

<asp:GridView ID="WIPListGrid" runat="server" DataSourceID="WIPDataSource" 
CssClass="site" AutoGenerateColumns="False" 
Width="95%" DataKeyNames="Masterid_Action" onrowdatabound="WIPListGrid_RowDataBound">
<Columns>
            <asp:TemplateField HeaderText="Action Due Date">
                <ItemTemplate>
                    <asp:Label ID="lblActionDueDate" runat="server" Text='<%# Bind("[Action Due Date]") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
</Columns>
</asp:GridView>

对于您的行DataBound事件使用

Dim DueDateLabel As Label = DirectCast(e.Row.FindControl("lblActionDueDate"), Label)
'Check Label Exists
If DueDateLabel IsNot Nothing Then
    Dim DueDateText As String = DueDateLabel.Text
    MsgBox(String.Format("Due Date {0}", DueDateText))
End If