开发者

I want RowCommand executed before RowCreate reloading OR something like this

I have

<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>

and

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var dataItem = e.Row.DataItem as ViewMode开发者_运维问答ls.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
}

but when I clicked the Gen LinkButton on the page. The GridView1_RowCreated was triggered first and threw the error Object reference not set to an instance of an object because the e.Row.DataItem was null.

Edit: The Code Behind

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


Can you store the utViewModelList in Session first time you get it? If so then you can get the UserTestorViewModel instance from saved by the selected row's DataKey value.


When you click any button in the gridview , your page is postbacked and the page load event is called before it goes into the RowCommand event. In the page load event you are binding your gridview again and that's why your RowCreated Event is called.

You have to bind your gridview under 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();
   }
}

Edit: Now I got your issue after you posted code..

The problem is here in Page_Init, can you remove the event handler from here and try the following:

protected void Page_Init(object sender, EventArgs e)
{
    GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
}

add here

<asp:GridView  onrowcreated="GridView1_RowCreated">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