我希望在RowCreate重新加载之前执行RowCommand或类似的操作

问题描述

|| 我有
<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\">
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...