概要
本文分步介绍在您排序、插入或删除 DataGrid 行后如何检索当前选中的 DataGrid 行。当您排序、插入或删除 DataGrid 行后,货币管理器仍以实际格式保留数据。修改了 DataGrid 的默认视图,而没有修改货币管理器。 DataGrid 的默认视图合并了行的任何排序、插入或删除。您可以使用默认视图来检索当前选中的 DataGrid 行。返回页首
用于在您排序、插入或删除行后 检索 DataGrid 的当前行的代码示例
若要在您排序、插入或删除行后检索 DataGrid 的当前行,请按下列步骤操作:- 在 Microsoft Visual Studio .NET 中,使用 Microsoft Visual Basic .NET 或 Microsoft Visual C# .NET 创建新的 Windows 应用程序项目。
默认情况下,将创建“Form1”。 - 在工具栏的“数据”选项卡上,双击“SqlDataAdapter”,然后单击“下一步”。
- 单击“新建连接”。键入您的 Microsoft SQL Server 的用户名和密码以连接到 SQL Server。
- 从“选择服务器上的数据库”列表中,单击选中“Northwind”,然后单击“确定”。
- 在创建此连接后,单击“下一步”,然后再单击“下一步”。
- 在“生成 SQL 语句”页上,键入 SQL 语句 Select * from Customers,然后单击“完成”。
- 右键单击“SqlDataAdapter1”,然后单击“生成数据集”。单击“确定”。
- 从工具箱中,将 DataGrid 控件拖到“Form1”上。
- 从工具箱向“Form1”添加两个“按钮”控件和两个“文本框”控件。
- 在解决方案资源管理器中,右键单击“Dataset1”,然后单击“查看代码”。
- 添加下面的代码以便将“DataGrid”与“DataSet”绑定到一起:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Button1.Text = "Get Current Row" Button2.Text = "Sort on City" ' Fill the DataSet with the Data from the database Me.SqlDataAdapter1.Fill(Me.DataSet11) ' Bind the DataGrid with the DataSource DataGrid1.DataSource = DataSet11.Tables(0).DefaultView End Sub
- 将下面的代码添加到“Button1_click”事件处理程序以检索当前行数据:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ' Get the Currency Manager by using the BindingContext of the DataGrid Dim cm As CurrencyManager = CType(Me.BindingContext(DataGrid1.DataSource, DataGrid1.DataMember), CurrencyManager) ' Retrieve the default DataView of the DataGrid Dim dv As DataView = CType(cm.List, DataView) ' Use Currency Manager and DataView to retrieve the Current Row Dim dr As DataRow dr = dv.Item(cm.Position).Row ' Display the Current Row Data TextBox1.Text = dr(0).ToString TextBox2.Text = dr(1).ToString End Sub
- 将下面的代码添加到“Button2_click”事件处理程序以便在“DataGrid”中排序数据:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click ' Sort the Data DataSet11.Tables(0).DefaultView.Sort = "City" ' Refresh the Grid to display the Sorted data DataGrid1.Refresh() End Sub
- 在“生成”菜单上,单击“生成解决方案”。
确认它可以使用
要验证它是否正常工作,请按下面的步骤操作:- 在“调试”菜单上,单击“启动”以运行该应用程序。
- 在“DataGrid”中单击选中一行。
- 单击“获取当前行”。
当前行数据显示在“文本框”中。 - 单击“按城市排序”。
“DataGrid”中的行将根据城市来排序。 - 再次单击“获取当前行”。
当前行数据显示在“文本框”中。
参考
有关其他信息,请单击下面的文章编号,以查看 Microsoft 知识库中相应的文章:308070 HOW TO:Implement a Searchable DataGrid by Using ADO.NET and Windows Forms
313154 HOW TO:Create a Summary Row for a DataGrid in ASP.NET by Using Visual Basic .NET
返回页首这篇文章中的信息适用于:
- Microsoft Visual Basic .NET (2003)
- Microsoft Visual Basic .NET (2002)
最近更新: | 2003-12-23 (2.0) |
关键字: | kbWindowsForms kbSystemData kbSqlClient kbDataBinding kbDatabase kbDataAdapter kbHOWTOmaster KB817247 kbAudDeveloper |