如何指定在gridview rowupdate中使用哪个控件

时间:2013-08-07 02:23:52

标签: c# asp.net .net gridview aspxgridview

我有一个gridview和几个模板字段以及几个rowcommands。我想使用内置的更新行命令,但我遇到的问题是使我的应用程序无法正常运行。

问题:在我的一个edititem模板字段中,我有一个Label控件和一个下拉控件。原因是我需要隐藏/显示一个或另一个,具体取决于rowcommand被触发。当我使用内置的编辑行命令时,我隐藏了下拉列表并显示下拉列表。所以一切都在那里。但是,当触发update rowcommand时,它使用的标签值不可见,并且必须显示月份而不是所需的完整日期。我使用下拉列表向用户显示月份,所选值为完整日期。由于一些奇怪的原因,它想要使用标签值而不是下拉列表选择值,即使我在后面的代码中指定更新参数。如果我从Commissionmonth列中删除标签,那么一切正常,除了在我的另一行命令下拉列表中我必须显示下拉列表而不是想要的标签。

如果你们中的任何人知道如何指定要在update rowcommand中使用的控件,或者以某种方式动态地将该列更改为只读取某些行命令,我将非常感激!

代码示例:

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

代码背后:

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

1 个答案:

答案 0 :(得分:0)

我终于能够使用以下代码解决我的问题:

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