我有
<asp:GridView>
<asp:TemplateField HeaderText="PsyHealth">
<ItemTemplate>
<asp:PlaceHolder runat="server" ID="PsyHealth" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="-">
<ItemTemplate>
<asp:LinkButton ID="Gen" CommandName="Gen" runat="server" Text="gen" />
</ItemTemplate>
</asp:TemplateField>
和
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var dataItem = e.Row.DataItem as ViewModels.UserTestorViewModel;
var psyHealth = e.Row.FindControl("PsyHealth") as PlaceHolder;
if (psyHealth != null)
{
psyHealth.Controls.Add(dataItem.PsyHeath);
}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//bla bla bla
}
但是当我点击页面上的Gen
LinkButton
时。 GridView1_RowCreated
首先被触发并抛出错误Object reference not set to an instance of an object
,因为e.Row.DataItem
为空。
编辑:背后的代码
protected void Page_Load(object sender, EventArgs e)
{
List<ViewModels.UserTestorViewModel> utViewModelList = new List<ViewModels.UserTestorViewModel> { };
utViewModelList = utRepo.GetUserTestorViewModelListByHrId();
this.GridView1.DataSource = utViewModelList;
this.GridView1.DataBind();
if (!IsPostBack)
{
}
}
protected void Page_Init(object sender, EventArgs e)
{
GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
}
答案 0 :(得分:0)
当您单击gridview中的任何按钮时,您的页面将被回发并且页面加载事件在进入RowCommand
事件之前被调用。在页面加载事件中,您再次绑定了gridview,这就是调用RowCreated Event
的原因。
您必须在if (!IsPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ViewModels.UserTestorViewModel> utViewModelList = new List<ViewModels.UserTestorViewModel> { };
utViewModelList = utRepo.GetUserTestorViewModelListByHrId();
this.GridView1.DataSource = utViewModelList;
this.GridView1.DataBind();
}
}
修改:现在,在发布代码后,我收到了您的问题。
问题出在Page_Init
,您可以从此处删除事件处理程序并尝试以下操作:
protected void Page_Init(object sender, EventArgs e)
{
GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
}
在这里添加
<asp:GridView onrowcreated="GridView1_RowCreated">
答案 1 :(得分:0)
你可以在第一次获得会话时将utViewModelList存储在会话中吗?如果是这样,那么您可以从所选行的DataKey值中保存UserTestorViewModel实例。