【问题标题】:How can I UPDATE specific GridView columns based on a CheckBox in one column如何根据一列中的 CheckBox 更新特定的 GridView 列
【发布时间】:2017-10-17 16:52:14
【问题描述】:

我的 GridView 有一个“活动”复选框,用于指示记录是否处于活动状态。它只是一个标志,数据库中的一个位值。

当用户选中或取消选中 CheckBox(在编辑模式下)时,我需要更新“ActivatedBy”和“DeactivatedBy”字段。

我目前每次更新一行时都会更新“UpdatedBy”字段,并用@UserName 填充它。

但是,我不知道如何以编程方式更新 ActivatedBy 或 DeactivatedBy 字段,仅当 CheckBox 分别被选中或未选中时。这只是记录谁更改了复选框(@UserName 是工作参数)。

请假设我需要为我详细说明的详细信息。我愿意。 ;-) 我只是在学习 C#,而 GridViews 是我的祸根。谢谢!

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Admin" MaintainScrollPositionOnPostback="true" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title>Admin</title>
    <style>
        body {
            font-family:Arial;
            font-size:12px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="programid" DataSourceID="ITAAdminSqlDataSource" ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:CommandField ShowEditButton="True" ShowSelectButton="True" />
                <asp:BoundField DataField="programid" HeaderText="programid" InsertVisible="False" ReadOnly="True" SortExpression="programid" Visible="False" />
                <asp:BoundField DataField="OccGroup" HeaderText="Occ Group" SortExpression="OccGroup" />
                <asp:BoundField DataField="Provider" HeaderText="Provider" SortExpression="Provider" />
                <asp:BoundField DataField="Program" HeaderText="Program" SortExpression="Program" />
                <asp:BoundField DataField="OnetCode" HeaderText="Onet Code" SortExpression="OnetCode" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:BoundField DataField="Telephone" HeaderText="Telephone" SortExpression="Telephone" >
                <ItemStyle Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="TuitionCosts" DataFormatString="{0:c}" HeaderText="Tuition" HtmlEncode="False" SortExpression="TuitionCosts" />
                <asp:BoundField DataField="OtherCosts" DataFormatString="{0:c}" HeaderText="Other Costs" HtmlEncode="False" SortExpression="OtherCosts" />
                <asp:BoundField DataField="SpecialConditions" HeaderText="Special Conditions" SortExpression="SpecialConditions" />
                <asp:BoundField DataField="Credential" HeaderText="Credential" SortExpression="Credential" />
                <asp:CheckBoxField DataField="Active" HeaderText="Active" SortExpression="Active" />
                <asp:BoundField DataField="DateEntered" DataFormatString="{0:d}" HeaderText="Date Entered" HtmlEncode="False" SortExpression="DateEntered" />
                <asp:BoundField DataField="EnteredBy" HeaderText="Entered By" SortExpression="EnteredBy" />
                <asp:BoundField DataField="DateUpdated" DataFormatString="{0:d}" HeaderText="Date Updated" HtmlEncode="False" SortExpression="DateUpdated" />
                <asp:BoundField DataField="UpdatedBy" HeaderText="Updated By" SortExpression="UpdatedBy" />
                <asp:BoundField DataField="DateActivated" DataFormatString="{0:d}" HeaderText="Date Activated" HtmlEncode="False" SortExpression="DateActivated" />
                <asp:BoundField DataField="ActivatedBy" HeaderText="Activated By" SortExpression="ActivatedBy" />
                <asp:BoundField DataField="DateDeactivated" DataFormatString="{0:d}" HeaderText="Date Deactivated" HtmlEncode="False" SortExpression="DateDeactivated" />
                <asp:BoundField DataField="DeactivatedBy" HeaderText="Deactivated By" SortExpression="DeactivatedBy" />
            </Columns>
            <EditRowStyle BackColor="Tomato" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
        </asp:GridView>
        <asp:SqlDataSource ID="ITAAdminSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ITAAdminConnectionString %>" 
            DeleteCommand="DELETE FROM [programs] WHERE [programid] = @programid" 
            InsertCommand="INSERT INTO [programs] ([OccGroup], [Provider], [Program], [OnetCode], [Address], [City], [Telephone], [TuitionCosts], [OtherCosts], [SpecialConditions], [Credential], [Active], [DateEntered], [EnteredBy], [DateUpdated], [UpdatedBy], [DateActivated], [ActivatedBy], [DateDeactivated], [DeactivatedBy]) VALUES (@OccGroup, @Provider, @Program, @OnetCode, @Address, @City, @Telephone, @TuitionCosts, @OtherCosts, @SpecialConditions, @Credential, @Active, @DateEntered, @EnteredBy, @DateUpdated, @UpdatedBy, @DateActivated, @ActivatedBy, @DateDeactivated, @DeactivatedBy)" 
            SelectCommand="SELECT [programid], [OccGroup], [Provider], [Program], [OnetCode], [Address], [City], [Telephone], [TuitionCosts], [OtherCosts], [SpecialConditions], [Credential], [Active], [DateEntered], [EnteredBy], [DateUpdated], [UpdatedBy], [DateActivated], [ActivatedBy], [DateDeactivated], [DeactivatedBy] FROM [programs] ORDER BY [Provider], [Program]" 
            UpdateCommand="UPDATE [programs] SET [OccGroup] = @OccGroup, [Provider] = @Provider, [Program] = @Program, [OnetCode] = @OnetCode, [Address] = @Address, [City] = @City, [Telephone] = @Telephone, [TuitionCosts] = @TuitionCosts, [OtherCosts] = @OtherCosts, [SpecialConditions] = @SpecialConditions, [Credential] = @Credential, [Active] = @Active, [DateEntered] = @DateEntered, [EnteredBy] = @EnteredBy, [DateUpdated] = GETDATE(), [UpdatedBy] = @UserName, [DateActivated] = @DateActivated, [ActivatedBy] = @ActivatedBy, [DateDeactivated] = @DateDeactivated, [DeactivatedBy] = @DeactivatedBy WHERE [programid] = @programid">
            <DeleteParameters>
                <asp:Parameter Name="programid" Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="OccGroup" Type="String" />
                <asp:Parameter Name="Provider" Type="String" />
                <asp:Parameter Name="Program" Type="String" />
                <asp:Parameter Name="OnetCode" Type="Int32" />
                <asp:Parameter Name="Address" Type="String" />
                <asp:Parameter Name="City" Type="String" />
                <asp:Parameter Name="Telephone" Type="String" />
                <asp:Parameter Name="TuitionCosts" Type="Decimal" />
                <asp:Parameter Name="OtherCosts" Type="Decimal" />
                <asp:Parameter Name="SpecialConditions" Type="String" />
                <asp:Parameter Name="Credential" Type="String" />
                <asp:Parameter Name="Active" Type="Boolean" />
                <asp:Parameter DbType="Date" Name="DateEntered" />
                <asp:Parameter Name="EnteredBy" Type="String" />
                <asp:Parameter DbType="Date" Name="DateUpdated" />
                <asp:Parameter Name="UpdatedBy" Type="String" />
                <asp:Parameter Name="username" Type="String" DefaultValue="Anonymous" /> <%-- username parameter filled in Page_Init. use @username instead of UpdatedBy, ActivatedBy, etc. --%>
                <asp:Parameter DbType="Date" Name="DateActivated" />
                <asp:Parameter Name="ActivatedBy" Type="String" />
                <asp:Parameter DbType="Date" Name="DateDeactivated" />
                <asp:Parameter Name="DeactivatedBy" Type="String" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="OccGroup" Type="String" />
                <asp:Parameter Name="Provider" Type="String" />
                <asp:Parameter Name="Program" Type="String" />
                <asp:Parameter Name="OnetCode" Type="Int32" />
                <asp:Parameter Name="Address" Type="String" />
                <asp:Parameter Name="City" Type="String" />
                <asp:Parameter Name="Telephone" Type="String" />
                <asp:Parameter Name="TuitionCosts" Type="Decimal" />
                <asp:Parameter Name="OtherCosts" Type="Decimal" />
                <asp:Parameter Name="SpecialConditions" Type="String" />
                <asp:Parameter Name="Credential" Type="String" />
                <asp:Parameter Name="Active" Type="Boolean" />
                <asp:Parameter DbType="Date" Name="DateEntered" />
                <asp:Parameter Name="EnteredBy" Type="String" />
                <asp:Parameter DbType="Date" Name="DateUpdated" />
                <asp:Parameter Name="UpdatedBy" Type="String" />
                <asp:Parameter Name="username" Type="String" DefaultValue="Anonymous" /> <%-- username parameter filled in Page_Init. use @username instead of UpdatedBy, ActivatedBy, etc. --%>
                <asp:Parameter DbType="Date" Name="DateActivated" />
                <asp:Parameter Name="ActivatedBy" Type="String" />
                <asp:Parameter DbType="Date" Name="DateDeactivated" />
                <asp:Parameter Name="DeactivatedBy" Type="String" />
                <asp:Parameter Name="programid" Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin : System.Web.UI.Page
{
    protected string ClearDomain(string sItem) //Format username without domain
    {
        int sLoc = (sItem.IndexOf("\\") + 1);
        string sOutPut;
        sOutPut = sItem.Substring(sLoc);
        return sOutPut;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //string usr;
        //usr = ClearDomain(User.Identity.Name.ToString());
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        ITAAdminSqlDataSource.InsertParameters["UserName"].DefaultValue = ClearDomain(User.Identity.Name.ToString());
        ITAAdminSqlDataSource.UpdateParameters["UserName"].DefaultValue = ClearDomain(User.Identity.Name.ToString());
    }
}

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    我会这样做。首先向您的 GridView 添加一个 TemplateField 以保存 CheckBox,并向 CheckBox 添加一个 OnCheckedChanged 事件并将 AutoPostBack 设置为 true。然后在 GridView 中设置DataKeyNames。该值应该是您的数据库索引或标识符。在您的情况下,可能是programid。生成的 GridView 将如下所示。

    <asp:GridView ID="GridView1" runat="server" DataKeyNames="programid">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server"
                        Checked='<%# Convert.ToBoolean(Eval("sold")) %>'
                        OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    

    然后在 CheckBox1_CheckedChanged 方法后面的代码中。

    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        //get the current datagrid item from the sender
        GridViewRow row = (GridViewRow)(((Control)sender).NamingContainer);
    
        //get the correct programid from the datakeys
        int programid = Convert.ToInt32(GridView1.DataKeys[row.DataItemIndex].Values[0]);
    
        //cast the sender back to a checkbox
        CheckBox cb = sender as CheckBox;
    
        //create the sql string
        string sqlString = "UPDATE programs SET ActivatedBy = @ActivatedBy WHERE (programid = @programid)";
    
        //create a connection to the db and a command
        using (SqlConnection connection = new SqlConnection(myConnectionString))
        using (SqlCommand command = new SqlCommand(sqlString, connection))
        {
            //set the proper command type
            command.CommandType = CommandType.Text;
    
            //replace the parameters
            command.Parameters.Add("@ActivatedBy", SqlDbType.Bit).Value = cb.Checked;
            command.Parameters.Add("@programid", SqlDbType.Int).Value = programid;
    
            try
            {
                //open the db and execute the sql string
                connection.Open();
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                //catch any errors like unable to open db or errors in command. view with ex.Message
                Response.Write(ex.Message);
            }
        }
    }
    

    【讨论】:

    • 谢谢你,VDWWD!这很有帮助。除了“ActivatedBy”之外,我还需要记录“DeactivatiedBy”,但我想我可以用你给我的东西找出条件。如果我没有遇到任何问题,我会设置这部分并回来接受您的回答。
    • 哦,我在 FormView 中完成了所有编辑和插入操作,但没有在 GridView 中显示 Edit LinkBut​​ton。不过,我认为它完全相同。 ...添加一个 TemplateField 到 FormView...
    • 哦,实际上它比那更容易...... FormView 已经有了它的 EditItemTemplate :-) 嗯,看起来后面的代码需要一些重大更改。 ...正在努力...
    • 抱歉切换到FormView问题;我没有意识到我必须从那个角度来研究它。我正在学习...
    • 没问题。代码几乎相同。唯一的区别是如何获得正确的programid,因为您不能使用我的 sn-p 的前两行。但也许 formview 也使用 DataKeys(我从不使用 formviews)
    【解决方案2】:
    I need a Status column in database which contains 1,0 for representing Employee's Status "Active" and "Inactive" respectively. I want edit this record through front-end,having grid-view, and want to perform on GridView's update event, after clicking on Edit Button. I have a TemplateField having header-text "Status". I am unable to update changed value of checkbox.
    
    Moreover, if will get checked or unchecked CheckBox on the basis of value stored in database, if it is 0 then CheckBox will be uncheked, otherwise will be checked. If user click on edit button, and then check or uncheck any Check-box, then on the basis of this, value should be updated in database.
    
    DataBase:-
    
    CREATE TABLE [dbo].[Employee](
        [Employee_ID] [int] IDENTITY(1,1) NOT NULL,
        [Employee_Name] [varchar](50) NULL,
        [Employee_Address] [varchar](100) NULL,
        [Emp_Status] [int] NULL,
    PRIMARY KEY CLUSTERED 
    (
        [Employee_ID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON
    
    Front-End:-
    
    Mark-up:
    
            <asp:GridView ID="GV_Product" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" AutoGenerateColumns="false" ShowFooter="true" OnRowEditing="GV_Product_RowEditing" OnRowUpdating="GV_Product_RowUpdating" OnRowDeleting="GV_Product_RowDeleting" OnRowCancelingEdit="GV_Product_RowCancelingEdit" OnRowCommand="GV_Product_RowCommand" AllowPaging="true" PageSize="5" OnPageIndexChanging="GV_Product_PageIndexChanging">
                                <AlternatingRowStyle BackColor="Gainsboro" />
    
                                <Columns>
                                    <asp:TemplateField HeaderText="Employee ID">
                                        <ItemTemplate>
                                            <asp:Label ID="lbl_ID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Employee_ID") %>'></asp:Label>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Employee Name">
                                      <ItemTemplate>
                                          <asp:TextBox ID="txt_Name" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Employee_Name") %>'></asp:TextBox>
                                      </ItemTemplate>
    
                                        <EditItemTemplate>
                                            <asp:TextBox ID="txtEdit_Name" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Employee_Name") %>'></asp:TextBox>
                                        </EditItemTemplate>
    
                                        <FooterTemplate>
                                            <asp:TextBox ID="txtAdd_Name" runat="server"></asp:TextBox>
                                            <%--<asp:RequiredFieldValidator ID="txtName" runat="server" ControlToValidate="txtAdd_Name" ErrorMessage="Please enter Employee Name"></asp:RequiredFieldValidator>--%>
                                        </FooterTemplate>
    
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Employee Address">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txt_Address" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Employee_Address") %>'></asp:TextBox>
                                        </ItemTemplate>
    
                                        <EditItemTemplate>
                                            <asp:TextBox ID="txtEdit_Address" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Employee_Address") %>'></asp:TextBox>
                                        </EditItemTemplate>
    
                                        <FooterTemplate>
                                            <asp:TextBox ID="txtAdd_Address" runat="server"></asp:TextBox>
                                        </FooterTemplate>
                                    </asp:TemplateField>
    
                                    <asp:TemplateField HeaderText="Action">
                                        <ItemTemplate>
                                            <asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" />
                                            <asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
    
                                        </ItemTemplate> 
    
                                        <EditItemTemplate>
                                            <asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName="Update" />
                                            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" />
                                        </EditItemTemplate>
    
                                        <FooterTemplate>
                                            <asp:LinkButton ID="lblAdd" runat="server" Width="100px" Text="Add" CommandName="ADD"></asp:LinkButton>
                                        </FooterTemplate>
                                    </asp:TemplateField>
    
                                    <asp:TemplateField HeaderText="Status">
                                        <ItemTemplate>
                                            <asp:CheckBox ID="ChkBox" runat="server" Checked='<%# GetStatus(DataBinder.Eval(Container.DataItem,"Emp_Status").ToString() )%>' />
                                        </ItemTemplate>
    
                                        <EditItemTemplate>
                                            <asp:CheckBox ID="EditChkBox" runat="server" Checked='<%# GetStatus(DataBinder.Eval(Container.DataItem,"Emp_Status").ToString() )%>'/>
                                            <%--<asp:CheckBoxList ID="ChkBoxList" runat="server">
                                                <asp:ListItem>1</asp:ListItem>
                                            </asp:CheckBoxList>--%>
                                        </EditItemTemplate>
                                    </asp:TemplateField>
    
    
                                </Columns>
    
    
         <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                            <SortedAscendingCellStyle BackColor="#F1F1F1" />
                            <SortedAscendingHeaderStyle BackColor="#0000A9" />
                            <SortedDescendingCellStyle BackColor="#CAC9C9" />
                            <SortedDescendingHeaderStyle BackColor="#000065" />
                        </asp:GridView>
    
    Code:
    
    protected bool GetStatus(string str)
        {
            if (str=="1")
            {
                return true;
            }
    
            else
            {
                return false;
            }
        }
    
    I am getting Error:- 
    
    An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多