简体   繁体   English

从datagrid选择行时获取特定的单元格

[英]Get a specific cell when selecting a row from datagrid

Im using a SQL database to store data. 我正在使用SQL数据库来存储数据。 I have a datagrid where i show the data from the database. 我有一个datagrid,用于显示数据库中的数据。 The problem is, when a user select a row in the datagrid, and click on my "Delete" button, i want to get the value for that cell under my column "ContactID" for that row. 问题是,当用户在数据网格中选择一行,然后单击我的“删除”按钮时,我想获取该行在我的列“ ContactID”下的该单元格的值。

I hope someone can help. 我希望有人能帮帮忙。

private void dgvProducts_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dgvProducts.SelectedCells.Count > 0) // Checking to see if any cell is selected
    {
        int mSelectedRowIndex = dgvProducts.SelectedCells[0].RowIndex;

        DataGridViewRow mSelectedRow = dgvProducts.Rows[mSelectedRowIndex];

        string mProductName = Convert.ToString(mSelectedRow.Cells[1].Value); //put your columb index where the 1 is 

        dgvProducts.CurrentCell.Value = null; // removes value from current cell

        SomeOtherMethod(mProductName); // Passing the name to where ever you need it

        UpdateDataBaseMethod(dgvProducts); // You can do that bit
    }
}

Then to put that value somewhere else you could do.. 然后将其值放在其他位置即可。

 private void SomeOtherMethod(string pProductName)
 {
    dgvProducts.Rows[dgvProducts.CurrentRow.Index].Cells["ContactID"].Value = pProductName; // where do you want it to go? Change the Column index to change the Column on the same row
 }

hope this helped, although you may want to move some of it about if you want to attach it to your delete button. 希望这对您有所帮助,尽管如果您想将其附加到删除按钮上,可能需要对其进行一些移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM