C# datagridview、datagrid、GridControl增加行號

01

 

WinForm中datagridview增加行號

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

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初始化類中:

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

  CM框架mvvm模式下:

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

  DG_LoadingRow事件如下:

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

  

03

 

WPF dev控件GridControl增加行號

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

 

增加控件引用空間

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

  

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

  定義模板資源

<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,切記備註 進群

 

Tags: