带有objectDataSource的GridView在RowEditing和RowUpdating事件中返回NULL单元格值

时间:2015-04-14 04:18:23

标签: c# asp.net gridview objectdatasource

我正在使用带有GridView的ObjectDataSource,如下所示。它包含在UpdatePanel中。当用户按下此UpdatePanel外部的按钮时,它应该通过向ObjectSource Select方法提供一些种子值来填充gridview。该部分工作正常 - 当调用Select方法时,gridView成功初始化。当用户继续按下“编辑”按钮时,gridView也会成功转换为具有可编辑TextBox控件的编辑模式。该部分也可以正常工作,但我试图在此转换过程中检查GridViewRow.Cell [i] .Text和GridViewRow.Cell [i] .Controls [j]值,并且对于gridview中的每个单元格它始终为NULL

最后,当在底层ObjectSource上调用Update方法时,传递给Update方法的所有参数实际上都是NULL。简而言之,即使用户看到单元格的内容,代码也永远无法捕获此内容 - 它只接收NULL。注意,我在!PostBack和RowEditing和RowUpdating事件期间在objectsource上实现了几个DataBinds。

为什么我无法捕获这些单元格中的字符串内容?

这是标记:

<asp:UpdatePanel ID="PgimUpdatePanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:HiddenField ID="hdnShowPgim" runat="server"/>
         <div id="jsPgimPanel">
             <asp:ObjectDataSource ID="pgimObjectSource" Runat="server" TypeName="CarePlanModifier.Models.PgimMapping" SelectMethod="GetPgims" EnablePaging="True" SelectCountMethod="TotalNumberOfPgims" UpdateMethod="UpdatePgims" InsertMethod="UpdatePgims" DeleteMethod="SoftDeletePgims" OnUpdating="pgimObjectSource_Updating" OnSelecting="pgimObjectSource_Selecting" >
                    <SelectParameters>
                        <asp:querystringparameter name="MatchCode" querystringfield="MatchCode" defaultvalue="0" />
                        <asp:querystringparameter name="CprId" querystringfield="CprId" defaultvalue="0" />
                        <asp:querystringparameter name="SessionUser" querystringfield="SessionUser" defaultvalue="0" />
                    </SelectParameters>
                    <UpdateParameters>
                        <asp:Parameter Type="Int32" Name="Id"></asp:Parameter>
                        <asp:Parameter Type="String" Name="Icd1Code"></asp:Parameter>
                        <asp:Parameter Type="String" Name="MatchCode"></asp:Parameter>
                        <asp:Parameter Type="String" Name="Problems"></asp:Parameter>
                        <asp:Parameter Type="String" Name="Goals"></asp:Parameter>
                        <asp:Parameter Type="String" Name="Interventions"></asp:Parameter>
                        <asp:Parameter Type="Int32" Name="CprId"></asp:Parameter>
                        <asp:Parameter Type="String" Name="EditUser"></asp:Parameter>
                    </UpdateParameters>
                </asp:ObjectDataSource>
             <asp:GridView ID="gridPgim" Runat="server" DataSourceID="pgimObjectSource" AutoGenerateColumns="False" AllowPaging="True" BorderWidth="1px" BackColor="White" CellPadding="3" BorderStyle="Solid" BorderColor="#999999" ForeColor="Black" GridLines="Vertical" pagesize="10" OnRowEditing="gridPgim_RowEditing" OnRowCancelingEdit="gridPgim_RowCancelingEdit" OnRowUpdating="gridPgim_RowUpdating" OnRowCommand="gridPgim_RowCommand" DataKeyNames="Id, MatchCode,CprId, EditUser">
                <FooterStyle BackColor="#CCCCCC" />
                <HeaderStyle  Font-Bold="True" BackColor="Black" ForeColor="White" />
                <AlternatingRowStyle BackColor="#CCCCCC" />
                <Columns>
                    <asp:CommandField ShowEditButton="True" ShowDeleteButton="False" ></asp:CommandField>
                    <asp:BoundField Visible="false" ReadOnly="True" HeaderText="Id" InsertVisible="False" DataField="Id" SortExpression="Id"></asp:BoundField>
                    <asp:BoundField Visible="false" ReadOnly="True" HeaderText="Icd1Code" DataField="Icd1Code" SortExpression="Icd1Code"></asp:BoundField>
                    <asp:BoundField Visible="false" ReadOnly="True" HeaderText="MatchCode" DataField="MatchCode" SortExpression="MatchCode"></asp:BoundField>
                    <asp:BoundField Visible="false" ReadOnly="True" HeaderText="CprId" InsertVisible="False" DataField="CprId" SortExpression="CprId"></asp:BoundField>
                    <asp:BoundField Visible="false" ReadOnly="True" HeaderText="EditUser" InsertVisible="False" DataField="EditUser" SortExpression="EditUser"></asp:BoundField>
                    <asp:TemplateField HeaderText="Problems" SortExpression="Problems">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtProblems" TextMode="MultiLine" runat="server" TextWrapping="Wrap" Rows="4"
                                   AcceptsReturn="False" VerticalScrollBarVisibility="Visible"
                                    Text='<%# Bind("Problems") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblEditProblems" runat="server" Text='<%# Bind("Problems") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Goals" SortExpression="Goals">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtGoals" runat="server" TextMode="MultiLine" TextWrapping="Wrap" Rows="4" AcceptsReturn="False" VerticalScrollBarVisibility="Visible" Text='<%# Bind("Goals") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblEditGoals" runat="server" Text='<%# Bind("Goals") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Interventions" SortExpression="Interventions">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtInterventions" runat="server" TextMode="MultiLine" TextWrapping="Wrap" Rows="4" AcceptsReturn="False" VerticalScrollBarVisibility="Visible" Text='<%# Bind("Interventions") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblEditInterventions" runat="server" Text='<%# Bind("Interventions") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#F1F1F1" />
                <SortedAscendingHeaderStyle BackColor="#808080" />
                <SortedDescendingCellStyle BackColor="#CAC9C9" />
                <SortedDescendingHeaderStyle BackColor="#383838" />
            </asp:GridView>
         </div>
        <script type="text/javascript" src="Scripts/jquery.jspanel.min.js"></script>
        <link rel="stylesheet" type="text/css" href="Scripts/jquery.jspanel.min.css"/>
        <link rel="stylesheet" type="text/css" href="Scripts/jsglyph.css"/>
         <script type="text/javascript"> 
             var pgim;
             function clearPanel() {
                 //alert('0');
                 pgim.close();
                 //alert('1');
             };
             function displayPanel() {
                 //alert('0');
                 if (pgim != null) {
                     pgim.close();
                 }
                 //alert('1');
                pgim = $.jsPanel({
                    content: $('div#jsPgimPanel'),
                    title: "PGIM",
                    position: "center right",
                    theme: "light",
                    overflow: 'visible',
                    size: { width: 800, height: 450 },
                });
             };
             function rePanel() {
                 alert('3');
                 pgim.reloadContent();
                 alert('4');
             };
         </script>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="gridDiagnoses" EventName="RowCommand"/>
    </Triggers>
