posted by Brad Prendergast at 6:39:00 PM
(2 comments)
Links to this post
Permalink
Code MonkeyLabels: Information, Misc
A DataGridView, DataGridViewCheckBoxColumn, DataGridViewButtonColumn and DataColumn.
As with any “upgrade” new “things” are introduced. In this case I will refer to the DataGridView, DataGridViewCheckBoxColumn and the DataGridViewButtonColumn classes. The allows for the displaying of “data” in a grid (Note: when working with large amounts of data don’t forget to set the VirtualMode property). This source of the data can be anything that implements a IList, IListSource, IBindingList or IBindingListView interface. The data displayed doesn’t always have to be from a database, a one dimmensional array alos works well with a datagrid (take a look at the sample method PopulateDataGridView). It may sound intimidating, but this is all fairly straght forward.
namespace DrawInDataGrid1
...{
public partial class Form1 : Form
...{
private DataTable myTable;
private DataGridViewCheckBoxColumn checkcolumn;
private DataGridViewButtonColumn buttoncolumn;
private DataColumn colItem1, colItem2, colItem3;
private DataRow NewRow;
private DataView myView;
public Form1()
...{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
...{
// DataTable to hold data that is displayed in DataGrid
myTable = new DataTable("myTable");
// the three columns in the table
colItem1 = new DataColumn("CheckBox", Type.GetType("System.Boolean"));
colItem2 = new DataColumn("Button", Type.GetType("System.String"));
colItem3 = new DataColumn("String", Type.GetType("System.String"));
// add the columns to the table
myTable.Columns.Add(colItem1);
myTable.Columns.Add(colItem2);
myTable.Columns.Add(colItem3);
checkcolumn = new DataGridViewCheckBoxColumn(false);
checkcolumn.HeaderText = "CheckBox";
checkcolumn.DataPropertyName = "CheckBox";
buttoncolumn = new DataGridViewButtonColumn();
buttoncolumn.HeaderText = "Button";
buttoncolumn.DataPropertyName = "Button";
dataGridView1.Columns.Add(checkcolumn);
dataGridView1.Columns.Add(buttoncolumn);

// Fill in some data
NewRow = myTable.NewRow();
NewRow[0] = true;
NewRow[1] = "0";
NewRow[2] = "Test";
myTable.Rows.Add(NewRow);
NewRow = myTable.NewRow();
NewRow[0] = false;
NewRow[1] = "1";
NewRow[2] = "Next One";
myTable.Rows.Add(NewRow);
// DataView for the DataGridView
myView = new DataView(myTable);
myView.AllowDelete = false;
myView.AllowEdit = false;
myView.AllowNew = false;
// add an event to check for button click
this.dataGridView1.CellContentClick +=
new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);
// Assign DataView to DataGrid
dataGridView1.DataSource = myView;
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
...{
if (sender is DataGridView)
...{
if ((((DataGridView)sender).Columns[e.ColumnIndex] is DataGridViewButtonColumn) &&
(e.RowIndex >= 0))
...{
MessageBox.Show(e.RowIndex.ToString());
}
}
}
}
}