首先定位,然后更改datagridview中选定行中单元格的值?

时间:2012-03-12 13:41:04

标签: c# visual-studio-2010 datagridview cell

我试图找出如何更改datagridview的选定行中特定单元格的值。我可以更改值,但不能在突出显示的行中更改,只能更改第一行。行的高亮显示在“查找”按钮代码中定义。

例如:我输入一个文本,它在每一行搜索特定列中的该文本,然后滚动并突出显示/选择整行。 (这很好)

然后,我希望能够通过选择下拉列表(组合框)中已存在的列名来获取突出显示的行的特定单元格的值。然后它获取该单元格的值,并从中扣除一个在NumericalUpDownCounter(nudQTY)中出现的值。

到目前为止,我可以为列名称(cbSupplList)选择的不同单元格执行此操作,但它仅针对第一行而不是“查找”按钮代码定义的突出显示行。

以下是我到目前为止的尝试:

 private void btnFind_Click(object sender, EventArgs e)
    {
        /* Code to search the alphanumneric Part Number (in Column1 header called "PART NUMBER") 
           and highlihgt the row*/
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            // Removes the row selection
            row.Selected = false;

            var cellValue = row.Cells["PART NUMBER"].Value;
            if (cellValue != null && cellValue.ToString() == tbPartNum.Text.ToUpper())
                {
                    // Scrolls the found row up and highlights the entire row
                    row.Selected = true;
                    dataGridView1.FirstDisplayedScrollingRowIndex = row.Index;
                }
        }
    }

    private void btnSold_Click(object sender, EventArgs e)
    {

        int cellVal;
        int newCellVal;

        cellVal = Convert.ToInt32(dataGridView1.CurrentRow.Cells[cbSuppList.Text.ToString()].Value);
        newCellVal = Convert.ToInt32(cellVal - nudQty.Value);
        dataGridView1.CurrentRow.Cells[cbSuppList.Text.ToString()].Value = newCellVal;

    }

似乎它可能与“查找”代码中的SELECTED ROW和“已售出”代码中的CURRENT ROW有关。制作SELECTED.ROW = CURRENT.ROW会解决它....任何想法?

1 个答案:

答案 0 :(得分:1)

您只取消选择行但没有单元格。

dataGridView1.CurrentRow - “获取包含当前单元格的行”

当前的细胞仍然是第一排的第一个细胞。

为了清除所有选定的行/单元格,请使用

dataGridView1.ClearSelection()

而不是

row.Selected = true;

使用

row.Cells["PART NUMBER"].Selected = true;

目前您只选择行但不选择单元格。 我希望这有帮助...

否则,您可能希望在 btnSold_Click()中找到与 btnFind_Click()

相同的单元格

修改

完整的解决方案

private void btnSold_Click(object sender,EventArgs e)     {

    int cellVal;
    int newCellVal;

    cellVal = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[cbSuppList.Text.ToString()].Value);
    newCellVal = Convert.ToInt32(cellVal - nudQty.Value);
    dataGridView1.SelectedRows[0].Cells[cbSuppList.Text.ToString()].Value = newCellVal;

}

我刚刚将 CurrentRow 替换为 SelectedRows [0] ,并且运行正常。