Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'c# 2005 programmer’s reference - chapter 13', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 250 CHAPTER 13 Databases catch SqlException ex Console.Write ex The following output demonstrates that even though the first INSERT was perfectly fine it never gets added because the second INSERT in the same transaction failed Before attempted inserts 1 Les Miserables 1862 2 Notre-Dame de Paris 1831 3 Le Rhin 1842 Exception occurred rolling back After attempted inserts 1 Les Miserables 1862 2 Notre-Dame de Paris 1831 3 Le Rhin 1842 Bind Data to a Control Using a DataSet Scenario Problem You want to easily display data from a database table on a form. Solution This section introduces the powerful technique of binding data to onscreen controls and allowing .NET to manage the interaction between them. All database binding functionality relies on data sets. Technically a data set can be any IEnumerable collection but often you can use the DataSet class which allows you to store relational data in memory. DataSet objects can be populated from a database after which the connection to the database can be safely closed. Bind Data to a Control in Windows Forms This code assumes the form contains a single DataGridView control See the DataBindingWinForms project for this chapter for the complete source code including all the UI stuff I neglected to copy here. public partial class Form1 Form DataSet _dataSet Bind Data to a Control Using a DataSet 251 public Form1 InitializeComponent _dataSet CreateDataSet dataGridView.DataSource _dataSet.Tables Books protected override void OnFormClosing FormClosingEventArgs e _dataSet.Dispose private DataSet CreateDataSet string connectionString @ Data source BEN-DESKTOP SQLEXPRESS Initial Catalog TestDB Integrated Security SSPI using SqlConnection conn new SqlConnection connectionString conn.Open using SqlCommand cmd new SqlCommand SELECT FROM Books conn using SqlDataAdapter adapter new SqlDataAdapter adapters know how to talk to specific database servers adapter.TableMappings.Add Table Books adapter.SelectCommand cmd DataSet dataSet new .