Easy way to add line breaks to Datagrid bound columns
So you want to add line breaks to a datagrid, and you are using bound columns.
You can achieve this as follows -
1. When you insert text into your database use - replace(vbcrlf, "<br>")
2. When you click on the Edit button (ie the datagrid_editcommand) column then use - replace("<br", vbcrlf) . The way I do this is I create a Method and call it immediately after the databinding event.
Protected Sub GridView1_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles GridView1.EditCommand
GridView1.EditItemIndex = e.Item.ItemIndexDim ds As DataSet = GetDataset()
BindGrid(ds)
AddLineBreaks()
End Sub
The AddLineBreaks Method loops through all the rows of the datagrid, and when I find the row that is in EditMode, then I can replace the "<br>" in that row with vbcrlf
Sub AddLineBreaks()
For i = 0 To GridView1.Items.Count - 1
If GridView1.Items(i).ItemType = ListItemType.EditItem Then
CType(GridView1.Items(i).Cells(1).Controls(0), TextBox).TextMode = TextBoxMode.MultiLine
CType(GridView1.Items(i).Cells(1).Controls(0), TextBox).Width = System.Web.UI.WebControls.Unit.Pixel(400)
CType(GridView1.Items(i).Cells(1).Controls(0), TextBox).Height = System.Web.UI.WebControls.Unit.Pixel(100)
CType(GridView1.Items(i).Cells(1).Controls(0), TextBox).Text = CType(GridView1.Items(i).Cells(1).Controls(0), TextBox).Text.Replace("<br>", vbCrLf)
End If
Next
Note that this will also allow you to resize the textboxes during edit mode for a datagrid
The Items collection of a datagrid are it's rows, and each row contains a collection of Cells, and each cell conatins a collection of controls. So you can speify which cells you want to replace <br> with vbcrlf, and which textboxes you want to resize.
3. When you click on the update button then use - replace(vbcrlf, "<br") . The update button in a datagrid triggers the update_command event. This will read the contents of a textbox while in edit mode, and replace vbcrlf with <br>
YOURCOLUMNNAME =
CType(e.Item.Cells(1).Controls(0), TextBox).Text.Replace(vbCrLf, "<br>")
I hope this helps datagrid people with both line breaks and with resizing editmode textboxes.