如何更改数据表中的选定行?

时间:2013-07-24 11:22:06

标签: c# datagridview datatable dataadapter

我有另一个问题。我已经绑定了datagridview,当我双击其中的行时,所有单元格值都“转换”为文本框。我想要做的是当我更改文本框值时,还必须在datagridview和datatable中进行更改。到目前为止,我只更改了第一行datagridview,而不是选中。这是我的代码:

private void buttonUredi_Click(object sender, EventArgs e)
    {
        int i = 0;
        foreach (DataGridViewRow row in dataGridView1.SelectedRows)
        {
            for (int j = 0; j < dataGridView1.ColumnCount; ++j)
            {
               competitorDataSet.Growns.Rows[i][j] = row.Cells[j].Value;
            }

                }
                competitorDataSet.Growns.Rows[i][0] = textStN.Text;
                competitorDataSet.Growns.Rows[i][1] = textN.Text;
                competitorDataSet.Growns.Rows[i][2] = textSN.Text;
                competitorDataSet.Growns.Rows[i][3] = textC.Text;
                competitorDataSet.Growns.Rows[i][4] = textYB.Text;
                this.grownsBindingSource.EndEdit();
                if (dataGridView1.BindingContext[competitorDataSet.Growns] != null)
                {
                    dataGridView1.BindingContext[competitorDataSet.Growns].EndCurrentEdit();
                }
                this.competitorDataSet.Growns.AcceptChanges();
}

2 个答案:

答案 0 :(得分:0)

您使用int i = 0作为DataTable.Rows中索引器的变量,但您永远不会更改它。

int i = 0;
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    for (int j = 0; j < dataGridView1.ColumnCount; ++j)
    {
       competitorDataSet.Growns.Rows[i][j] = row.Cells[j].Value;
    }
    i++;
}

然而,这将改变表中的任意行,即第一行dataGridView1.SelectedRows.Count行。这是期望的吗?

答案 1 :(得分:0)

所选行号存储在EventArgs e中。用它来定位选定的行。

EDIT 我明白你在dgv中双击行?如果是,你有这样的事情:

private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)

您可以像这样存储点击的行号:

int nClickedRow = e.RowIndex;