【问题标题】:GridView with objectDataSource is returning NULL cell values in RowEditing and RowUpdating events带有 objectDataSource 的 GridView 在 RowEditing 和 RowUpdating 事件中返回 NULL 单元格值
【发布时间】:2015-04-14 04:18:22
【问题描述】:

我正在使用带有 GridView 的 ObjectDataSource,如下所示。它包含在 UpdatePanel 中。当用户按下此 UpdatePanel 外部的按钮时,它应该通过向 ObjectSource Select 方法提供一些种子值来填充网格视图。该部分工作正常 - 调用 Select 方法时,gridView 成功初始化。当用户继续按下 Edit 按钮时,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();
        }
    }
}

【问题讨论】:

    标签: c# asp.net gridview objectdatasource


    【解决方案1】:

    使用以下代码,我能够实现我所需要的(尽管并不完全符合我的希望并且有很多妥协)。

    protected void gridPgim_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            ISession session = HiHibernateUtil.GetCurrentSession();
            CarePlanReview xCpr = (CarePlanReview)Request.RequestContext.HttpContext.Session["xCpr"];
            if (e.CommandName == "Edit")
            {
                GridViewRow row = gridPgim.Rows[Convert.ToInt32(e.CommandArgument)];
                TableCellCollection tbc = row.Cells;
                Object[] objArray = new Object[row.Cells.Count];
                tbc.CopyTo(objArray, 0);
                DataControlFieldCell problemsCf = (DataControlFieldCell)objArray[Convert.ToInt32(Utility.getAppSetting("pgimProblemIndex"))];
                //String txtProb = ((Label)problemsCf.Controls[1]).Text;
                String txtProb = problemsCf.Text;
                DataControlFieldCell goalCf = (DataControlFieldCell)objArray[Convert.ToInt32(Utility.getAppSetting("pgimGoalIndex"))];
                //String txtGoal = ((Label)goalCf.Controls[1]).Text;
                String txtGoal = goalCf.Text;
                DataControlFieldCell interventionCf = (DataControlFieldCell)objArray[Convert.ToInt32(Utility.getAppSetting("pgimInterventionIndex"))];
                //String txtInt = ((Label)interventionCf.Controls[1]).Text;
                String txtInt = interventionCf.Text;
                DataControlFieldCell diagCode = (DataControlFieldCell)objArray[Convert.ToInt32(Utility.getAppSetting("pgimDiagIndex"))];
                String txtdiag = diagCode.Text;
    
                int cprId = Convert.ToInt32(hdnCprId.Value);
    
                // now add the PGIM to this Care Plan
                CareNeeds cneeds = new CareNeeds();
                cneeds.Active = 0;
                cneeds.CprId = cprId;
                cneeds.EditUser = xCpr.SessionUser.Username;
                cneeds.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
                cneeds.Goal = txtGoal;
                cneeds.Problem = txtProb;
                cneeds.Interventions = txtInt;
                cneeds.Icd1Code = txtdiag;
                cneeds.AddedDate = DateTime.Now;
    
                using (ITransaction txn = session.BeginTransaction())
                {
                    session.Save(cneeds);
    
                    txn.Commit();
                }
    
                careNeedsDataSource.SelectParameters.Clear();
                careNeedsDataSource.SelectParameters.Add("CprId", System.Data.DbType.Int32, Convert.ToString(cprId));
                careNeedsDataSource.Select();
                careNeedsDataSource.DataBind();
            }
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "clearPanel();", true);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      相关资源
      最近更新 更多