最近帮朋友写个wince 的程序,要用到DataGrid。wince不能用 datagridview,用datagrid不习惯。数据字段比较长的时候,需要手动拉datagrid,比较麻烦。
网上找来资料,改了改:
public void AutoSizeTable(DataGrid dgData)
{
int numCols = dgData.TableStyles[0].GridColumnStyles.Count;
for (int i = 0; i < numCols; i++)
{
AutoSizeCol(dgData,i);
}
}
private static void AutoSizeCol(DataGrid dgData, int colIndex)
{
int rowNums = ((DataTable)dgData.DataSource).Rows.Count;
Byte[] myByte = System.Text.Encoding.Default.GetBytes(dgData.TableStyles["ROW"].GridColumnStyles
[colIndex].HeaderText);
int textCount = myByte.Length;
int tempCount = 0;
for (int i = 0; i < rowNums; i++)
{
if (dgData[i, colIndex] != null)
{
myByte = System.Text.Encoding.Default.GetBytes(dgData[i, colIndex].ToString().Trim());
tempCount = myByte.Length;
if (tempCount > textCount)
{
textCount = tempCount;
}
}
}
dgData.TableStyles[0].GridColumnStyles[colIndex].Width = textCount * 7;
}
使用时候,报错 什么 索引column不能为负----莫名ing
研究下 ,加入:
// Create a table style that will hold the new column style
// that we set and also tie it to our customer's table from our DB
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = "BOX";
// make the dataGrid use our new tablestyle and bind it to our table
dataGrid1.TableStyles.Clear();
dataGrid1.TableStyles.Add(tableStyle);