Question : Auto Textbox Width

I have a asp.net TextBox control in a DataGrid column for inline editing of the row item.  My question is, how do I resize the width of the TextBox automatically when I bind the Data to the Datagrid?

 I am currently creating the Textbox controls ondatabound event of the grid and inserting the text into the textbox control.  Because some text can be very long, I do not want it to be truncated inside the textbox.  Therefore I need a way to resize the textbox based on the length of my text.  And because the grid width = 100%, I am letting the grid handle the column width based on the text it contains.

Please advice.

Answer : Auto Textbox Width

As adilkhan says, you simply need to use the RowDataBound event.  

The second argument gives you the GridViewRow.  You should be able to find the TextBox in the required RowState, and RowType.  Then you can set the Rows property to the Length of the Text.  (Note:  this works if the Width argument has not been set to a value.)

The RowType should be the DataRow, unless you've placed the box in the Header or something.

The RowState matches whatever template(s) in which the TextBox is located.  Eg: Normal, Alternate, Edit, Insert, etcetera.  You can also use Selected if you need to do something special when you select a row.

The TextBox property you wish to alter is actually called Columns!  Odd as this sounds, it sets the length of the TextBox by a number of characters (based the font face and size).  Don't set the Width property, as Columns calculates things for you, so you don't want to override this feature.  (Note: If you have a MultiLine textbox, the Rows property does the same for the display height.)
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
Protected Sub gvYours_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvYours.RowDataBound
   '-- Pick the RowState and RowTypes you need.  Eg:
   If (e.Row.RowType = DataControlRowType.DataRow) and (e.Row.RowState = DataControlRowState.Normal) Then
       Dim T as TextBox = CType(e.Row.FindControl("txtTheBox"), TextBox)
       If T Is Nothing Then
           '-- TODO: TextBox not found in row error handling.
       Else
           T.Columns = T.Text.Length
       End If
    End If
End Sub
Random Solutions  
 
programming4us programming4us