简体   繁体   English

如何指定在GridView RowUpdate中使用哪个控件

[英]How to specify which control to use in the gridview rowupdate

I have a gridview and several template fields and several rowcommands. 我有一个gridview和几个模板字段和几个rowcommand。 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. 我想使用内置的update row命令,但是遇到的问题是它使我的应用程序无法正常运行。

Problem: In one of my edititem template fields I have both a Label control and a dropdown control. 问题:在我的edititem模板字段之一中,我同时具有Label控件和下拉控件。 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. 由于某种奇怪的原因,即使我在后面的代码中指定了update参数,它也希望使用标签值而不是下拉列表中的选定值。 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. 如果我从Commissionmonth列中删除标签,则一切正常,除了在我的另一行命令下拉列表中,我必须显示一个下拉列表而不是所需标签的事实。

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! 如果您知道如何指定要在update rowcommand中使用的控件,或者以某种方式动态地将该列更改为仅在某些行命令上读取,我将不胜感激!

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;
    }
}

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;
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM