Csharp/C Sharp/Database ADO.net/DataGridView
Содержание
- 1 Bind DataGridView to Array
- 2 Bind List to DataGridView
- 3 Custom DataGridView with DataGridViewTextBoxColumn, DataGridViewImageColumn,DataGridViewComboBoxColumn
- 4 Data Source with Generic Collection
- 5 Setup Columns for DataGridView
- 6 Set up DataGridView from DataColumn
- 7 Use DataViewRowState to filter DataGridView
Bind DataGridView to Array
<source lang="csharp"> using System; using System.Collections.Generic; using System.ruponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; public class Form1 : Form {
public Form1() { InitializeComponent(); } private void getData_Click(object sender, EventArgs e) { Item[] items = new Item[] { new Item ( "One" ) , new Item ( "Two" ) , new Item ( "Three" ) }; dataGridView1.AutoGenerateColumns = true; dataGridView1.DataSource = items; } protected class Item { public Item(string text) { m_text = text; } public string Text { get { return m_text; } } private string m_text; } private void InitializeComponent() { this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.getData = new System.Windows.Forms.Button(); ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(12, 12); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(268, 223); this.dataGridView1.TabIndex = 0; this.getData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.getData.Location = new System.Drawing.Point(204, 242); this.getData.Name = "getData"; this.getData.Size = new System.Drawing.Size(75, 23); this.getData.TabIndex = 1; this.getData.Text = "Get Data"; this.getData.UseVisualStyleBackColor = true; this.getData.Click += new System.EventHandler(this.getData_Click); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 271); this.Controls.Add(this.getData); this.Controls.Add(this.dataGridView1); ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.Button getData; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
}
</source>
Bind List to DataGridView
<source lang="csharp"> using System; using System.Collections.Generic; using System.ruponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;
using System; using System.Collections.Generic; using System.ruponentModel; using System.Drawing; using System.Text; public class Person {
public Person(string name, Sex sex, DateTime dob) { _name = name; _sex = sex; _dateOfBirth = dob; } public string Name { get { return _name; } set { _name = value; } } public Sex Sex { get { return _sex; } set { _sex = value; } } public DateTime DateOfBirth { get { return _dateOfBirth; } set { _dateOfBirth = value; } } private string _name; private Sex _sex; private DateTime _dateOfBirth;
} public enum Sex {
Male, Female
} class PersonList : List<Person> { } public class Form1 : Form {
public Form1() { InitializeComponent(); } private void getData_Click(object sender, EventArgs e) { PersonList people = new PersonList(); people.Add(new Person("F", Sex.Male, new DateTime(1970, 12, 14))); people.Add(new Person("B", Sex.Male, new DateTime(1976, 10, 29))); people.Add(new Person("J", Sex.Male, new DateTime(1945, 5, 17))); people.Add(new Person("J", Sex.Female, new DateTime(1982, 1, 3))); dataGridView1.AutoGenerateColumns = true; dataGridView1.DataSource = people; } private void InitializeComponent() { this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.getData = new System.Windows.Forms.Button(); ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(13, 13); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(267, 217); this.dataGridView1.TabIndex = 0; // this.getData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.getData.Location = new System.Drawing.Point(205, 236); this.getData.Size = new System.Drawing.Size(75, 23); this.getData.Text = "Get Data"; this.getData.UseVisualStyleBackColor = true; this.getData.Click += new System.EventHandler(this.getData_Click); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 271); this.Controls.Add(this.getData); this.Controls.Add(this.dataGridView1); this.Text = "DataSourceGenericCollection"; ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.Button getData; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
}
</source>
Custom DataGridView with DataGridViewTextBoxColumn, DataGridViewImageColumn,DataGridViewComboBoxColumn
<source lang="csharp"> using System; using System.Collections.Generic; using System.ruponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Windows.Forms; class Form1 : Form {
public Form1() { InitializeComponent(); } private void getData_Click(object sender, EventArgs e) { getData.Enabled = false; using (SqlConnection con = new SqlConnection(ConfigurationSettings.ConnectionStrings["northwind"].ConnectionString)) { string select = "SELECT EmployeeID, FirstName, LastName, Photo, IsNull(ReportsTo,0) as ReportsTo FROM Employees"; SqlDataAdapter da = new SqlDataAdapter(select, con); DataSet ds = new DataSet(); da.Fill(ds, "Employees"); select = "SELECT EmployeeID, FirstName + " " + LastName as Name FROM Employees union select 0,"(None)""; da = new SqlDataAdapter(select, con); da.Fill(ds, "Managers"); SetupColumns(ds); dataGridView.AutoGenerateColumns = false; dataGridView.DataSource = ds.Tables["Employees"]; dataGridView.AutoSizeRows(DataGridViewAutoSizeRowsMode.HeaderAndColumnsAllRows); } } private void SetupColumns(DataSet ds) { DataGridViewTextBoxColumn forenameColumn = new DataGridViewTextBoxColumn(); forenameColumn.DataPropertyName = "FirstName"; forenameColumn.HeaderText = "Forename"; forenameColumn.ValueType = typeof(string); forenameColumn.Frozen = true; dataGridView.Columns.Add(forenameColumn); DataGridViewTextBoxColumn surnameColumn = new DataGridViewTextBoxColumn(); surnameColumn.DataPropertyName = "LastName"; surnameColumn.HeaderText = "Surname"; surnameColumn.Frozen = true; surnameColumn.ValueType = typeof(string); dataGridView.Columns.Add(surnameColumn); DataGridViewImageColumn photoColumn = new DataGridViewImageColumn(); photoColumn.DataPropertyName = "Photo"; photoColumn.Width = 200; photoColumn.HeaderText = "Image"; photoColumn.ReadOnly = true; photoColumn.ImageLayout = DataGridViewImageCellLayout.Normal; dataGridView.Columns.Add(photoColumn); DataGridViewComboBoxColumn reportsToColumn = new DataGridViewComboBoxColumn(); reportsToColumn.HeaderText = "Reports To"; reportsToColumn.DataSource = ds.Tables["Managers"]; reportsToColumn.DisplayMember = "Name"; reportsToColumn.ValueMember = "EmployeeID"; reportsToColumn.DataPropertyName = "ReportsTo"; dataGridView.Columns.Add(reportsToColumn); } private void InitializeComponent() { this.getData = new System.Windows.Forms.Button(); this.dataGridView = new System.Windows.Forms.DataGridView(); this.SuspendLayout(); // // getData // this.getData.Location = new System.Drawing.Point(661, 544); this.getData.Name = "getData"; this.getData.TabIndex = 0; this.getData.Text = "Get Data"; this.getData.Click += new System.EventHandler(this.getData_Click); // // dataGridView // this.dataGridView.AllowUserToAddRows = false; this.dataGridView.AllowUserToDeleteRows = false; this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView.Location = new System.Drawing.Point(13, 13); this.dataGridView.Name = "dataGridView"; this.dataGridView.Size = new System.Drawing.Size(722, 522); this.dataGridView.TabIndex = 1; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(748, 579); this.Controls.Add(this.dataGridView); this.Controls.Add(this.getData); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } private System.Windows.Forms.Button getData; private System.Windows.Forms.DataGridView dataGridView; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.EnableRTLMirroring(); Application.Run(new Form1()); }
}
</source>
Data Source with Generic Collection
<source lang="csharp">
using System; using System.Collections.Generic; using System.ruponentModel; using System.Drawing; using System.Text; using System; using System.Collections.Generic; using System.ruponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; public class Person {
public Person(string name, Sex sex, DateTime dob) { _name = name; _sex = sex; _dateOfBirth = dob; } public string Name { get { return _name; } set { _name = value; } } public Sex Sex { get { return _sex; } set { _sex = value; } } public DateTime DateOfBirth { get { return _dateOfBirth; } set { _dateOfBirth = value; } } private string _name; private Sex _sex; private DateTime _dateOfBirth;
} public enum Sex {
Male, Female
} class PersonList : List<Person> { } public class SexDisplay {
public SexDisplay(Sex s) { _sex = s; _caption = s.ToString(); } public Sex Sex { get { return _sex; } } public string Caption { get { return _caption; } } private Sex _sex; private string _caption;
} public class SexList : List<SexDisplay> { } class Form1 : Form {
public Form1() { InitializeComponent(); } private void getData_Click(object sender, EventArgs e) { PersonList people = new PersonList(); people.Add(new Person("F", Sex.Male, new DateTime(1970, 12, 14))); people.Add(new Person("B", Sex.Male, new DateTime(1976, 10, 29))); people.Add(new Person("J", Sex.Male, new DateTime(1945, 5, 17))); people.Add(new Person("J", Sex.Female, new DateTime(1982, 1, 3))); dataGridView.AutoGenerateColumns = true; dataGridView.DataSource = people; } private void Stuff() { DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn(); nameColumn.DataPropertyName = "Name"; nameColumn.Name = "Name"; nameColumn.HeaderText = "Name"; nameColumn.ValueType = typeof(string); dataGridView.Columns.Add(nameColumn); DataGridViewButtonColumn buttonCol = new DataGridViewButtonColumn(); buttonCol.Text = "Hello"; buttonCol.Name = "Hello"; buttonCol.HeaderText = "Hello"; buttonCol.ValueType = typeof(string); buttonCol.DataPropertyName = "Name"; dataGridView.Columns.Add(buttonCol); DataGridViewCheckBoxColumn checkCol = new DataGridViewCheckBoxColumn(); checkCol.HeaderText = "Blah"; dataGridView.Columns.Add(checkCol); DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn(); comboCol.HeaderText = "Combo"; SexList sl = new SexList(); sl.Add(new SexDisplay(Sex.Male)); sl.Add(new SexDisplay(Sex.Female)); comboCol.DataSource = sl; comboCol.DisplayMember = "Caption"; comboCol.ValueMember = "Sex"; comboCol.DataPropertyName = "Sex"; dataGridView.Columns.Add(comboCol); DataGridViewLinkColumn linkCol = new DataGridViewLinkColumn(); linkCol.HeaderText = "Link"; linkCol.Text = "Bibble"; dataGridView.Columns.Add(linkCol); linkCol.DataPropertyName = "DateOfBirth"; } private void dataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e) { int i = 0; } private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e) { int i = 0; } private void InitializeComponent() { this.getData = new System.Windows.Forms.Button(); this.dataGridView = new System.Windows.Forms.DataGridView(); this.SuspendLayout(); // // getData // this.getData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.getData.Location = new System.Drawing.Point(776, 600); this.getData.Name = "getData"; this.getData.TabIndex = 0; this.getData.Text = "Get Data"; this.getData.Click += new System.EventHandler(this.getData_Click); // // dataGridView // this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView.Location = new System.Drawing.Point(13, 13); this.dataGridView.Name = "dataGridView"; this.dataGridView.Size = new System.Drawing.Size(837, 573); this.dataGridView.TabIndex = 1; this.dataGridView.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellClick); this.dataGridView.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView_DataError); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(863, 635); this.Controls.Add(this.dataGridView); this.Controls.Add(this.getData); this.ResumeLayout(false); } private System.Windows.Forms.Button getData; private System.Windows.Forms.DataGridView dataGridView; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.EnableRTLMirroring(); Application.Run(new Form1()); }
}
</source>
Setup Columns for DataGridView
<source lang="csharp">
using System; using System.Collections.Generic; using System.ruponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Configuration; using System.Data.SqlClient; // CustomDataGridView public class Form1 : Form {
public Form1() { InitializeComponent(); } private void getData_Click(object sender, EventArgs e) { getData.Enabled = false; using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwind"].ConnectionString)) { string select = "SELECT EmployeeID, FirstName, LastName, Photo, IsNull(ReportsTo,0) as ReportsTo FROM Employees"; SqlDataAdapter da = new SqlDataAdapter(select, con); DataSet ds = new DataSet(); da.Fill(ds, "Employees"); select = "SELECT EmployeeID, FirstName + " " + LastName as Name FROM Employees union select 0,"(None)""; da = new SqlDataAdapter(select, con); da.Fill(ds, "Managers"); SetupColumns(ds); dataGridView1.AutoGenerateColumns = false; dataGridView1.DataSource = ds.Tables["Employees"]; dataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells); } } private void SetupColumns(DataSet ds) { DataGridViewTextBoxColumn forenameColumn = new DataGridViewTextBoxColumn(); forenameColumn.DataPropertyName = "FirstName"; forenameColumn.HeaderText = "Forename"; forenameColumn.ValueType = typeof(string); forenameColumn.Frozen = true; dataGridView1.Columns.Add(forenameColumn); DataGridViewTextBoxColumn surnameColumn = new DataGridViewTextBoxColumn(); surnameColumn.DataPropertyName = "LastName"; surnameColumn.HeaderText = "Surname"; surnameColumn.Frozen = true; surnameColumn.ValueType = typeof(string); dataGridView1.Columns.Add(surnameColumn); DataGridViewImageColumn photoColumn = new DataGridViewImageColumn(); photoColumn.DataPropertyName = "Photo"; photoColumn.Width = 200; photoColumn.HeaderText = "Image"; photoColumn.ReadOnly = true; photoColumn.ImageLayout = DataGridViewImageCellLayout.Normal; dataGridView1.Columns.Add(photoColumn); DataGridViewComboBoxColumn reportsToColumn = new DataGridViewComboBoxColumn(); reportsToColumn.HeaderText = "Reports To"; reportsToColumn.DataSource = ds.Tables["Managers"]; reportsToColumn.DisplayMember = "Name"; reportsToColumn.ValueMember = "EmployeeID"; reportsToColumn.DataPropertyName = "ReportsTo"; dataGridView1.Columns.Add(reportsToColumn); } private void InitializeComponent() { this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.getData = new System.Windows.Forms.Button(); ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(13, 13); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(507, 372); this.dataGridView1.TabIndex = 0; // // getData // this.getData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.getData.Location = new System.Drawing.Point(445, 391); this.getData.Name = "getData"; this.getData.Size = new System.Drawing.Size(75, 23); this.getData.TabIndex = 1; this.getData.Text = "Get Data"; this.getData.UseVisualStyleBackColor = true; this.getData.Click += new System.EventHandler(this.getData_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(532, 426); this.Controls.Add(this.getData); this.Controls.Add(this.dataGridView1); this.Name = "Form1"; this.Text = "CustomDataGridView"; ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); }
private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.Button getData; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
}
</source>
Set up DataGridView from DataColumn
<source lang="csharp"> using System; using System.Collections.Generic; using System.ruponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; public class Car {
public string carPetName, carMake, carColor; public Car(string petName, string make, string color) { carPetName = petName; carColor = color; carMake = make; }
} public class MainForm : Form {
private List<Car> arTheCars = new List<Car>(); private DataTable inventoryTable = new DataTable("Inventory"); DataView coltsOnlyView; // I only show red colts. public MainForm() { InitializeComponent(); arTheCars.Add(new Car("C", "BMW", "Green")); arTheCars.Add(new Car("T", "Y", "White")); arTheCars.Add(new Car("AAA", "Jeep", "Tan")); arTheCars.Add(new Car("PInducer", "Caravan", "Pink")); arTheCars.Add(new Car("F", "BMW", "Pea Soup Green")); arTheCars.Add(new Car("B", "BMW", "Black")); arTheCars.Add(new Car("M", "DDD", "Red")); arTheCars.Add(new Car("S", "Colt", "Black")); CreateDataTable(); CreateDataView(); } private void CreateDataTable() { DataColumn carIDColumn = new DataColumn("CarID", typeof(int)); carIDColumn.ReadOnly = true; carIDColumn.Caption = "Car ID"; carIDColumn.AllowDBNull = false; carIDColumn.Unique = true; carIDColumn.AutoIncrement = true; carIDColumn.AutoIncrementSeed = 0; carIDColumn.AutoIncrementStep = 1; carIDColumn.ColumnMapping = MappingType.Attribute; DataColumn carMakeColumn = new DataColumn("Make", typeof(string)); DataColumn carColorColumn = new DataColumn("Color", typeof(string)); DataColumn carPetNameColumn = new DataColumn("PetName", typeof(string)); carPetNameColumn.Caption = "Pet Name"; inventoryTable.Columns.AddRange(new DataColumn[] { carIDColumn, carMakeColumn, carColorColumn, carPetNameColumn }); inventoryTable.PrimaryKey = new DataColumn[] { inventoryTable.Columns[0] }; foreach (Car c in arTheCars) { DataRow newRow = inventoryTable.NewRow(); newRow["Make"] = c.carMake; newRow["Color"] = c.carColor; newRow["PetName"] = c.carPetName; inventoryTable.Rows.Add(newRow); } carInventoryGridView.DataSource = inventoryTable; } private void CreateDataView() { coltsOnlyView = new DataView(inventoryTable); coltsOnlyView.RowFilter = "Make = "Colt""; dataGridColtsView.DataSource = coltsOnlyView; } private void btnRemoveRow_Click(object sender, EventArgs e) { try { inventoryTable.Rows[(int.Parse(txtRowToRemove.Text))].Delete(); inventoryTable.AcceptChanges(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnGetMakes_Click(object sender, EventArgs e) { string filterStr = string.Format("Make= "{0}" ", txtMakeToGet.Text); DataRow[] makes = inventoryTable.Select(filterStr, "PetName DESC"); if (makes.Length == 0) MessageBox.Show("Sorry, no cars...", "Selection error!"); else { string strMake = null; for (int i = 0; i < makes.Length; i++) { DataRow temp = makes[i]; strMake += temp["PetName"] + "\n"; } MessageBox.Show(strMake, txtMakeToGet.Text + " type(s):"); } } private void btnChangeBeemersToColts_Click(object sender, EventArgs e) { string filterStr = "Make="BMW""; string strMake = null; DataRow[] makes = inventoryTable.Select(filterStr); for (int i = 0; i < makes.Length; i++) { DataRow temp = makes[i]; strMake += temp["Make"] = "Colt"; makes[i] = temp; } } private void ShowCarsWithIdLessThanFive() { DataRow[] properIDs; string newFilterStr = "ID > "5""; properIDs = inventoryTable.Select(newFilterStr); string strIDs = null; for (int i = 0; i < properIDs.Length; i++) { DataRow temp = properIDs[i]; strIDs += temp["PetName"] + " is ID " + temp["ID"] + "\n"; } MessageBox.Show(strIDs, "Pet names of cars where ID > 5"); } private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.carInventoryGridView = new System.Windows.Forms.DataGridView(); this.btnRemoveRow = new System.Windows.Forms.Button(); this.txtRowToRemove = new System.Windows.Forms.TextBox(); this.txtMakeToGet = new System.Windows.Forms.TextBox(); this.btnGetMakes = new System.Windows.Forms.Button(); this.btnChangeBeemersToColts = new System.Windows.Forms.Button(); this.dataGridColtsView = new System.Windows.Forms.DataGridView(); this.label2 = new System.Windows.Forms.Label(); ((System.ruponentModel.ISupportInitialize)(this.carInventoryGridView)).BeginInit(); ((System.ruponentModel.ISupportInitialize)(this.dataGridColtsView)).BeginInit(); this.SuspendLayout(); // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(11, 76); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(102, 13); this.label1.TabIndex = 0; this.label1.Text = "All Cars in DataTable"; // this.carInventoryGridView.Location = new System.Drawing.Point(12, 93); this.carInventoryGridView.Name = "carInventoryGridView"; this.carInventoryGridView.Size = new System.Drawing.Size(392, 150); this.carInventoryGridView.TabIndex = 1; this.carInventoryGridView.Text = "dataGridView1"; // this.btnRemoveRow.Location = new System.Drawing.Point(12, 13); this.btnRemoveRow.Name = "btnRemoveRow"; this.btnRemoveRow.Size = new System.Drawing.Size(101, 23); this.btnRemoveRow.TabIndex = 2; this.btnRemoveRow.Text = "Remove Row #"; this.btnRemoveRow.Click += new System.EventHandler(this.btnRemoveRow_Click); // this.txtRowToRemove.Location = new System.Drawing.Point(120, 15); this.txtRowToRemove.Name = "txtRowToRemove"; this.txtRowToRemove.Size = new System.Drawing.Size(100, 20); this.txtRowToRemove.TabIndex = 3; // this.txtMakeToGet.Location = new System.Drawing.Point(120, 44); this.txtMakeToGet.Name = "txtMakeToGet"; this.txtMakeToGet.Size = new System.Drawing.Size(100, 20); this.txtMakeToGet.TabIndex = 5; // // btnGetMakes // this.btnGetMakes.Location = new System.Drawing.Point(12, 42); this.btnGetMakes.Name = "btnGetMakes"; this.btnGetMakes.Size = new System.Drawing.Size(101, 23); this.btnGetMakes.TabIndex = 4; this.btnGetMakes.Text = "Get These Makes"; this.btnGetMakes.Click += new System.EventHandler(this.btnGetMakes_Click); // // btnChangeBeemersToColts // this.btnChangeBeemersToColts.Location = new System.Drawing.Point(245, 15); this.btnChangeBeemersToColts.Name = "btnChangeBeemersToColts"; this.btnChangeBeemersToColts.Size = new System.Drawing.Size(159, 23); this.btnChangeBeemersToColts.TabIndex = 6; this.btnChangeBeemersToColts.Text = "Change BMW to Colts"; this.btnChangeBeemersToColts.Click += new System.EventHandler(this.btnChangeBeemersToColts_Click); // // dataGridColtsView // this.dataGridColtsView.Location = new System.Drawing.Point(12, 266); this.dataGridColtsView.Name = "dataGridColtsView"; this.dataGridColtsView.Size = new System.Drawing.Size(392, 150); this.dataGridColtsView.TabIndex = 8; this.dataGridColtsView.Text = "dataGridView1"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(11, 249); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(76, 13); this.label2.TabIndex = 7; this.label2.Text = "Colts Only View"; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(417, 433); this.Controls.Add(this.dataGridColtsView); this.Controls.Add(this.label2); this.Controls.Add(this.btnChangeBeemersToColts); this.Controls.Add(this.txtMakeToGet); this.Controls.Add(this.btnGetMakes); this.Controls.Add(this.txtRowToRemove); this.Controls.Add(this.btnRemoveRow); this.Controls.Add(this.carInventoryGridView); this.Controls.Add(this.label1); this.Name = "MainForm"; this.Text = "Car Data Table"; ((System.ruponentModel.ISupportInitialize)(this.carInventoryGridView)).EndInit(); ((System.ruponentModel.ISupportInitialize)(this.dataGridColtsView)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } private System.Windows.Forms.Label label1; private System.Windows.Forms.DataGridView carInventoryGridView; private System.Windows.Forms.Button btnRemoveRow; private System.Windows.Forms.TextBox txtRowToRemove; private System.Windows.Forms.TextBox txtMakeToGet; private System.Windows.Forms.Button btnGetMakes; private System.Windows.Forms.Button btnChangeBeemersToColts; private System.Windows.Forms.DataGridView dataGridColtsView; private System.Windows.Forms.Label label2; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); }
}
</source>
Use DataViewRowState to filter DataGridView
<source lang="csharp"> DataSourceDataView using System; using System.Collections.Generic; using System.ruponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Configuration; using System.Data.SqlClient; // public class Form1 : Form {
public Form1() { InitializeComponent(); } private void getData_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwind"].ConnectionString)) { string select = "SELECT * FROM products"; SqlDataAdapter da = new SqlDataAdapter(select, con); DataSet ds = new DataSet(); da.Fill(ds, "Products"); originalData.AutoGenerateColumns = true; originalData.DataSource = ds.Tables["Products"]; DataView dv = new DataView(ds.Tables["Products"]); filteredData.AutoGenerateColumns = true; filteredData.DataSource = dv; comboBox1.SelectedIndex = 6; comboBox1.Enabled = true; } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { DataViewRowState state; switch (comboBox1.Text) { case "Added": state = DataViewRowState.Added; break; case "CurrentRows": state = DataViewRowState.CurrentRows; break; case "Deleted": state = DataViewRowState.Deleted; break; case "ModifiedCurrent": state = DataViewRowState.ModifiedCurrent; break; case "ModifiedOriginal": state = DataViewRowState.ModifiedOriginal; break; case "None": state = DataViewRowState.None; break; case "OriginalRows": state = DataViewRowState.OriginalRows; break; case "Unchanged": state = DataViewRowState.Unchanged; break; default: state = DataViewRowState.OriginalRows; break; } try { ((DataView)filteredData.DataSource).RowStateFilter = state; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void InitializeComponent() { this.originalData = new System.Windows.Forms.DataGridView(); this.getData = new System.Windows.Forms.Button(); this.ruboBox1 = new System.Windows.Forms.ruboBox(); this.filteredData = new System.Windows.Forms.DataGridView(); this.label1 = new System.Windows.Forms.Label(); ((System.ruponentModel.ISupportInitialize)(this.originalData)).BeginInit(); ((System.ruponentModel.ISupportInitialize)(this.filteredData)).BeginInit(); this.SuspendLayout(); // // originalData // this.originalData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.originalData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.originalData.Location = new System.Drawing.Point(12, 12); this.originalData.Name = "originalData"; this.originalData.Size = new System.Drawing.Size(600, 214); this.originalData.TabIndex = 0; // // getData // this.getData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.getData.Location = new System.Drawing.Point(536, 501); this.getData.Name = "getData"; this.getData.Size = new System.Drawing.Size(75, 23); this.getData.TabIndex = 1; this.getData.Text = "Get Data"; this.getData.UseVisualStyleBackColor = true; this.getData.Click += new System.EventHandler(this.getData_Click); // // comboBox1 // this.ruboBox1.DropDownStyle = System.Windows.Forms.ruboBoxStyle.DropDownList; this.ruboBox1.Enabled = false; this.ruboBox1.FormattingEnabled = true; this.ruboBox1.Items.AddRange(new object[] { "Added", "CurrentRows", "Deleted", "ModifiedCurrent", "ModifiedOriginal", "None", "OriginalRows", "Unchanged"}); this.ruboBox1.Location = new System.Drawing.Point(108, 232); this.ruboBox1.Name = "comboBox1"; this.ruboBox1.Size = new System.Drawing.Size(502, 21); this.ruboBox1.TabIndex = 2; this.ruboBox1.SelectedIndexChanged += new System.EventHandler(this.ruboBox1_SelectedIndexChanged); // // filteredData // this.filteredData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.filteredData.Location = new System.Drawing.Point(12, 259); this.filteredData.Name = "filteredData"; this.filteredData.Size = new System.Drawing.Size(598, 236); this.filteredData.TabIndex = 3; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 233); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(29, 13); this.label1.TabIndex = 4; this.label1.Text = "Filter"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(624, 536); this.Controls.Add(this.label1); this.Controls.Add(this.filteredData); this.Controls.Add(this.ruboBox1); this.Controls.Add(this.getData); this.Controls.Add(this.originalData); this.Name = "Form1"; this.Text = "04_DataSourceDataView"; ((System.ruponentModel.ISupportInitialize)(this.originalData)).EndInit(); ((System.ruponentModel.ISupportInitialize)(this.filteredData)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); }
private System.Windows.Forms.DataGridView originalData; private System.Windows.Forms.Button getData; private System.Windows.Forms.ruboBox comboBox1; private System.Windows.Forms.DataGridView filteredData; private System.Windows.Forms.Label label1; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
}
</source>