?
Solved

Updating Gridview using OnUpdating Event does not get Values from Editing row

Posted on 2010-09-15
5
Medium Priority
?
2,321 Views
Last Modified: 2013-12-16
Scenario:
I am using the RowUpdating Event of the Gridview to do updates because I need more flexibility than the SQLDatasource Update provides.  So the problem I am having is that when I get the Datakey value I am trying to get the values in the controls in the Edit Mode of the current row I am trying to update.  But I get some strange results.  I am using the FindControl function to get the values from the editing row so I specifically name the dropdownlists and textboxes so I can access them here.  But what happens is that I do get some of the values but they are the original values not the new ones being changed.  In the code below I do get the CountryID and RegionID but they are the original values not the new ones selectedfrom the Edit Mode row.   The Textbox values come back as empty, which is even stranger.  Need some help figuring this out.  Below is the code for both the GridView HTML and the C# code behind.

Code (C# OnUpdating Event)

protected void gvMain_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //---- Get Gridview Datakey Value and Dropdown value from selected Index ---
        string recIDTxt = gvMain.DataKeys[e.RowIndex].Value.ToString();
        int recID = Convert.ToInt32(recIDTxt);

        //--- Define Gridview Row Elements
        GridView grid = (GridView)sender;
        GridViewRow row = (GridViewRow)grid.Rows[e.RowIndex];
        DropDownList ddlCountryEdit = (DropDownList)row.FindControl("ddlCountryEdit");
        DropDownList ddlRegionEdit = (DropDownList)row.FindControl("ddlRegionEdit");
        TextBox txtModelNameEdit = (TextBox)row.FindControl("txtModelNameEdit");
        TextBox txtTransModelEdit = (TextBox)row.FindControl("txtTransModelEdit");
        TextBox txtPriceEdit = (TextBox)row.FindControl("txtPriceEdit");
         

        int countryID = Convert.ToInt32(ddlCountryEdit.SelectedValue);  // This returns old value
        int regionID = Convert.ToInt32(ddlRegionEdit.SelectedValue); // This returns old value
        string modelName = txtSearchModelName.Text;  // This returns and empty string
        string transModel = txtTranslateModel.Text;  // This returns and empty string
        decimal price = Convert.ToDecimal(txtPriceEdit.Text); // this retuns the old value


        if (row.RowType == DataControlRowType.DataRow)
        {
            HttpCookie cookie = Request.Cookies["DOTOOLS"];
            string returnUser = string.Empty;

            if (cookie != null)
            {
                string userID = cookie["UserID"];
                string fname = cookie["FirstName"];
                string lname = cookie["LastName"];
                returnUser = fname.Substring(0, 1) + "." + lname;
            }

            UpdatedByUpdate(recID, returnUser, countryID, regionID, modelName, transModel, price);
        }
    }

Gridview HTML Code

