Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get original object from DataRow in GridView C#

I try to display a collection (IEnumerable) of objects (generated via Linq to Sql). Therefore I bind the Gridviews DataSource property to the generated output of my Linq to SQL method. In the SelectedIndexChanged event of the GridView I try to convert the selected rows DataItem back to my original object but end up with a null value instead.

Here is my code:

protected void Page_Load(object sender, EventArgs e)
{
    RlDataContext dc = new RlDataContext();
    this.dgvReports.DataSource = dc.GetReports(1);
    this.dgvReports.DataBind();
}

protected void dgvReports_SelectedIndexChanged(object sender, EventArgs e)
{
    if (this.dgvReports.SelectedIndex >= 0)
    {
        Report rpt = (Report)this.dgvReports.SelectedRow.DataItem;
    }
}

The return type of GetReports is ISingleResult<Report>

like image 212
Romano Zumbé Avatar asked Feb 03 '26 03:02

Romano Zumbé


1 Answers

Use a bindingsource between your datagridview and your list. When a selection is made is datagridview use the bindingsource's Current property to get you the right item from the list.

like image 155
user2320861 Avatar answered Feb 05 '26 17:02

user2320861