.NET Setting TextBox Width in a DataGrid's Edit Mode

Took me a while to figure this out.  Code is in VB.NET, but easy enough to update it for C# accordingly.

In the databound event of a datagrid, look for an edit item like this:

If e.Item.ItemType = ListItemType.EditItem Then

Then find the textbox you want to work with like this:

Dim txtUserName As TextBox = CType(e.Item.Cells(dgUserListColumns.UserName).Controls(0), TextBox)

A couple of things to note here.  The name of the textbox is arbitrary, but I make it similar to the column name.  Also, I use an enum (named 'dgUserListColumns' here) to set the order of all the columns (hidden or otherwise).  This allows me to update the column list in the enum if I add or subtract a column, and not have to go through all the code and change index numbers.  Also, the index of the control will be different in different cases.  It is almost always 0, as it is here, but if you set the TextMode to Password, for instance, the control index will be 1.  Trial and error with debugging will get you the right value.

Finally, set the width like this:

txtUserName.Width = System.Web.UI.WebControls.Unit.Pixel(100)

You can't just set the width to a value by itself, as you could choose to use Pixel, Percentage, or Point.  It's up to you to decide what you want to use here.

And that's it.  I'm sure there are other ways to do it (I found other examples through Google that for whatever reason (probably user error on my part) didn't seem to work), but this does work.

posted on Saturday, May 21, 2005 4:03 PM Print
# re: .NET Setting TextBox Width in a DataGrid's Edit Mode
3/15/2011 5:59 AM
Its work fine thanks for the cool solution

Post Comment

Title *
Name *
Comment *  
Please add 5 and 2 and type the answer here: