将值从单元格分配给另一个单元格

时间:2012-04-24 09:46:50

标签: c#

int rowsCount = 0;
//This checks to see that both textbox for items and subitems do not gain focus at the same time
if (textBoxSubItems.Text != string.Empty)
    txtItems.Enabled = false;
else 
    txtItems.Enabled = true;
if (comboBoxItems.SelectedItem != null)
{

    int idx = dataGridViewTimesheet.Rows.Add();
    DataGridViewRow row = dataGridViewTimesheet.Rows[idx];
    row.Cells["items"].Value = comboBoxItems.SelectedItem.ToString() + "-" + textBoxSubItems.Text;
    row.Cells["fromTime"].Value = DateTime.Now.ToLongTimeString();
    row.Cells["toTime"].Value = null;
    row.Cells["duration"].Value = null;
    row.Cells["subTotal"].Value = null;
    // row.Cells["comments"].Value = "1";
}
else 
    MessageBox.Show("Please select an item");

string strGetColumnValue;
if (dataGridViewTimesheet.Rows.Count != 0)
    rowsCount = dataGridViewTimesheet.Rows.Count;
else
    MessageBox.Show("No row in the datagridview");
while (dataGridViewTimesheet.Rows.Count > 0)
{
    try
    {
        if (dataGridViewTimesheet.CurrentRow != null)
            for (int counter = 0; counter < dataGridViewTimesheet.Columns.Count; counter++)
            {
                if (dataGridViewTimesheet.Columns[counter].Index == 3)
                {
                    strGetColumnValue = dataGridViewTimesheet.Rows[rowsCount].Cells[counter].Value.ToString();
                    dataGridViewTimesheet.Rows[rowsCount - 1].Cells[3].Value = strGetColumnValue;
                }
            }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

请在datagridview中有6列,动态添加行。我想要的是当datagridview中的行多于一行时,它应该将当前(创建的最后一行)行的第二列的值分配给上一行的第三列。我如何实现这一目标。

1 个答案:

答案 0 :(得分:0)

尝试这种事情

  int count =1;
  foreach (DataGridRow row in dataGridViewTimesheet.Rows)
  { 
     if (count % 2 == 0)
     {
       string secondColumn = dataGridViewTimesheet.Rows[count -1].Cells[1].ToString();
       dataGridViewTimesheet.Rows[count].Cells[2].Value = secondColumn;
     }
    count++;
  }