我们只想显示OrderID、CustomerID、OrderDate这三个字段,并且想将OrderID的列表头显示为“订单号”,CustomerID显示为“客户号”,OrderDate显示为“订单日期”,这就要用TableStyles来控制了。
新建一个TableStyle,将此TableStyle.MappingName属性对应到这个TableStyle要控制的那个DataTable的名字:
DataGridTableStyle myTableStyle = new DataGridTableStyle();
myTableStyle.MappingName = "myDateTable";
再建立三个DataGridColumnStyle,分别用来控制将要显示的三个列:
DataGridColumnStyle myColumnStyle1 = new DataGridTextBoxColumn();
myColumnStyle1.MappingName = "OrderID";
myColumnStyle1.HeaderText = "订单号";
DataGridColumnStyle myColumnStyle2 = new DataGridTextBoxColumn();
myColumnStyle2.MappingName = "CustomerID";
myColumnStyle2.HeaderText = "客户号";
DataGridColumnStyle myColumnStyle3 = new DataGridTextBoxColumn();
myColumnStyle3.MappingName = "OrderDate";
myColumnStyle3.HeaderText = "订单日期";
将这三个DataGridColumnStyle添加到TableStyle中:
myTableStyle.GridColumnStyles.Add(myColumnStyle1);
myTableStyle.GridColumnStyles.Add(myColumnStyle2);
myTableStyle.GridColumnStyles.Add(myColumnStyle3);
最后将TableStyle添加到DataGrid中:
dataGrid1.TableStyles.Add(myTableStyle);
将 TableStyle添加到DataGrid后,再绑定数据源,这时我们就会看到这样的数据显示了:
figure-2
◆ DataGrid的编辑修改
DataGrid支持对DataGrid所显示的DataTable的编辑修改,只要DataGrid的ReadOnly属性为False,就可以在DataGrid中直接修改单元中的内容,修改完后数据将直接反应到此DataGrid对应的那个DataTable的单元。
如果这个DataTable是通过vs.net的可视化数据设计器新建DataAdapter,并生成了SelectCommand、 InsertCommand、UpdateCommand、DeleteCommand这四个命令,用DataAdapter的Fill方法得来的,那么事情就简单了,修改过的DataTable你可以直接用DataAdapter的UpDate方法写回到数据库。下面看一下vs.net的可视数据数据器生成的InsertCommand命令:
this.sqlInsertCommand1.CommandText = @"INSERT INTO Customers(CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax) VALUES (@CustomerID, @CompanyName, @ContactName, @ContactTitle, @Address, @City, @Region, @PostalCode, @Country, @Phone, @Fax); SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers WHERE (CustomerID = @CustomerID)";
this.sqlInsertCommand1.Connection = this.sqlConnection2;
this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@CustomerID", System.Data.SqlDbType.NVarChar, 5, "CustomerID"));
this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@CompanyName", System.Data.SqlDbType.NVarChar, 40, "CompanyName"));
this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ContactName", System.Data.SqlDbType.NVarChar, 30, "ContactName"));
this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ContactTitle", System.Data.SqlDbType.NVarChar, 30, "ContactTitle"));
this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Address", System.Data.SqlDbType.NVarChar, 60, "Address"));
来源:http://www.002pc.com/master/College/Programming/aspnet/13247.html
DataTable,DataView和DataGrid中一些容易混淆的(3)
最新推荐文章于 2024-08-27 15:51:22 发布