我想在RowCreate重新加载之前执行RowCommand或类似的东西

时间:2011-05-26 08:42:57

标签: asp.net webforms

我有

<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);
}

2 个答案:

答案 0 :(得分:0)

当您单击gridview中的任何按钮时,您的页面将被回发并且页面加载事件在进入RowCommand事件之前被调用。在页面加载事件中,您再次绑定了gridview,这就是调用RowCreated Event的原因。

您必须在if (!IsPostBack)

下绑定gridview
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实例。