Question

I have a gridview and several template fields and several rowcommands. I would like to use the built in update row command but the problem I'm running into is making it so my application isn't functioning correctly.

Problem: In one of my edititem template fields I have both a Label control and a dropdown control. The reason for this is that I need to hide/show one or the other depending on the rowcommand is triggered. When I use the built in edit rowcommand I hide the dropdown and display the dropdownlist. So everything works there. However, when update rowcommand is triggered it is using the label value which is not visible and is bound to display the month rather than the full date that is needed. I use the drop down list to display the month to the user and the selected value is the full date. For some odd reason it wants to use the label value instead of the drop down list selected value even though I specify the update parameter in the code behind. If I remove the label from the commissionmonth column then everything works just fine except for the fact that on my other row commands the drop down list I would have to display a drop down list instead of the wanted label.

If any of you know how to specify the control to use in the update rowcommand or somehow dynamically change that column to read only on certain row commands I would greatly appreciate it!

Code Sample:

<asp:GridView ID="UnverifiedSalesGV" runat="server" AllowSorting="True" 
            AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" 
            BorderStyle="None" BorderWidth="1px" CellPadding="4"
            DataSourceID="UnverifiedSalesSDS" ForeColor="Black" GridLines="Vertical" 
            Width="100%" ShowHeaderWhenEmpty="True" DataKeyNames="ID" 
            onrowupdating="UnverifiedSalesGV_RowUpdating" 
            onrowcommand="UnverifiedSalesGV_RowCommand" 
            onrowdatabound="UnverifiedSalesGV_RowDataBound">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField ShowHeader="False">
                                <ItemTemplate>
                                    <asp:Button ID="EditBTN" runat="server" CausesValidation="False" 
                                        CommandName="Edit" Text="Edit" />
                                    <asp:Button ID="VerifyBTN" runat="server" Text="Verify" CommandName="VerifyRecord" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
                                </ItemTemplate>
                                <ItemStyle HorizontalAlign="Center" />
                                <EditItemTemplate>
                                    <asp:Button ID="UpdateBTN" runat="server" CausesValidation="True" 
                                        CommandName="Update" Text="Update" />
                                    <asp:Button ID="UpdateProductBTN" runat="server" Text="Verify" CommandName="UpdateProduct" Visible="false" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
                                    &nbsp;<asp:Button ID="CancelBTN" runat="server" CausesValidation="False" 
                                        CommandName="Cancel" Text="Cancel" />

                                </EditItemTemplate>
                </asp:TemplateField>

                <asp:BoundField DataField="CompanyName" HeaderText="Company" 
                    SortExpression="CompanyName" ReadOnly="True" />
                <asp:BoundField DataField="SalesRep" HeaderText="Sales Rep" 
                    SortExpression="SalesRep" ReadOnly="True" >
                <ItemStyle Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="AccountManager" HeaderText="Account Manager" 
                    SortExpression="AccountManager" ReadOnly="True" >
                <ItemStyle Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="ProductID" HeaderText="ProductID" 
                    SortExpression="ProductID" Visible="False" />
                <asp:TemplateField HeaderText="Product" SortExpression="Product">
                    <ItemTemplate>
                        <asp:Label ID="Label5" runat="server" Text='<%# Bind("Product") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="CurrentProductLBL" runat="server" Text='<%# Eval("Product") %>'></asp:Label>
                        <asp:DropDownList ID="RenewalProductDDL" runat="server" 
                            DataSourceID="RenewalProductSDS" DataTextField="Product" DataValueField="ID" Visible="false">
                        </asp:DropDownList>
                        <asp:SqlDataSource ID="RenewalProductSDS" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:Wizard_SwearsConnectionString1 %>" 

                        SelectCommand="SELECT * FROM [Product] LEFT JOIN ProductToProductCategory AS Category ON Product.ID = Category.ProductID WHERE Category.ProductCategoryID = 5 AND Product.ID &lt;&gt; 38 ORDER BY [Product]"></asp:SqlDataSource>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="DateFulfilled" DataFormatString="{0:M/d/yyyy}" 
                    HeaderText="Date Fulfilled" SortExpression="DateFulfilled" 
                    ReadOnly="True" />
                <asp:TemplateField HeaderText="Gross Sales Amount" 
                    SortExpression="GrossSalesAmount">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" 
                            Text='<%# Bind("GrossSalesAmount", "{0:C}") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="GrossSalesLBL" runat="server" 
                            Text='<%# Bind("GrossSalesAmount", "{0:C}") %>' Visible="false"></asp:Label>
                        <asp:TextBox ID="GrossSalesTXT" runat="server" 
                            Text='<%# Bind("GrossSalesAmount") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Net Sales Amount" 
                    SortExpression="NetSalesAmount">
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" 
                            Text='<%# Bind("NetSalesAmount", "{0:C}") %>' ></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="NetSalesLBL" runat="server" Text='<%# Bind("NetSalesAmount", "{0:C}") %>' Visible="false"></asp:Label>
                        <asp:TextBox ID="NetSalesTXT" runat="server" Text='<%# Bind("NetSalesAmount") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Commission Month" 
                    SortExpression="CommissionMonth">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" 
                            Text='<%# Bind("CommissionMonth", "{0:MMMM}") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="CommissionMonthDDL" runat="server" 
                            DataSourceID="SalesCommissionDDLSDS" DataTextField="Month" 
                            DataValueField="CommissionMonth">
                        </asp:DropDownList>
                        <asp:Label ID="SalesCommissionLBL" runat="server" 
                            Text='<%# Bind("CommissionMonth") %>' Visible="false" ></asp:Label>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Notes" SortExpression="Notes">
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("Notes") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="NotesLBL" runat="server" Text='<%# Bind("Notes") %>' Visible="false"></asp:Label>
                        <asp:TextBox ID="NotesTXT" runat="server" Text='<%# Bind("Notes") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCC99" />
            <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#F7F7DE" />
            <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FBFBF2" />
            <SortedAscendingHeaderStyle BackColor="#848384" />
            <SortedDescendingCellStyle BackColor="#EAEAD3" />
            <SortedDescendingHeaderStyle BackColor="#575357" />
        </asp:GridView>

