I was asked to do some WinForm programming the other day, which I haven't done for a couple of years now, because, as most of you are aware, I'm more a ASP.NET man with the occasional Win Mob thrown in. And boy, was it good to be back! I forgot how easy it was to do EVERYTHING! You don't have to worry about CSS, state management, session vars...
Anyway, let me cut to the chase. I wanted to use the DataGridView, populate it with data, and based on the data coming out of the DB, highlight certain cells, not rows, with the colour red and make the cell editable. Well, as you know, the DataGridView is editable by default, so I was on a mission. And the last requirement was to show only certain columns out of the entire data set, so I needed a way of creating the columns. So, let me get to the point. Below is how to create the columns:
dataGridView1.Columns.Add(
"Reason code(s)",
"Reason code(s)");
dataGridView1.Columns.Add(
"Value0",
"Value0");
dataGridView1.Columns.Add(
"Size 1",
"Value1");
The first field is the column name, which I believe you can reference with something like: dataGridView1["ColumnName"], but don't quote me, and the second field is the header text for the column. The final requirement for the columns, was to have a hidden column which would hold the unique key back in the DB. Here you have to create a new DataGridView column and text box cell and set it properties, like so:
DataGridViewColumn newColl =
new DataGridViewColumn();
newColl.HeaderText =
"";
newColl.Name =
"NoteID";
newColl.DataPropertyName =
"NoteID";
DataGridViewCell oCell =
new DataGridViewTextBoxCell();
newColl.CellTemplate = oCell;
newColl.Width = 90;
dataGridView1.Columns.Add(newColl);
GetMobaOutuput();
Finally, I needed to highlight certain cells in red and make the editable and anything outside of the if, not editable. Here goes:
dataGridView1.CurrentCell = dataGridView1.Rows[count].Cells[0];
dataGridView1.BeginEdit(
true);
dataGridView1.Rows[count].Cells[0].ReadOnly =
false;
dataGridView1.Rows[count].Cells[0].Style.Font =
new Font(
"Verdana", 10,
FontStyle.Bold);
dataGridView1.Rows[count].Cells[0].Style.BackColor =
Color.Red;
You seem to need to call the BeginEdit method before you can alter the properties. It was the ReadOnly property that took me a long time to find. Setting it to false means that it's editable and vice versa.