</asp:UpdatePanel>

以下是代码隐藏事件方法:

protected void btnFindPgim_Load(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)sender;
    //PgimUpdatePanel.Triggers.Add(new  PostBackTrigger{  ControlID=btn.UniqueID });
    PgimUpdatePanel.Triggers.Add(new AsyncPostBackTrigger { ControlID = btn.UniqueID, EventName = "Click" });
}

protected void gridPgim_RowEditing(object sender, GridViewEditEventArgs e)
{
    //Set the edit index.
    gridPgim.EditIndex = e.NewEditIndex;

    string diagCode = hdnSelectedDiagCode.Value;
    int cprId = Convert.ToInt32(hdnCprId.Value);

    CarePlanReview xCpr = (CarePlanReview)Request.RequestContext.HttpContext.Session["xCpr"];
    displayFiles(Convert.ToInt32(hdnCprId.Value), xCpr.Client);

    //GridView gv = (GridView)sender;
    //gv.EditIndex = e.NewEditIndex;
    //gv.DataBind();

    BindPgimGrid(diagCode, cprId);

    //ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "clearPanel();", true);
    ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "displayPanel();", true);
    //ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "rePanel();", true);
}

protected void gridPgim_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    CarePlanReview xCpr = (CarePlanReview)Request.RequestContext.HttpContext.Session["xCpr"];
    displayFiles(Convert.ToInt32(hdnCprId.Value), xCpr.Client);

    //Reset the edit index.
    gridPgim.EditIndex = -1;
    ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "clearPanel();", true);
}

