如何交换选定的datagridview行

时间:2014-07-01 16:17:58

标签: c# winforms

我有一个名为dgvNoveStavke的datagridview,每次按下表格中的按钮时我都会添加一行:

private void btnDodajStavke_Click(object sender, EventArgs e)
{
  DataGridViewRow red = (DataGridViewRow)dgvNoveStavke.Rows[0].Clone();
  red.Cells[0].Value = txtIdStavke.Text;
  red.Cells[1].Value = txtIzabranaStavka.Text;
  red.Cells[2].Value = txtKolicina.Text;
  red.Cells[3].Value = txtPopust.Text;
  dgvNoveStavke.Rows.Add(red);
}

当我在数据网格视图中单击一行时,我在文本框中填入行中的数据,然后启用按钮来编辑和删除行,如下所示:

private void dgvNoveStavke_SelectionChanged(object sender, EventArgs e)
{
  txtIdStavke.Text = dgvNoveStavke.SelectedCells[0].Value.ToString();
  txtIzabranaStavka.Text = dgvNoveStavke.SelectedCells[1].Value.ToString();
  txtKolicina.Text = dgvNoveStavke.SelectedCells[2].Value.ToString();
  txtPopust.Text = dgvNoveStavke.SelectedCells[3].Value.ToString();
  btnObrisiStavku.Enabled = true;
  btnUrediStavku.Enabled = true;
}

当我按下编辑按钮时,我不知道如何将旧行与我创建的新行交换。

private void btnUrediStavku_Click(object sender, EventArgs e)
{         
  DataGridViewRow red = (DataGridViewRow)dgvNoveStavke.Rows[0].Clone();
  red.Cells[0].Value = txtIdStavke.Text;
  red.Cells[1].Value = txtIzabranaStavka.Text;
  red.Cells[2].Value = txtKolicina.Text;
  red.Cells[3].Value = txtPopust.Text;
  // how do I replace the selected row with the new one I created here
}

我尝试使用

dgvNoveStavke.SelectedRows[0] = red;

但这不起作用,我不知道还有什么可以尝试,有人可以告诉我如何交换或替换我在datagridview中选择的行。

编辑: 弄清楚了! 我刚刚选择了每个单元格,为它们设置了新值。 这是代码:

private void btnUrediStavku_Click(object sender, EventArgs e)
        {
            if (dgvNoveStavke.SelectedRows.Count > 0)
            {
                dgvNoveStavke.SelectedCells[0].Value = txtIdStavke.Text;
                dgvNoveStavke.SelectedCells[1].Value = txtIzabranaStavka.Text;
                dgvNoveStavke.SelectedCells[2].Value = txtKolicina.Text;
                dgvNoveStavke.SelectedCells[3].Value = txtPopust.Text;
            }      
        }

1 个答案:

答案 0 :(得分:0)

选择我为其设置新值的每个单元格。这是代码:

private void btnUrediStavku_Click(object sender, EventArgs e)
{
   if (dgvNoveStavke.SelectedRows.Count > 0)
   {
       dgvNoveStavke.SelectedCells[0].Value = txtIdStavke.Text;
       dgvNoveStavke.SelectedCells[1].Value = txtIzabranaStavka.Text;
       dgvNoveStavke.SelectedCells[2].Value = txtKolicina.Text;
       dgvNoveStavke.SelectedCells[3].Value = txtPopust.Text;
   }      
}