public static class GridViewEx
{
public static void SetShowRowNo(this GridView gv)
{
Debug.Assert(gv != null);
gv.OptionsView.ShowIndicator = true;
gv.ResetIndicatorWidth();
//设置行号
gv.CustomDrawRowIndicator += delegate(object sender, RowIndicatorCustomDrawEventArgs e)
{
IndicatorObjectInfoArgs info = e.Info;
if (info == null || !info.IsRowIndicator || e.RowHandle < 0)
return;
info.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
info.DisplayText = (e.RowHandle + 1).ToString();
};
//行数改变
gv.RowCountChanged += delegate(object sender, EventArgs e)
{
GridView selfView = sender as GridView;
if (selfView == null)
return;
selfView.ResetIndicatorWidth();
};
//gv有子表时,展开子表重置其行号宽度
gv.MasterRowExpanded += delegate(object sender, CustomMasterRowEventArgs e)
{
GridView View = sender as GridView;
if (View == null)
return;
GridView dView = View.GetDetailView(e.RowHandle, e.RelationIndex) as GridView;
if (dView == null)
return;
dView.ResetIndicatorWidth();
};
}
/// <summary>
/// 重置行号宽度
/// </summary>
/// <param name="gvw"></param>
/// <param name="rowCount"></param>
public static void ResetIndicatorWidth(this GridView gvw, int rowCount = -1)
{
Debug.Assert(gvw != null);
gvw.IndicatorWidth = GetIndicatorWidth(rowCount == -1 ? gvw.RowCount : rowCount);
}
//行号宽度
private static int GetIndicatorWidth(int p)
{
return 7 * p.ToString().Length + 20;
}
}
引用:
GridView gridView1;
gridView1.SetShowRowNo();