protected void gridPgim_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    ISession session = HiHibernateUtil.GetCurrentSession();
    CarePlanReview xCpr = (CarePlanReview)Request.RequestContext.HttpContext.Session["xCpr"];
    try
    {
        PgimMapping pm = new PgimMapping();
        if (e.NewValues["Problems"] != null)
        {
            pm.Problems = (string)e.NewValues["Problems"];
        }

        GridView gv = (GridView)sender;
        for (int i = 0; i < gv.Columns.Count; i++)
        {
            DataControlFieldCell cell = gv.Rows[e.RowIndex].Cells[i] as DataControlFieldCell;
            gv.Columns[i].ExtractValuesFromCell(e.NewValues, cell, DataControlRowState.Edit, true);
        }

        foreach (DictionaryEntry de in e.NewValues)
        {
            string dkey = (string)de.Key;
            if ( dkey.Equals("Icd1Code", StringComparison.CurrentCultureIgnoreCase) )
            {
                pm.Icd1Code = (string)de.Value;
            }
            if (dkey.Equals("CprId", StringComparison.CurrentCultureIgnoreCase))
            {
                pm.CprId = Convert.ToInt32((string)de.Value);
            }
            if (dkey.Equals("MatchCode", StringComparison.CurrentCultureIgnoreCase))
            {
                pm.MatchCode = (string)de.Value;
            }
            if (dkey.Equals("MatchCode", StringComparison.CurrentCultureIgnoreCase))
            {
                pm.MatchCode = (string)de.Value;
            }
            if (dkey.Equals("Problems", StringComparison.CurrentCultureIgnoreCase))
            {
                pm.Problems = (string)de.Value;
            }
            if (dkey.Equals("Goals", StringComparison.CurrentCultureIgnoreCase))
            {
                pm.Goals = (string)de.Value;
            }
            if (dkey.Equals("Interventions", StringComparison.CurrentCultureIgnoreCase))
            {
                pm.Interventions = (string)de.Value;
            }
        }

        if (pm.CprId < 1)
        {
            throw new Exception("ERROR the 'cprId' value is invalid for " + pm.CprId);
        }
        if (String.IsNullOrEmpty(pm.Problems) || pm.Problems.Length < 3)
        {
            throw new Exception("ERROR the 'problem' value is empty for " + pm.MatchCode);
        }
        if (String.IsNullOrEmpty(pm.Goals) || pm.Goals.Length < 3)
        {
            throw new Exception("ERROR the 'goal' value is empty for " + pm.MatchCode);
        }

        pm.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
        pm.Active = 0;
        pm.AddedDate = DateTime.Now;
        pm.EditUser = xCpr.SessionUser.Username;

        // now add the PGIM to this Care Plan
        CareNeeds cneeds = new CareNeeds();
        cneeds.Active = 0;
        cneeds.CprId = pm.CprId;
        cneeds.EditUser = pm.EditUser;
        cneeds.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
        cneeds.Goal = pm.Goals;
        cneeds.Problem = pm.Problems;
        cneeds.Interventions = pm.Interventions;
        cneeds.AddedDate = DateTime.Now;

        using (ITransaction txn = session.BeginTransaction())
        {

            session.Save(pm);
            session.Save(cneeds);

            txn.Commit();
        }

        //Reset the edit index.
        gridPgim.EditIndex = -1;
    }
    catch (System.Exception ee)
    {
        log.Error("gridPgim_RowUpdating()  " + ee.Message);
        log.Error("gridPgim_RowUpdating()  " + ee.StackTrace);
        LabelErrorMessages2.CssClass = "errorlabel";
        LabelErrorMessages2.Text = LabelErrorMessages.Text + " " + ee.Message;
    }
    finally
    {
        session.Flush();
        session.Close();
    }
}

protected void gridPgim_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Update")
    {
        BindPgimGrid(hdnSelectedDiagCode.Value, Convert.ToInt32(hdnCprId.Value));
        GridViewRow row = gridPgim.Rows[gridPgim.EditIndex];

    } else if ( e.CommandArgument == "Edit" )
    {

    }
    ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "displayPanel();", true);
}

最后,这里是DAL对象(也映射到nHibernate映射),但删除了一些方法以缩短此帖子。

public class PgimMapping
{
    private static readonly log4net.ILog log = LogManager.GetLogger(typeof(PgimMapping));

    public PgimMapping(string diagCode, int cprId, string suser)
    {
        this.matchCode = diagCode;
        this.cprId = cprId;
        this.sessionUser = suser;
    }