Code behind:

protected void UnverifiedSalesGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

    //Get date and user info
    DateTime getDate = System.DateTime.Now;
    MembershipUser user = Membership.GetUser();
    string activeuser = user.UserName;

    try
    {
        //Get dropdown and textbox values
        string commisionMonth;
        string grossSalesAmount;
        string netSalesAmount;
        string notes;

        TextBox grossSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("GrossSalesTXT");
        TextBox netSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("NetSalesTXT");
        TextBox notesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("NotesTXT");
        DropDownList commissionMonthValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("CommissionMonthDDL");
        grossSalesAmount = grossSalesValue.Text;
        netSalesAmount = netSalesValue.Text;
        commisionMonth = commissionMonthValue.SelectedValue;
        notes = notesValue.Text;


        UnverifiedSalesSDS.UpdateParameters["GrossSalesAmount"].DefaultValue = grossSalesAmount;
        UnverifiedSalesSDS.UpdateParameters["NetSalesAmount"].DefaultValue = netSalesAmount;
        UnverifiedSalesSDS.UpdateParameters["CommissionMonth"].DefaultValue = commisionMonth;
        UnverifiedSalesSDS.UpdateParameters["Notes"].DefaultValue = notes;
        UnverifiedSalesSDS.UpdateParameters["DateLastModified"].DefaultValue = getDate.ToString();
        UnverifiedSalesSDS.UpdateParameters["UserLastModified"].DefaultValue = activeuser;


        UnverifiedSalesSDS.Update();



    }
    catch (Exception ex)
    {
        MessageLBL.ForeColor = Color.Red;
        MessageLBL.Text = "Could not update record. Message: " + ex.Message;
    }
}
Was it helpful?

Solution

I was finally able to solve my problem with the following code:

