C# datagridview、datagrid、GridControl增加行号

01

 

WinForm中datagridview增加行号

在界面上拖一个控件dataGridView1,在datagridview添加行事件中添加如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            try
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    this.dataGridView1.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
            catch
            {
                MessageBox.Show("处理异常:表格行标题添加异常");
            }
        }

  

这样表格中每次有新行增添就会被自动打标行号.

 

02

 

WPF中datagrid增加行号

WPF类似WinForm中datagridview的表格控件是datagrid,我们可以将行标题添加代码写在LoadingRow事件中:

①附件事件:

一般是在xmal窗体的cs初始化类中:

1
DG.LoadingRow += new EventHandler<DataGridRowEventArgs>(DG_LoadingRow);

  CM框架mvvm模式下:

1
[Event LoadingRow]=[DG_LoadingRow($source,$eventArgs)]"

  DG_LoadingRow事件如下:

1
2
3
4
private void DG_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

  

03

 

WPF dev控件GridControl增加行号

dev控件GridControl没有行增添增添事件,我们可以用下面的方法去做:

 

增加控件引用空间

1
xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"

  

1
2
3
4
5
<dxg:GridControl Name="grid" AutoGenerateColumns="AddNew">
   <dxg:GridControl.View>
        <dxg:TableView RowIndicatorContentTemplate="{StaticResource rowIndicatorContentTemplate}"/>
   </dxg:GridControl.View>
</dxg:GridControl

  定义模板资源

1
2
3
4
5
6
7
8
9
10
<UserControl.Resources>
        <DataTemplate x:Key="rowIndicatorContentTemplate">
            <StackPanel VerticalAlignment="Stretch"
                        HorizontalAlignment="Stretch">
                <TextBlock Text="{Binding Path=RowHandle.Value}"
                           TextAlignment="Center"
                           Foreground="Gray"/>
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>

  

----------------------------------------------------

以上就是本节的全部内容,如果感觉有用,请多多的点击在看和分享,需要进技术交流群的,请加小编微信zls20210502,切记备注 进群

 

posted @   zls366  阅读(176)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示