Hi to all,

I like to reach all the cells by column name in a loop( foreach...) and
compare the content of the cell in datetime type and add a value to another cell depending on the result of the comparison. I do this for all the populated rows.
Question is how do I locate a particular cell in each row.

Thanks in advance
snakay

serkan sendur commented: N/A -2

Recommended Answers

All 7 Replies

Hi snakay, welcome to DANIWEB.

A DataGridView has a Rows property which is of type DataGridViewRowCollection. You could use that if you want.
Usually I just index like this : dataGridView[0, 2].Value = something...
Which is the first cell of the third row.

Hi ddanbe,

with - dataGridView[0, 2].Value = something... - you are assuming that you know the indexes of row and column. If it is sequential reading of grid with foreach, I mean the whole table, it should come from program. And column index I have to find it by giving the column name. So it is current row and index by column name. I hope I made myself clear.

thanks
snakay

Try this:

private void button3_Click(object sender, EventArgs e)
    {

      StringBuilder sb = new StringBuilder();
      foreach (DataGridViewColumn col in dataGridView1.Columns)
      {
        sb.AppendLine(col.Name);
      }
      MessageBox.Show("Column Names: " + Environment.NewLine + sb.ToString());


      foreach (DataGridViewRow gridRow in dataGridView1.Rows)
      {
        if (gridRow.IsNewRow)
          continue;

        string nameLast = Convert.ToString(gridRow.Cells["nameLastDataGridViewTextBoxColumn"].Value);
        int custId = Convert.ToInt32(gridRow.Cells["custNumberDataGridViewTextBoxColumn"].Value);
      }
    }

Try to search or manipulate data in datasource object (DataTable) instead of ViewControls (datagridView).

thank you very much sknake,

I did the job perfect, took sometime becouse confused with continue after the new row test.Good example

regards
snakay

You're welcome.

Please mark this thread solved as you have found an answer to your issue and good luck!

Like to attach what I did just in case someone needs;

// right after populating dataGridView

StringBuilder sb = new StringBuilder();
                   foreach (DataGridViewColumn col in myGridView.Columns)
                    { 
                       sb.AppendLine(col.Name); 
                    } 
                    MessageBox.Show("Column Names: " + Environment.NewLine + sb.ToString());

                   foreach (DataGridViewRow r in myGridView.Rows)
DateTime dt = Convert.ToDateTime(r.Cells["colDate"].Value);
TimeSpan MyDays = (Convert.ToDateTime(txtBoxDate.Text)).Subtract(dt);
 int MyMonths = ((Convert.ToDateTime(txtBoxDate.Text.Text)).Month) - ((dt).Month);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.