Solved

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

Posted on 2010-09-15
5
2,135 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
  • 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 500 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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

707 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now