<asp:GridView ID="gvMain" runat="server" AllowSorting="True" AutoGenerateColumns="False"
        DataSourceID="dsrcGridViewMain1" DataKeyNames="RecID,CountryID,ModelName" OnRowDataBound="gvMain_RowDataBound" OnRowUpdating="gvMain_RowUpdating" OnRowUpdated="gvMain_RowUpdated">
        <Columns>
            <asp:TemplateField ShowHeader="False">
                <EditItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                        Text="Update"></asp:LinkButton>
                    <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                        Text="Cancel"></asp:LinkButton>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
                        Text="Edit"></asp:LinkButton>
                    <asp:LinkButton ID="lnkDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
                        Text="Delete"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="RecID" HeaderText="RecID" InsertVisible="False" ReadOnly="True"
                SortExpression="RecID" Visible="False" />
            <asp:BoundField DataField="RegionID" HeaderText="RegionID" SortExpression="RegionID"
                Visible="False" />
            <asp:BoundField DataField="CountryID" HeaderText="CountryID" ReadOnly="True" SortExpression="CountryID"
                Visible="False" />
            <asp:TemplateField HeaderText="CompanyCode" SortExpression="CompanyCode">
                <EditItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("CompanyCode") %>'></asp:Label>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("CompanyCode") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Country" SortExpression="Country">
                <EditItemTemplate>
                    <asp:DropDownList ID="ddlCountryEdit" runat="server" AppendDataBoundItems="True"
                            DataSourceID="dsrcCountryCodes" DataTextField="Country" DataValueField="CountryID" SelectedValue='<%# Bind("CountryID") %>'>
                        <asp:ListItem>-- Select Country --</asp:ListItem>
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("CountryName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Region" SortExpression="Region">
                <EditItemTemplate>
                    <asp:DropDownList ID="ddlRegionEdit" runat="server" AppendDataBoundItems="True"
                            DataSourceID="dsrcNewRegions" DataTextField="Region" DataValueField="RegionID" SelectedValue='<%# Bind("RegionID") %>'>
                        <asp:ListItem>-- Select Region --</asp:ListItem>
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("Region") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ModelName" SortExpression="ModelName">
                <EditItemTemplate>
                    <asp:TextBox ID="txtModelNameEdit" runat="server" Text='<%# Bind("ModelName") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label6" runat="server" Text='<%# Bind("ModelName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="TranslateModel" SortExpression="TranslateModel">
                <EditItemTemplate>
                    <asp:TextBox ID="txtTransModelEdit" runat="server" Text='<%# Bind("TranslateModel") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label7" runat="server" Text='<%# Bind("TranslateModel") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Price" SortExpression="Price">
                <EditItemTemplate>
                    <asp:TextBox ID="txtPriceEdit" runat="server" Text='<%# Bind("Price") %>' Width="60px"></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label8" runat="server" Text='<%# Bind("Price", "{0:0.00}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Updated" SortExpression="LastUpdatedOn">
                <EditItemTemplate>
                    <asp:Label ID="lblUpdatedOn" runat="server" Text='<%# Bind("LastUpdatedOn", "{0:d}") %>'></asp:Label>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("LastUpdatedOn", "{0:d}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="By" SortExpression="LastUpdatedBy">
                <EditItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("LastUpdatedBy") %>'></asp:Label>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("LastUpdatedBy") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <HeaderStyle ForeColor="White" />
        <AlternatingRowStyle BackColor="#EFF3FB" />
    </asp:GridView>
    <asp:SqlDataSource ID="dsrcGridViewMain" runat="server" ConnectionString="<%$ ConnectionStrings:ControlTablesConnectionString %>"
        DeleteCommand="DELETE FROM dbo.AARP_DATA_D1_BillMatrix WHERE (RecID = @RecID) " 
        SelectCommand="SELECT RecID, CompanyID, RegionID, CountryID, CompanyCode, CompanyName, AppID, CountryCode, CountryName, RegionCompanyID, Region, ModelName, TranslateModel, Price, LastUpdatedOn, LastUpdatedBy FROM dbo.AARP_DATA_D1_BillMatrix_View;"
        UpdateCommand="UPDATE dbo.AARP_DATA_D1_BillMatrix SET RegionID = @RegionID, CountryID = @CountryID, ModelName = @ModelName, TranslateModel = @TranslateModel, Price = @Price WHERE (RecID = @RecID)">
        <DeleteParameters>
            <asp:Parameter Name="RecID" />
        </DeleteParameters>
        <UpdateParameters>
            <asp:Parameter Name="RegionID" />
            <asp:Parameter Name="CountryID" />
            <asp:Parameter Name="ModelName" />
            <asp:Parameter Name="TranslateModel" />
            <asp:Parameter Name="Price" />
            <asp:Parameter Name="RecID" />
        </UpdateParameters>
    </asp:SqlDataSource>

0
Comment
Question by:jholmes0724
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 41

Expert Comment

by:guru_sami
ID: 33684053
did you try accessing via e.NewValues?
Check two example here:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowupdating.aspx
0
 

Author Comment

by:jholmes0724
ID: 33684285
It still gets the old values,  when I loop thru the Dictionary and in debug step thru it I see it still gets the original values not the new values that the user enters when they are changing each item.

// Iterate through the NewValues collection and HTML encode all
    // user-provided values before updating the data source.
    foreach (DictionaryEntry entry in e.NewValues)
    {

      e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());

    }
0
 
LVL 41

Accepted Solution

by:
guru_sami earned 2000 total points
ID: 33703814
I don't know really what's going on but will still ask a stupid question:
Check if your GV is not being databound accidentally in code-behind before Updating call.
0
 

Author Comment

by:jholmes0724
ID: 33735521
guru_sami,
sorry it took me so long to get back, I have been off on vacation and just got back, but yes you are right on, I went back and debugged the entire postback and it was rebinding the grid on postback on the page_load event.   Thanks good call.
0
 

Author Closing Comment

by:jholmes0724
ID: 33735531
Thank you your analysis was right on the money.
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question