问题描述
||
我有
<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
,并由于e.Row.DataItem
为空而引发错误Object reference not set to an instance of an object
。
编辑:背后的代码
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);
}
解决方法
您可以在第一次获取utViewModelList时将其存储在Session中吗?如果是这样,则可以从所选行的DataKey值保存的位置获取UserTestorViewModel实例。
,当您单击gridview中的任何按钮时,页面将回发并在进入
RowCommand
事件之前调用页面加载事件。在页面加载事件中,您将再次绑定gridview,这就是调用ѭ9的原因。
您必须将网格视图绑定到ѭ10下
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();
}
}
编辑:现在,您发布代码后,我收到了您的问题。
问题出在ѭ12中,您可以从这里删除事件处理程序并尝试以下操作:
protected void Page_Init(object sender,EventArgs e)
{
GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
}
在这里添加
<asp:GridView onrowcreated=\"GridView1_RowCreated\">