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.
Asked
Active
Viewed 2,562 times
0

webaware
- 2,795
- 2
- 30
- 37

g_shockTan
- 325
- 2
- 8
- 15
1 Answers
1
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>

Tim Schmelter
- 450,073
- 74
- 686
- 939
-
The Comment column is on the 7th column. – g_shockTan Jan 29 '13 at 20:22
-
@g_shockTan: Since `GridViewRow.Cells` returns a `TableCellCollection` with an (zero-based)indexer, you can get the correct TableCell via `e.Row.Cells(6)` then. – Tim Schmelter Jan 29 '13 at 20:27
-
I'm getting the following error: Index and length must refer to a location within the string. Parameter name: length. Even when I changed it to the proper column number. – g_shockTan Jan 29 '13 at 20:33
-
@g_shockTan: Have you used my code above with the `If` clause around? – Tim Schmelter Jan 29 '13 at 20:37
-
Thanks. That was wierd. I thought I copied and pasted everything including the If statement, but it was missing. It works now, but would like to add a ..... at the end to show more comments are available. – g_shockTan Jan 29 '13 at 21:15
-
@Time Schmelter. Thank you Tim. You are the man. It works and looks perfect. Consider question as resolved. – g_shockTan Jan 29 '13 at 21:50