views:

83

answers:

2

Hi,

I have never used the datagridview in any other scenario other than one where it is populating by a database so suddenly my mind goes blank...

I have 10 tubes, each with 8 vertical positions within it, so I have a 10 by 8 grid basically. Each has of those slots has (or not) an image in a folder. How do I get a datagridview to reflect this information, draw a grid, check the folder and if the image exists paint it white, and if not paint it red?

Sorry it if sounds a little odd, thanks, R.

A: 

Assuming it's called DataGridView1 that contains 10 columns and that you've got a method called ImageExists that accepts 2 int indexes the following should work:

dataGridView1.AllowUserToAddRows = false;
dataGridView1.ReadOnly = true;
for (int rowIndex = 0; rowIndex < 8; rowIndex++)
{
     DataGridViewRow row = new DataGridViewRow();
     row.CreateCells(dataGridView1);
     dataGridView1.Rows.Add(row);
     for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++)
     {
          if (!ImageExists(rowIndex, cellIndex))
                row.Cells[cellIndex].Style.BackColor = Color.Red;                        
     }
}
ho1
A: 

This may work nicely with a grid set in virtual mode:

  • Set the grid's VirtualMode property to True.
  • Add a handler to the CellValueNeeded event, something along the lines of:

.

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.RowCount = 8;
    dataGridView1.ColumnCount = 10;
}

private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
    var bgColor = ((0 == e.ColumnIndex % 2) && (0 == e.RowIndex % 2))
        ? Color.Red
        : Color.White;
    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = bgColor;
}

Of course, the % 2 stuff would be replaced with actual image existence checking.

More on DataGridView in virtual mode here.

Sorin Comanescu