C# 将 dataGridView 中的选定行作为对象检索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19682526/
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-10 15:36:26  来源:igfitidea点击:

Retrieving selected row in dataGridView as an object

c#.netwinformsdatagridview

提问by Dimo

I have a class like this:

我有一个这样的课程:

public partial class AdressBokPerson
    {
        public long Session { get; set; }
        public string F?rnamn { get; set; }
        public string Efternamn { get; set; }
        public string Mail { get; set; }
    }

Added to a list:

添加到列表中:

private readonly List<AdressBokPerson> _avp = new List<AdressBokPerson>();

With binding to a dataGridView like this:

绑定到像这样的 dataGridView:

dataGridView1.DataSource = _avp;

So far so good.

到现在为止还挺好。

Here is my question:

这是我的问题:

How do I find out 'which' object is selected when a row in the dataGridView is selected. I need to retrieve the selectedobject AdressBokPersonsomehow.

选择 dataGridView 中的一行时,如何找出选择了“哪个”对象。我需要以某种方式检索选定的对象AdressBokPerson

采纳答案by Alex

You get the object by casting the DataBoundItemto the specified type:

您可以通过将DataBoundItem转换为指定类型来获取对象:

AdressBokPerson currentObject = (AdressBokPerson)dataGridView1.CurrentRow.DataBoundItem;