    private string sessionUser = null;

    private string matchCode = null;
    public string MatchCode
    {
        get { return matchCode; }
        set { matchCode = value; }
    }

    private int id = 0;
    public virtual int Id
    {
        get { return id; }
        set { id = value; }
    }

    private string icd1Code = null;
    public virtual string Icd1Code
    {
        get { return icd1Code; }
        set { icd1Code = value; }
    }

    private string icd9Code = null;
    public virtual string Icd9Code
    {
        get { return icd9Code; }
        set { icd9Code = value; }
    }

    private string description = null;
    public virtual string Description
    {
        get { return description; }
        set { description = value; }
    }

    private string problems = null;
    public virtual string Problems
    {
        get { return problems; }
        set { problems = value; }
    }

    private string goals = null;
    public virtual string Goals
    {
        get { return goals; }
        set { goals = value; }
    }

    private string interventions = null;
    public virtual string Interventions
    {
        get { return interventions; }
        set { interventions = value; }
    }

    private string measures = null;
    public virtual string Measures
    {
        get { return measures; }
        set { measures = value; }
    }

    private string discussWDr = null;
    public virtual string DiscussWDr
    {
        get { return discussWDr; }
        set { discussWDr = value; }
    }

    private string memberProblems = null;
    public virtual string MemberProblems
    {
        get { return memberProblems; }
        set { memberProblems = value; }
    }

    private string memberGoals = null;
    public virtual string MemberGoals
    {
        get { return memberGoals; }
        set { memberGoals = value; }
    }

    private DateTime? addedDate = null;
    public virtual DateTime? AddedDate
    {
        get { return addedDate; }
        set { addedDate = value; }
    }

    private string editUser = null;
    public virtual string EditUser
    {
        get { return editUser; }
        set { editUser = value; }
    }

    private DateTime? modifyDate = null;
    public virtual DateTime? ModifyDate
    {
        get { return modifyDate; }
        set { modifyDate = value; }
    }

    private int gmtOffset = 0;
    public virtual int GmtOffset
    {
        get { return gmtOffset; }
        set { gmtOffset = value; }
    }

    private int active = 0;
    public virtual int Active
    {
        get { return active; }
        set { active = value; }
    }

    private int cprId = 0;
    public int CprId
    {
        get { return cprId; }
        set { cprId = value; }
    }

    public void UpdatePgims(int Id, string Icd1Code, string MatchCode, int CprId, string Problems, string Goals, string Interventions, string EditUser)
    {

        ISession session = HiHibernateUtil.GetCurrentSession();
        try
        {
            if (CprId < 1)
            {
                throw new Exception("ERROR the 'cprId' value is invalid for " + CprId);
            }
            if (String.IsNullOrEmpty(Problems) || Problems.Length < 3)
            {
                throw new Exception("ERROR the 'problem' value is empty for " + MatchCode);
            }
            if (String.IsNullOrEmpty(Goals) || Goals.Length < 3)
            {
                throw new Exception("ERROR the 'goal' value is empty for " + MatchCode);
            }
            PgimMapping pm = new PgimMapping(Icd1Code, CprId, EditUser);
            pm.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
            pm.Goals = Goals;
            pm.Problems = Problems;
            pm.Interventions = Interventions;
            pm.Icd1Code = Icd1Code;
            pm.Active = 0;
            pm.AddedDate = DateTime.Now;
            pm.CprId = CprId;
            pm.MatchCode = MatchCode;
            pm.sessionUser = EditUser;

            // now add the PGIM to this Care Plan
            CareNeeds cneeds = new CareNeeds();
            cneeds.Active = 0;
            cneeds.CprId = CprId;
            cneeds.EditUser = EditUser;
            cneeds.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
            cneeds.Goal = Goals;
            cneeds.Problem = Problems;
            cneeds.Interventions = Interventions;
            cneeds.AddedDate = DateTime.Now;

            using (ITransaction txn = session.BeginTransaction())
            {
                session.Save(pm);
                session.Save(cneeds);
                txn.Commit();
            }
        }
        catch (Exception ee)
        {
            log.Error("UpdatePgims()  " + ee.Message);
            log.Error("UpdatePgims()  " + ee.StackTrace);
        }
        finally
        {
            session.Flush();
            session.Close();
        }
    }
}

0 个答案:

没有答案