网格使用ObjectDataSource绑定和更新网格后,在更新后显示旧值

时间:2012-11-15 10:46:33

标签: c# asp.net ajaxcontroltoolkit

我正在使用ObjectDataSource来绑定和更新网格。它工作正常并且数据库中的记录正在更新但是在更新后,它仍然在网格中显示相同的记录(Previous Values)。请帮助我,我会这样做,以便在数据库更新后,网格将显示更新的记录,而不是旧记录。如果有任何人找到解决方案,请修改我的代码。

先谢谢。

请找到以下代码。

GridView代码: -

<asp:Panel ID="pnlGrdShift" runat="server" ScrollBars="Auto" Width="900px" Height="520px" CssClass="srcColor">
            <cc1:GridView  ID="gvShift" runat="server" AutoGenerateColumns="False" AllowSorting="True"
               CssClass="grid"
               OnDataBound="gvShift_DataBound" 
               DataSourceID="odsShiftDetails" 
               AllowPaging="True" 
               ShowFooter="false"
               onrowcancelingedit="gvShift_RowCancelingEdit" 
               onrowcommand="gvShift_RowCommand" 
               onrowdeleting="gvShift_RowDeleting" 
               onrowediting="gvShift_RowEditing" 
               onrowupdating="gvShift_RowUpdating" 
               OnSelectedIndexChanged="gvShift_SelectedIndexChanged" 
               OnRowDataBound="gvShift_RowDataBound">        
                <AlternatingRowStyle CssClass="altrowstyle"  />
                <HeaderStyle CssClass="headerstyle" />
                <RowStyle CssClass="rowstyle" Wrap="false"  />
                <EmptyDataRowStyle BackColor="#edf5ff" Height="300px" VerticalAlign="Middle" HorizontalAlign="Center" />
                <EmptyDataTemplate >
                    No Records Found
                </EmptyDataTemplate> 
                <Columns>
                    <asp:TemplateField HeaderText="E Code" SortExpression="userecode" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
                        <ItemTemplate>
                            <asp:Label ID="lblUserECode" runat="server" Text='<%#Eval("userecode") %>' CssClass="GridContent" />                    
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:Label ID="lblEditUserECode" runat="server" Text='<%#Eval("userecode") %>' style="width:50px;" CssClass="GridContent" />                    
                        </EditItemTemplate>
                    </asp:TemplateField>                       

                    <asp:TemplateField HeaderText="User Name" SortExpression="username" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
                        <ItemTemplate>
                            <asp:Label ID="lblUserName" runat="server" Text='<%#Eval("username") %>' CssClass="GridContent" />                    
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:Label ID="lblEditUserName" runat="server" Text='<%#Eval("username") %>' style="width:100px;" CssClass="GridContent"/>                    
                        </EditItemTemplate>
                    </asp:TemplateField>


                    <asp:TemplateField HeaderText="Shift Start Time" SortExpression="ShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
                         <ItemTemplate>
                            <asp:Label ID="lblShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>'  CssClass="GridContent"/>                    
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="ddlShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
                            <asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftStartTime" runat="server" ControlToValidate="ddlShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />                            

                        </EditItemTemplate>                            
                    </asp:TemplateField>  

                    <asp:TemplateField HeaderText="Shift End Time" SortExpression="ShiftEndTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
                        <ItemTemplate>
                            <asp:Label ID="lblShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' CssClass="GridContent" />                    
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="ddlShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' style="width:65px;" CssClass="GridContent"  />
                            <asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftEndTime" runat="server" ControlToValidate="ddlShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />                            

                        </EditItemTemplate>                            
                    </asp:TemplateField>
                        <%--<asp:BoundField DataField="ShiftEndTIme" HeaderText="Shift End Time" SortExpression="ShiftEndTIme"/>--%>
                    <asp:TemplateField HeaderText="Saturday Shift Start Time" SortExpression="WeekendShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
                        <ItemTemplate>
                            <asp:Label ID="lblWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' CssClass="GridContent" />                    
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="ddlWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />  
                            <asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftStartTime" runat="server" ControlToValidate="ddlWeekendShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />                          

                        </EditItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Saturday Shift End Time" SortExpression="weekendshiftendtime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
                    <ItemTemplate>
                            <asp:Label ID="lblWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' CssClass="GridContent"/>                    
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="ddlWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' style="width:65px;" CssClass="GridContent" /> 
                            <asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftEndTime" runat="server" ControlToValidate="ddlWeekendShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />                           

                        </EditItemTemplate>                           
                    </asp:TemplateField>

                    <asp:TemplateField  ShowHeader="False" > 
                        <EditItemTemplate> 
                          <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update" ForeColor="White"></asp:LinkButton> 
                          <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" ForeColor="White"></asp:LinkButton> 
                        </EditItemTemplate> 
                        <ItemTemplate> 
                          <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" ForeColor="White"></asp:LinkButton> 
                        </ItemTemplate> 
                </asp:TemplateField>                    
           </Columns>
                <PagerTemplate >
                     <table width="100%" >
                        <tr>
                            <td style="text-align:  left">
                                Page Size: 
                                    <asp:DropDownList ID="ddPageSize" runat="server" EnableViewState="true" OnSelectedIndexChanged="ddPageSize_SelectedIndexChanged" AutoPostBack="true" style="width:50px;">
                                    <asp:ListItem Text="10" ></asp:ListItem>
                                    <asp:ListItem Text="20" ></asp:ListItem>
                                    <asp:ListItem Text="30" ></asp:ListItem>
                                    <asp:ListItem Text="40" ></asp:ListItem>
                                    <asp:ListItem Text="50" ></asp:ListItem>
                                </asp:DropDownList>
                            </td>
                            <td style="text-align: right">
                                <asp:Label ID="lblPageCount" runat="server"></asp:Label>
                            </td>
                        </tr>
                    </table>
                </PagerTemplate>
                </cc1:GridView>      
         </asp:Panel>


 <asp:ObjectDataSource ID="odsShiftDetails" runat="server" 
                SelectMethod="GetShiftInfoSortedPage" TypeName="EQ.DAL.ShiftInfoDB"
                EnablePaging="True" SelectCountMethod="GetShiftInfoCount" 
                SortParameterName="sortExpression" UpdateMethod="UpdateShift">
                <UpdateParameters>
                <asp:Parameter Name="sql"/>
                </UpdateParameters>
                <SelectParameters>
                    <asp:ControlParameter  ControlID="hfSearchCriteria"  Name="searchCriteria" Direction="Input"  />
                </SelectParameters>                                            
            </asp:ObjectDataSource>

