原文地址:http://www.cnblogs.com/bengxia/archive/2006/06/08/420529.aspx
方法不错!值得借鉴,简单易懂!
前不久在使用VS.NET 2005开发Pocket PC 2003应用的时候发现DataGrid是不支持即时编辑的,开始总在找DataSource的问题,Google之后找到了问题根源:NET Compact Framework 版本的 DataGrid 的一个主要区别在于它无法在运行时在 DataGrid 中编辑单元格。但是觉得MSDN提供的方案不够理想,就稍微改良了一下。
//由于NetCF上的DataGrid不支持编辑,所以用这个文本框来托管.
private TextBox _cellEditBase = new TextBox();
public FormTest()
{
InitializeComponent();
//初始化DataGrid编辑文本框.
_cellEditBase.Parent = dagRanges;
_cellEditBase.Visible = false;
_cellEditBase.LostFocus += new EventHandler(_cellEditBase_LostFocus);
_cellEditBase.TextChanged += new EventHandler(_cellEditBase_TextChanged);
_cellEditBase.GotFocus += new EventHandler(_cellEditBase_GotFocus);
}
private void _cellEditBase_GotFocus(object sender, EventArgs e)
{
_cellEditBase.SelectAll();
}
private void _cellEditBase_TextChanged(object sender, EventArgs e)
{
try
{
dagRange[_bindCellBase.RowNumber, _bindCellBase.ColumnNumber] = _cellEditBase.Text;
}
catch
{
//TODO: hack the format exception.
}
}
private void _cellEditBase_LostFocus(object sender, EventArgs e)
{
_cellEditBase.Visible = false;
}
//处理DataGrid的CurrentCellChanged事件,以显示文本编辑框.
private void dagRanges_CurrentCellChanged(object sender, EventArgs e)
{
if (RangesTable.Columns[dagRanges.CurrentCell.ColumnNumber].ReadOnly)
{
return;
}
_bindCellBase = dagRanges.CurrentCell;
object objValue = dagRanges [_bindCellBase.RowNumber, _bindCellBase.ColumnNumber];
string cellValue = string.Empty;
if (objValue != null)
{
cellValue = objValue.ToString();
}
_cellEditBase.Text = cellValue;
_cellEditBase.Bounds = dagRanges.GetCellBounds(_bindCellBase.RowNumber, _bindCellBase.ColumnNumber);
_cellEditBase.Visible = true;
_cellEditBase.Focus();
}
2. 修改datagrid的列宽
//设置datagride的列宽
DataGridTableStyle tsMain = new DataGridTableStyle();
YingYangGrid.TableStyles.Add(tsMain);
tsMain.MappingName = yingyangTable.TableName;
tsMain.GridColumnStyles[0].Width = 120; //名称列
tsMain.GridColumnStyles[1].Width = 100; //消化能列
tsMain.GridColumnStyles[2].Width = 80; //粗蛋白列
tsMain.GridColumnStyles[3].Width = 60; //钙列
tsMain.GridColumnStyles[4].Width = 60; //磷列
tsMain.GridColumnStyles[5].Width = 80; //赖氨酸列