7.10. Creating Custom Columns in a Windows Forms DataGrid
Problem
You need to create a
DataGrid having
columns with custom formatting and attributes.
Solution
Use the
DataGridTableStyle
class.
The sample code contains two event handlers:
Form.LoadSets up the sample by creating a
DataAdapterand using it to fill aDataTablewith data from the ProductID, ProductName, and Discontinued columns of the Products table in the Northwind database. TheDataGridTableStyleclass is used to define a data grid containing three custom columns—two text boxes and one check box—corresponding to the ProductID, ProductName, and Discontinued columns. Finally, the default view of the ProductsDataTableis bound to the data grid on the form.- Update
Button.Click Uses the
DataAdaptercreated in theForm.Loadevent handler to update changes made to the ProductsDataTableback to the database.
The C# code is shown in Example 7-18.
Example 7-18. File: CustomColumnsInDataGridForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; private SqlDataAdapter da; private DataTable dt; // . . . private void CustomColumnsInDataGridForm_Load(object sender, System.EventArgs e) { // Create the DataAdapter. String selectCommand = "SELECT ProductID, ProductName, Discontinued " + "FROM Products"; da = new SqlDataAdapter(selectCommand, ConfigurationSettings.AppSettings["Sql_ConnectString"]); // Use CommandBuilder to handle ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access