带有可变按钮文本的VB.NET网格视图

时间:2013-09-05 15:00:41

标签: vb.net button gridview

如何根据gridview

中的值更改Gridview中按钮的文本

例如,在下面的代码中,如何为年龄低于40的行设置按钮文本为YOUNG,为高于或等于40的行设置OLD

<asp:GridView ID="GV_DataByGroupAct" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Age" HeaderText="Age" />
        <asp:BoundField DataField="Hight" HeaderText="Hight" />
        <asp:ButtonField Text="Young/Old" />
    </Columns>
</asp:GridView>

由于

2 个答案:

答案 0 :(得分:0)

我会使用TemplateField代表真正的Button控件和RowDataBound作为您的逻辑:

ASPX:

<asp:GridView ID="GV_DataByGroupAct" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Age" HeaderText="Age" />
        <asp:BoundField DataField="Hight" HeaderText="Hight" />
        <asp:TemplateField>
           <ItemTemplate>
              <asp:Button ID="BtnYoungOld" runat="server" Text="Young/Old" />
           </ItemTemplate>
       </asp:TemplateField>
    </Columns>
</asp:GridView>

代码隐藏:

Private Sub GV_DataByGroupAct_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GV_DataByGroupAct.RowDataBound
    Select Case e.Row.RowType
        Case DataControlRowType.DataRow
            Dim row = DirectCast(e.Row.DataItem, DataRowView)
            Dim age As Int32 = Int32.Parse(row("age").ToString)
            Dim BtnYoungOld = DirectCast(e.Row.FindControl("BtnYoungOld"), Button)
            BtnYoungOld.Text = If(age < 40, "YOUNG", "OLD")
    End Select
End Sub

答案 1 :(得分:0)

您需要处理网格视图的RowDataBound事件,以便在绑定时更改每行上按钮文本的内容,如下所示:

Protected Sub GridView1_RowDataBound(sender As [Object], e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        ' Put logic here to check age and then update button text
    End If
End Sub