In some cases, folks like to dynamically populate their DataGrids and have the columns autogenerate. I do this most of the time, and also had the need to adjust column width. I've seen ONE post so far in all my searching that mentioned how to do it in code, but it did not work. Below, you will see a simple function that I wrote in C# to address the issue of customizing datagrid child controls.
Right now, this can be used for textboxes, but as I'm sure you can see, expanding it would be pretty darn easy to encompass other child controls.
Feel free to use this code as is or modify to do what you want it to. Here is the sample code also, to use the function....
Example Call Statement:
Code:
AdjustDataGridTextBoxWidth(<Name of DataGrid Here>, "TextBox", 110, 4, TextBoxMode.MultiLine, 8);
The Function Code:
private void AdjustDataGridTextBoxWidth(DataGrid GridName, string SubControlType, Unit Width, int RowsCount, TextBoxMode TBMode, FontUnit FontSize)
{
if (SubControlType == "TextBox")
{
for (int i = 0; i < GridName.Items.Count; i++)
{
for (int o = 1; o < GridName.Items[i].Cells.Count; o++)
{
for (int x = 0; x < GridName.Items[i].Cells[o].Controls.Count; x++)
{
if (GridName.Items[i].Cells[o].Controls[x].GetType().ToString() == "System.Web.UI.WebControls.TextBox")
{
TextBox GridTextBox = (TextBox)GridName.Items[i].Cells[o].Controls[x];
GridTextBox.Width = Width;
GridTextBox.Rows = RowsCount;
GridTextBox.TextMode = TBMode;
GridTextBox.Font.Size = FontSize;
}
}
}
}
}
}