更新后面的代码: -

protected void gvShift_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            TextBox txtShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftStartTime");
            TextBox txtShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftEndTime");
            TextBox txtWeekendShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftStartTime");
            TextBox txtWeekendShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftEndTime");
            Label lblUserecode = (Label)gvShift.Rows[e.RowIndex].FindControl("lblEditUserECode");

            string userecode = lblUserecode.Text.ToString();
            string _ShiftStart = txtShiftStartTime.Text.ToString();
            string _ShiftEnd = txtShiftEndTime.Text.ToString();
            string _WeekendShiftStart = txtWeekendShiftStartTime.Text.ToString();
            string _WeekendShiftend = txtWeekendShiftEndTime.Text.ToString();

            EmployeeQuotientCL.Entities.ConfigurationVariables _configVariables = new ConfigurationVariables();
            string databaseConnectionString = _configVariables.ConnectionString;
            SqlConnection sqlConnection = null;
            if (((databaseConnectionString + string.Empty) != string.Empty))
            {

                DBConnect dbConnect = new DBConnect(_configVariables.ConnectionString);
                sqlConnection = dbConnect.SQLConnection;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = sqlConnection;
                string sql=null;
                cmd.CommandText = "UPDATE UserInfo SET ShiftStartTime ='" + _ShiftStart + "',ShiftEndTime='" + _ShiftEnd.ToString() + "',Weekendshiftstarttime='" + _WeekendShiftStart.ToString() + "',Weekendshiftendtime='" + _WeekendShiftend.ToString() + "'   WHERE UserECode=" + userecode.ToString();
                odsShiftDetails.UpdateParameters["sql"].DefaultValue = cmd.CommandText;
                odsShiftDetails.Update();
            }
        }
        catch (Exception ex)
        {
        }
    }

ShiftInfoDBCache.cs

public class ShiftInfoDB
{
    private const string SHIFTINFO_CACHE_KEY = "SHIFTINFO_DATA";
    private const string SHIFTINFOCOUNT_CACHE_KEY = "SHIFTINFO_COUNT";
    static EmployeeQuotientCL.Entities.ConfigurationVariables _config = new EmployeeQuotientCL.Entities.ConfigurationVariables();
    static int _SupervisorecodeforShift;


    public static  DataTable GetShiftInfoSortedPage(int maximumRows, int startRowIndex, string sortExpression, string searchCriteria)
    {
        _SupervisorecodeforShift=EmployeeQuotientCL.Entities.StaticGlobalValue.UserId;

        if (string.IsNullOrEmpty(sortExpression))
            sortExpression = "userecode";
        try
        {
            if (ShiftInfoDBCache.isRecordsCached(SHIFTINFO_CACHE_KEY))
                return ShiftInfoDBCache.GetData(SHIFTINFO_CACHE_KEY, startRowIndex + 1, maximumRows, sortExpression, searchCriteria);

            SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
            string sql = "select distinct MP.userecode,UI.username,UI.ShiftStartTime,UI.ShiftEndTime,UI.WeekendShiftStartTime,UI.weekendshiftendtime from AssociateSupervisorMapping MP inner join UserInfo UI on MP.Userecode=UI.Userecode where supervisorecode=" + _SupervisorecodeforShift.ToString();

            SqlCommand custCommand = new SqlCommand(sql, dbConnection);

            custCommand.CommandType = CommandType.Text;

            SqlDataAdapter ad = new SqlDataAdapter(custCommand);
            DataTable dtCustomers = new DataTable();
            ad.Fill(dtCustomers);
            dbConnection.Close();


            //Cache records
            ShiftInfoDBCache.Add(SHIFTINFO_CACHE_KEY, dtCustomers);

        }
        catch (Exception e)
        {

            throw;
        }
        return ShiftInfoDBCache.GetData(SHIFTINFO_CACHE_KEY, startRowIndex + 1, maximumRows, sortExpression, null);
    }

