Pregunta

I have a gridview using <asp:BoundField DataField="Comments" HeaderText="COMMENTS" />, I would like to only show the first 20 characters in the Commemnt column when the gridview gets populated. Is there way to accomplish this in VB? Thank you.

¿Fue útil?

Solución

One way is using the RowDataBound event in codebehind:

Protected Sub Gridview1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles Gridview1.RowDataBound
    Select Case e.Row.RowType
        Case DataControlRowType.DataRow
            ' assuming the comments column is the first column '
            If e.Row.Cells(0).Text.Length > 20 Then
                e.Row.Cells(0).Text = e.Row.Cells(0).Text.Substring(0, 20)
            End If
    End Select
End Sub

Note that you can access the text on this way only with BoundFields. With TemplateFields you need to use FindControl to get a reference of your controls(f.e. a TextBox).

If you would use a TemplateField you could also limit the text on the aspx markup:

<asp:TemplateField HeaderText="Commnents">
<ItemTemplate>
    <asp:TextBox ID="txtID"  
         MaxLength="20" runat="server" 
         Text='<%# DataBinder.Eval(Container.DataItem, "Comments") %>'>
    </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top