//Verify and Update Record
protected void UnverifiedSalesGV_RowCommand(object sender, GridViewCommandEventArgs e)
{
    buttonCommand = e.CommandName;

    if (buttonCommand != "Cancel" && buttonCommand != "Edit" && buttonCommand != "Sort")
    {

        //Get Gridview data key and row index
        rowIndex = Convert.ToInt32(e.CommandArgument);
        salesID = UnverifiedSalesGV.DataKeys[rowIndex].Value.ToString();
        MessageLBL.Text = "";

        //Get productID 
        SalesData getSalesRecord = new SalesData();
        getSalesRecord.GetRowValuesSalesID(salesID);
        string productID = getSalesRecord.productID;

        if (buttonCommand == "VerifyRecord")
        {
            if (productID != "38")
            {

                try
                {
                    UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET Verified = @Verified WHERE ID = @ID";
                    UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
                    UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
                    UpdateSalesRecordSDS.Update();

                    UnverifiedSalesGV.DataBind();
                    VerifiedSalesGV.DataBind();
                }
                catch (Exception ex)
                {
                    MessageLBL.ForeColor = Color.Red;
                    MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
                }
            }
            else
            {
                //Get row index.
                UnverifiedSalesGV.SetEditRow(rowIndex);
                UnverifiedSalesGV.DataBind();

            }
        }
        if (buttonCommand == "UpdateProduct")
        {

            DropDownList productValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("RenewalProductDDL");
            if (productValue.SelectedIndex != 0)
            {
                try
                {
                    UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET ProductID = @ProductID, Verified = @Verified WHERE ID = @ID";
                    UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
                    UpdateSalesRecordSDS.UpdateParameters["ProductID"].DefaultValue = productValue.SelectedValue;
                    UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
                    UpdateSalesRecordSDS.Update();

                    UnverifiedSalesGV.DataBind();
                    UnverifiedSalesGV.EditIndex = -1;
                    VerifiedSalesGV.DataBind();
                }
                catch (Exception ex)
                {
                    MessageLBL.ForeColor = Color.Red;
                    MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
                }
            }
            else
            {
                MessageLBL.ForeColor = Color.Red;
                MessageLBL.Text = "Please select renewal type.";
            }

        }
        if (buttonCommand == "UpdateRecord")
        {
            //Get date and user info
            DateTime getDate = System.DateTime.Now;
            MembershipUser user = Membership.GetUser();
            string activeuser = user.UserName;

            try
            {
                //Get dropdown and textbox values
                string amid;
                string commisionMonth;
                string grossSalesAmount;
                string netSalesAmount;
                string notes;

                DropDownList accountManagerID = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("AccountManagerDDL");
                TextBox grossSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("GrossSalesTXT");
                TextBox netSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NetSalesTXT");
                TextBox notesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NotesTXT");
                DropDownList commissionMonthValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("CommissionMonthDDL");

                amid = accountManagerID.SelectedValue;
                grossSalesAmount = grossSalesValue.Text;
                netSalesAmount = netSalesValue.Text;
                commisionMonth = commissionMonthValue.SelectedValue;
                notes = notesValue.Text;

                UnverifiedSalesSDS.UpdateCommand = "UPDATE [Sales] SET [OriginalAMID] = @OriginalAMID, [GrossSalesAmount] = @GrossSalesAmount, [NetSalesAmount] = @NetSalesAmount, [Notes] = @Notes, [CommissionMonth] = @CommissionMonth, [DateLastModified] = @DateLastModified, [UserLastModified] = @UserLastModified WHERE [ID] = @ID";
                UnverifiedSalesSDS.UpdateParameters["OriginalAMID"].DefaultValue = amid;
                UnverifiedSalesSDS.UpdateParameters["GrossSalesAmount"].DefaultValue = grossSalesAmount;
                UnverifiedSalesSDS.UpdateParameters["NetSalesAmount"].DefaultValue = netSalesAmount;
                UnverifiedSalesSDS.UpdateParameters["CommissionMonth"].DefaultValue = commisionMonth;
                UnverifiedSalesSDS.UpdateParameters["Notes"].DefaultValue = notes;
                UnverifiedSalesSDS.UpdateParameters["DateLastModified"].DefaultValue = getDate.ToString();
                UnverifiedSalesSDS.UpdateParameters["UserLastModified"].DefaultValue = activeuser;
                UnverifiedSalesSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();


                UnverifiedSalesSDS.Update();
                UnverifiedSalesGV.DataBind();
                UnverifiedSalesGV.EditIndex = -1;


            }
            catch (Exception ex)
            {
                MessageLBL.ForeColor = Color.Red;
                MessageLBL.Text = "Could not update record. Message: " + ex.Message;
            }
        }
    }
}

//Hide and show fields
protected void UnverifiedSalesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex == rowIndex)
    {
        string state = e.Row.RowState.ToString();
        if (state == "Alternate, Edit" || state == "Edit")
        {

            //Get record ID
            string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.Row.DataItemIndex)].Value.ToString();

            //Get productID 
            SalesData getSalesRecord = new SalesData();
            getSalesRecord.GetRowValuesSalesID(salesID);

            string productID = getSalesRecord.productID;

            if (productID == "38")
            {
                //Items to Hide/Display
                Button UpdateProductBTN = (Button)e.Row.FindControl("UpdateProductBTN");
                Button UpdateBTN = (Button)e.Row.FindControl("UpdateBTN");
                Label productLBL = (Label)e.Row.FindControl("CurrentProductLBL");
                Label accountManagerLBL = (Label)e.Row.FindControl("AccountManagerLBL");
                DropDownList productDDL = (DropDownList)e.Row.FindControl("RenewalProductDDL");
                DropDownList accountManagerDDL = (DropDownList)e.Row.FindControl("AccountManagerDDL");
                Label grossSalesLBL = (Label)e.Row.FindControl("GrossSalesLBL");
                TextBox grossSalesTXT = (TextBox)e.Row.FindControl("GrossSalesTXT");
                Label netSalesLBL = (Label)e.Row.FindControl("NetSalesLBL");
                TextBox netSalesTXT = (TextBox)e.Row.FindControl("NetSalesTXT");
                Label commissionMonthLBL = (Label)e.Row.FindControl("SalesCommissionLBL");
                DropDownList commissionMonthDDL = (DropDownList)e.Row.FindControl("CommissionMonthDDL");
                TextBox notesTXT = (TextBox)e.Row.FindControl("NotesTXT");
                Label notesLBL = (Label)e.Row.FindControl("NotesLBL");


                UpdateProductBTN.Visible = true;
                UpdateBTN.Visible = false;
                productLBL.Visible = false;
                productDDL.Visible = true;
                accountManagerLBL.Visible = true;
                accountManagerDDL.Visible = false;
                grossSalesLBL.Visible = true;
                grossSalesTXT.Visible = false;
                netSalesLBL.Visible = true;
                netSalesTXT.Visible = false;
                commissionMonthLBL.Visible = true;
                commissionMonthDDL.Visible = false;
                notesTXT.Visible = false;
                notesLBL.Visible = true;
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top