    public static int GetShiftInfoCount(string searchCriteria)
    {
         _SupervisorecodeforShift=EmployeeQuotientCL.Entities.StaticGlobalValue.UserId;
        int custCount = 0;
        try
        {
            SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
            string sql = "select Count(*)from (select distinct MP.userecode,UI.username,UI.ShiftStartTime,UI.ShiftEndTime,UI.WeekendShiftStartTime,UI.weekendshiftendtime from AssociateSupervisorMapping MP inner join UserInfo UI on  MP.Userecode=UI.Userecode   where supervisorecode="+_SupervisorecodeforShift.ToString()+")AS internalQuery";

            if (!string.IsNullOrEmpty(searchCriteria))
                sql = sql + " where " + searchCriteria;

            SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
            sqlCommand.Connection = dbConnection;
            dbConnection.Open();
            sqlCommand.CommandType = CommandType.Text;

            custCount = Convert.ToInt32(sqlCommand.ExecuteScalar());

            dbConnection.Close();

            if (ShiftInfoDBCache.Get(SHIFTINFOCOUNT_CACHE_KEY) != null)
            {
                // remove customers data if customers count has changed since first cache
                if (Convert.ToInt32(ShiftInfoDBCache.Get(SHIFTINFOCOUNT_CACHE_KEY)) != custCount && string.IsNullOrEmpty(searchCriteria))
                {
                    ShiftInfoDBCache.Remove(SHIFTINFO_CACHE_KEY);
                }
            }

            if (string.IsNullOrEmpty(searchCriteria))
                ShiftInfoDBCache.Add(SHIFTINFOCOUNT_CACHE_KEY, custCount);
        }
        catch (Exception e)
        {
            throw;
        }
        return custCount;

    }

    public static void UpdateShift(string sql)
    {
        SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
        SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
        sqlCommand.CommandType=CommandType.Text;
        sqlCommand.CommandText=sql;
        dbConnection.Open();
        sqlCommand.Connection = dbConnection;
        //sqlCommand.CommandType = CommandType.Text;
        sqlCommand.ExecuteNonQuery();
        dbConnection.Close();
    }



}

ShiftInfoDBCache.cs

public  class ShiftInfoDBCache
{
    public static bool isRecordsCached(string cacheKey)
    {
        Cache dbCache = HttpContext.Current.Cache;

        if (dbCache[cacheKey] == null)
            return false;

        return true;
    }

    public static void Add(string key, object value)
    {
        Cache dbCache = HttpContext.Current.Cache;

        dbCache.Add(key, value, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);

    }

    public static object Get(string key)
    {
        Cache dbCache = HttpContext.Current.Cache;

        return dbCache[key];
    }

    public static object Remove(string key)
    {
        Cache dbCache = HttpContext.Current.Cache;

        return dbCache.Remove(key);
    }

    public static DataTable GetData(string cacheKey, int startRowIndex, int maximumRowNumber, string sortExpression, string searchCriteria)
    {
        Cache dbCache = HttpContext.Current.Cache;

        if (dbCache[cacheKey] != null)
        {

            DataTable dtble = dbCache[cacheKey] as DataTable;
            DataTable dtblNew = dtble.Clone();

            DataRow[] rows = dtble.Select(searchCriteria, sortExpression);

            if (rows != null)
            {
                if (rows.Count() > 0)
                {
                    if (startRowIndex > rows.Count())
                    {
                        startRowIndex = rows.Count() - maximumRowNumber;

                        if (startRowIndex < 0)
                        {
                            startRowIndex = 1;
                            maximumRowNumber = rows.Count();
                        }
                    }

                    for (int i = startRowIndex - 1; i < (startRowIndex + maximumRowNumber - 1); i++)
                    {
                        if (i < rows.Count())
                            dtblNew.ImportRow(rows[i]);
                    }

                    return dtblNew;
                }
            }

            return dtblNew;

        }

        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

public static void UpdateShift(string sql)
    {
        SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
        SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
        sqlCommand.CommandType=CommandType.Text;
        sqlCommand.CommandText=sql;
        dbConnection.Open();
        sqlCommand.Connection = dbConnection;
        //sqlCommand.CommandType = CommandType.Text;
        sqlCommand.ExecuteNonQuery();
        dbConnection.Close();
        ShiftInfoDBCache.Remove(SHIFTINFO_CACHE_KEY);


    }

UpdateShift中修改ShiftInfoDB.cs方法解决了我的问题。

相关问题