在ASP.NET Gridview的RowDataBound事件中,我试图在模板字段中读取Label的值。我更喜欢在RowUpdating事件中捕获这个值,但出于某种原因我似乎记得它是不可能的。这是ASP ......
<asp:TemplateField HeaderText="Translation" ItemStyle-Width="250" >
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("lang_String") %>' Width="250px"></asp:Label>
</ItemTemplate>
这是我试图找出的VB.net代码....
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
' The value in the third column postion.
Dim needThisValue as string = e.Row.Cells(3).Text
End If
End Sub
非常感谢任何和所有帮助。
感谢,
答案 0 :(得分:3)
我不确定为什么您认为自己的标签位于EditItemTemplate
,因为您选择了RowState=DataControlRowState.Edit
。
实际上你需要检查RowType=DataControlRowType.DataRow
。这是必需的,因为第一行的RowType
是标题。
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.rowtype.aspx
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
' in the following way you get the row's DataSource: '
Dim row = DirectCast(e.Row.DataItem, DataRowView).Row
' you could also use the DataSource to get the value: '
Dim lang_String = row.Field(Of String)("lang_String")
' and here you get the reference to your Label in the ItemTemplate: '
Dim Label11 = DirectCast(e.Row.FindControl("Label11"), Label)
' at this point Label11.Text is already set to lang_String '
End If
End Sub
如果你想获得EditItemTemplate
的控件,你需要检查RowState,例如在你的GridView中(通常你会在EditItemTemplate
中使用像TextBox这样的可编辑控件):
<ItemTemplate>
<asp:Label ID="LblLanguage" runat="server" Text='<%# Bind("lang_String") %>' Width="250px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtLanguage" runat="server" Text='<%# Bind("lang_String") %>' Width="250px"></asp:TextBox>
</EditItemTemplate>
RowDataBound
中的:
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
' in the following way you get the row's DataSource: '
Dim row = DirectCast(e.Row.DataItem, DataRowView).Row
' you could also use the DataSource to get the value: '
Dim lang_String = row.Field(Of String)("lang_String")
If e.Row.RowState = DataControlRowState.Normal Then
' and here you get the reference to your Label in the ItemTemplate: '
Dim LblLanguage = DirectCast(e.Row.FindControl("LblLanguage"), Label)
' at this point LblLanguage.Text is already set to lang_String '
ElseIf e.Row.RowState = DataControlRowState.Edit Then
' and here you get the reference to your TextBox in the EditItemTemplate: '
Dim TxtLanguage = DirectCast(e.Row.FindControl("TxtLanguage"), TextBox)
' at this point TxtLanguage.Text is already set to lang_String '
End If
End If
End Sub
请注意,我已将控件的ID更改为更具可读性。