Get a business object from Grid View mode

What exactly returns e.Row.DataItem .. MSDN says. returns an object representing the underlying data object to which the GridViewRow is bound.

Here is my DataGrid ...

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" OnRowDataBound="GridView1_RowDataBound"> <Columns> <asp:BoundField DataField="PracticeCode" HeaderText="PracticeCode" SortExpression="PracticeCode" /> <asp:BoundField DataField="AccountNo" HeaderText="AccountNo" SortExpression="AccountNo" /> <asp:BoundField DataField="PatientName" HeaderText="PatientName" SortExpression="PatientName" /> <asp:TemplateField HeaderText="Status"> <ItemTemplate> <asp:Label ID="LblStatus" runat="server"></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 

And I associate it with my business object List <Patient> . In the DataBound event line, I try this ...

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { Patient p1 = (Patient)e.Row.DataItem; Label lbl = e.Row.FindControl("LblStatus") as Label; if (p1 == null) { throw new Exception("P1 is null"); } if (p1.OpenItems.Count > 0) { lbl.Text = "Has open Items"; } else { lbl.Text = ""; } } 

I get the exception P1 is null ... Why so ... What am I missing ..

Note There may be other ways to do this, but I look especially at why my p1 is null ... and is there a way to get the Patient Object back from the GridView after the binding.

+4
source share
1 answer

RowDataBound is also called for the header and footer, you need to make sure your current actual DataRow before calling e.Row.DataItem :

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if(e.Row.RowType != DataControlRowType.DataRow) return; Patient p1 = (Patient)e.Row.DataItem; 
+7
source

Source: https://habr.com/ru/post/1313485/


All Articles