True DBGrid for WinForms can display data without being bound to a DataSource. Creating an unbound grid can be done in a few steps.
To create an unbound grid, complete the following:
C# |
Copy Code
|
---|---|
// Create columns trueDBGrid1.Columns.Add(new C1DataColumn("FirstName", typeof(string))); trueDBGrid1.Columns.Add(new C1DataColumn("LateName", typeof(string))); trueDBGrid1.Columns.Add(new C1DataColumn("DateOfBirth", typeof(DateTime))); |
C# |
Copy Code
|
---|---|
// Call SetDataBinding method with zero arguments
trueDBGrid1.SetDataBinding();
|
C# |
Copy Code
|
---|---|
// Use AddRow to populate the grid trueDBGrid1.AddRow("John;Doe;11/29/1985"); trueDBGrid1.AddRow("Jane;Doe;7/12/1980"); int index = this.trueDBGrid1.AddRows(2); for (int i = index; i < 2; i++) { this.trueDBGrid1[i, "FirstName"] = "Joe"; this.trueDBGrid1[i, "LastName"] = "Doe"; this.trueDBGrid1[i, "DateOfBirth"] = new DateTime(2000, 1, 15); } |
You have successfully created an unbound grid.
You can now easily add new rows to an unbound grid by using the C1TrueDBGrid.NewRow method which creates a new System.Data.DataRow with the same schema as the unbound grid. In the following steps you'll use the C1TrueDBGrid.Rows collection, which gets the DataRowCollection for an unbound grid, and the C1TrueDBGrid.NewRow method to insert a new row into the specified index of an unbound grid.
Complete the following steps:
C# |
Copy Code
|
---|---|
using C1.Win.TrueDBGrid;
|
C# |
Copy Code
|
---|---|
private void Form1_Load(object sender, EventArgs e) { // Add a caption to the grid. trueDBGrid1.Caption = "Unbound Grid"; // Add columns to the grid. trueDBGrid1.Columns.Add(new C1DataColumn("Col 1", typeof(string))); trueDBGrid1.Columns.Add(new C1DataColumn("Col 2", typeof(string))); trueDBGrid1.Columns.Add(new C1DataColumn("Col 3", typeof(string))); trueDBGrid1.Columns.Add(new C1DataColumn("Col 4", typeof(string))); // Call the SetDataBinding method with no arguments. trueDBGrid1.SetDataBinding(); // Populate the grid. for (int i = 0; i < 20; i++) { string s = String.Format("Data {0};Data {1};Data {2}; Data {3}", i, i, i, i); trueDBGrid1.AddRow(s); } } |
C# |
Copy Code
|
---|---|
private void button1_Click(object sender, EventArgs e) { int idx = (int)this.numericUpDown1.Value; // Create a new row. DataRow dr = trueDBGrid1.NewRow(); dr[0] = "new row"; // Add the new row at the selected index. trueDBGrid1.Rows.InsertAt(dr, idx); } |
The form will appear similar to the following:
Use the arrows to change the number in the New Row Index box and then select the Add New Row button. The new row will appear at the index that you chose: