Formatting DataGridView cell with custom DataSource
Posted on January 13, 2010
When you use a custom DataSource (in my case a generic list) the properties become the columns and the property names, become the column header.
I needed to format a DateTime field, so I did this:
1 2 3 4 5 6 7 8 9 | private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "Date") { DateTime value = (DateTime)e.Value; e.Value = value.ToString("G"); e.FormattingApplied = true; } } |
In this case, "Date" is the property name of a DateTime field.
In case you are curious, the DataSource assignment is like this:
1 2 3 | List<GoodReceipts> grrs = new List<GoodReceipts>(); grrs.AddRange(logic.GetGRRData(consumptions, validSince, validTo)); dataGridView1.DataSource = grrs; |
DataGridView EditOnEnter and row deleting
Posted on December 21, 2009
When you're working in a datagridview, sometimes is useful to use the EditOnEnter edit mode.
But for some reason (i.e. Bug) the deleting functionality is broken under this scheme.
To overcome this, you could use this little hack.
You'll need 2 events:
CellEnter
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) { DataGridView dgv = sender as DataGridView; if (dgv != null) { dgv.EditMode = DataGridViewEditMode.EditOnEnter; } }
MouseClick
private void dataGridView1_MouseClick(object sender, MouseEventArgs e) { DataGridView dgv = sender as DataGridView; if (dgv != null) { DataGridView.HitTestInfo hti = dgv.HitTest(e.X, e.Y); if (hti.Type == DataGridViewHitTestType.RowHeader) { dgv.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2; dgv.EndEdit(); } } }