C# 如何从 Windows 窗体应用程序的 DataGrid 中的选定行获取值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9049937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:44:10  来源:igfitidea点击:

How to get values from selected row in DataGrid for Windows Form Application?

c#winforms

提问by athom

Title is pretty self-explanatory. I've got a DataGrid for a Windows Form Application, and I want to be able to store the values of a selected row. What is the easiest way to go about doing this?

标题是不言自明的。我有一个用于 Windows 窗体应用程序的 DataGrid,我希望能够存储选定行的值。这样做的最简单方法是什么?

I have found this chunk of code as an example in my search, but doesn't work when the DataGrid is sorted differently:

我在搜索中找到了这段代码作为示例,但是当 DataGrid 以不同方式排序时不起作用:

private void grdPatients_CurrentCellChanged(object sender, EventArgs e)
    {
        int row = grdPatients.CurrentRowIndex;

        grdPatients.Select(row);

        ArrayList arrayList = new ArrayList();

        for (int i = 0; i < 3; i++)
        {

            arrayList.Insert(i, (patientsDS.Tables["PatientList"].Rows[row].ItemArray.GetValue(i)));

        }

        textBox1.Text = "" + arrayList[0];

        textBox2.Text = "" + arrayList[1];

        textBox3.Text = "" + arrayList[2];
    }

采纳答案by dknaack

Description

描述

Assuming i understand your question.

假设我理解你的问题。

You can get the selected row using the DataGridView.SelectedRowsCollection. If your DataGridView allows only one selected, have a look at my sample.

您可以使用DataGridView.SelectedRows集合获取选定的行。如果您的 DataGridView 只允许选择一个,请查看我的示例。

DataGridView.SelectedRowsGets the collection of rows selected by the user.

DataGridView.SelectedRows获取用户选择的行的集合。

Sample

样本

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

更多信息

回答by james Heller

You could just use

你可以用

DataGridView1.CurrentRow.Cells["ColumnName"].Value