如何在一个标签C#windows窗体中获取多行单元格

时间:2017-07-27 20:27:03

标签: c# datagridview label

我需要在dataGridView中选择多行,对于所有选定的行,我需要将所有ProductsNames [cell 2]设置为一个标签。 这是我的代码

Bill bill = new Bill();
foreach (DataGridViewCell cell in dataGridView2.SelectedCells)
{         
    bill.label12.Text = this.dataGridView2.CurrentRow.Cells[2].Value.ToString() + Environment.NewLine +  this.dataGridView2.CurrentRow.Cells[2].Value.ToString();
    bill.label14.Text = this.dataGridView2.CurrentRow.Cells[8].Value.ToString();
    bill.label15.Text = this.dataGridView2.CurrentRow.Cells[6].Value.ToString();

    bill.StartPosition = FormStartPosition.CenterScreen;
    bill.Show();
}

1 个答案:

答案 0 :(得分:0)

目前还不清楚你的要求究竟是什么,但是根据什么,我猜你希望用户能够选择“多行”,然后,通过一些未知的机制,这些“选定的行”填充了几个标签。这和我在这里可以解释的差不多。

由于看起来你正在寻找行,并设置了完整行选择模式,我猜测循环SelectedRows可能更容易,而不是SelectedCells

对于所有“Selected”单元格/行/列方法,要记住的是集合从NEWEST到OLDEST顺序存储。换句话说,SelectedRows集合是一个堆栈,每次用户添加到选择时,新选择的单元格将转到SelectedRows集合的顶部,其他所有内容都会向下移动。这使您可以跟踪用户在必要时选择单元格的顺序。

鉴于此,从您的问题看来,您至少需要两行。由于multi-select为true,因此必须假设用户可能选择了两行以上,或者可能只选择了一行。这可以通过查看SelectedRows.Count的数量来检查。如果选择了两行以上,您不清楚这里会做什么。我假设可能使用前两个选定的行,或最后两个选定的行。

以下是演示SelectedRows集合的示例。 DataGridViews SelectionMode应设置为FullRowSelect。按钮用于遍历所有选定的行,并将一些值输出到文本框中。我希望这是有道理的。

private void Form1_Load(object sender, EventArgs e) {
  SetColumns();
  FillGrid();
}

private void SetColumns() {
  for (int i = 0; i < 9; i++) {
    dataGridView1.Columns.Add("Col" + i, "Col" + i);
  }
}

private void FillGrid() {
  int newRowIndex = 0;
  for (int row = 0; row < 10; row++) {
    newRowIndex = dataGridView1.Rows.Add();
    for (int col = 0; col < dataGridView1.Columns.Count; col++) {
      dataGridView1.Rows[newRowIndex].Cells[col].Value = "R" + row + "C" + col;
    }
  }
}

private void button1_Click(object sender, EventArgs e) {
  foreach (DataGridViewRow curRow in dataGridView1.SelectedRows) {
    textBox1.Text += "--- New row ---" + Environment.NewLine;
    textBox1.Text += "Label1: " + curRow.Cells["Col2"].Value.ToString() + Environment.NewLine;
    textBox1.Text += "Label2: " + curRow.Cells["Col8"].Value.ToString() + Environment.NewLine;
    textBox1.Text += "Label3: " + curRow.Cells["Col6"].Value.ToString() + Environment.NewLine;
  }
}