WPF DataGrid 绑定DataSet数据 自动生成行号

本文介绍了如何在WPF应用程序中使用DataGrid控件进行数据绑定,并提供了自定义列及行号的方法。通过示例代码展示了如何设置DataGrid的列显示及如何在加载时为每一行添加行号。

1、绑定数据:dataGrid1.ItemsSource = dataSet.Tables[0].DefaultView;

注意:在创建DataGrid 时可以通过AutoGenerateColumns 属性设置列是否自动生成,从而加入自定义列。如果DataGrid 中同时包含“自动生成列”与“用户自定义列”,则首先创建“用户自定义列”。DataGrid 支持的四种列及其数据类型见下表:

2011050122124711.png

DataGrid绑定列名、数据列代码:


  
1 < DataGrid.Columns >
2 < DataGridTextColumn Header = " 客户编码 " Binding = " {Binding CustomerCode} " />
3 < DataGridTextColumn Header = " 客户名称 " Binding = " {Binding CustomerName} " />
4 < DataGridTextColumn Header = " 证件号码 " Binding = " {Binding CardID} " />
5 < DataGridTextColumn Header = " 固定电话 " Binding = " {Binding Phone} " />
6 < DataGridTextColumn Header = " 移动电话 " Binding = " {Binding MobilePhone} " />
7 < DataGridTextColumn Header = " 电子邮件 " Binding = " {Binding Email} " />
8 < DataGridTextColumn Header = " QQ " Binding = " {Binding QQ} " />
9 < DataGridTextColumn Header = " 联系地址 " Binding = " {Binding Address} " />
10 </ DataGrid.Columns >

简单的数据显示可以在sql语句中将字段名另存在(as)中文列名,直接在DataGrid中作为列名使用。

2、自动生成行号(关键是最后一句):


  
1 private void Window_Loaded( object sender, RoutedEventArgs e)
2 {
3 LoadDataGrid();
4 }
5
6 private void LoadDataGrid()
7 {
8 dataGrid1.ItemsSource = UserDAL.GetUserDataSet().Tables[ 0 ].DefaultView; // 读取用户并刷新datagrid
9   dataGrid1.LoadingRow += new EventHandler < DataGridRowEventArgs > (dataGrid_LoadingRow);
10 }
11
12 public void dataGrid_LoadingRow( object sender, DataGridRowEventArgs e)
13 {
14 e.Row.Header = e.Row.GetIndex() + 1 ;
15 }

转载于:https://www.cnblogs.com/dinid/articles/2021271.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值