The*_*ing 4 c# asp.net gridview business-objects
究竟是什么e.Row.DataItem返回.. MSDN说.. 返回一个Object,表示GridViewRow对象绑定到的底层数据对象.
这是我的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>
Run Code Online (Sandbox Code Playgroud)
然后我将它绑定到我的业务对象列表<Patient> ..在DataBound行事件中,我试试这个...
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 = "";
}
}
Run Code Online (Sandbox Code Playgroud)
我得到异常P1为空 ......为什么这样......我错过了什么..
注意:可能有其他方法可以实现这一点,但我特别关注为什么我的p1为null ...并且有任何方法可以在绑定后从GridView 获取Patient对象.
也为页眉和页脚调用RowDataBound,你需要DataRow在调用之前确保你当前处于实际状态e.Row.DataItem:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType != DataControlRowType.DataRow)
return;
Patient p1 = (Patient)e.Row.DataItem;
Run Code Online (Sandbox Code Playgroud)