如何在一列中更新基于CheckBox的特定GridView列 [英] How can I UPDATE specific GridView columns based on a CheckBox in one column

查看:81
本文介绍了如何在一列中更新基于CheckBox的特定GridView列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的GridView有一个Active复选框,用于指示记录是否处于活动状态。这只是一个标志,在数据库中有点价值。



当用户选中或取消选中CheckBox时,需要更新ActivatedBy和DeactivatedBy编辑模式)。



我每次更新行时都会更新UpdatedBy字段,并用@UserName填充。 但是,我不知道如何分别编程更新ActivatedBy或DeactivatedBy字段,仅当CheckBox被选中或未选中时。这只是为了记录谁改变了复选框(@ UserName是工作参数)。



请假设我需要为我详细说明的细节。我做。 ;-)我只是在学C#而GridViews是我的祸根。谢谢!

 <%@ Page Language =C#AutoEventWireup =trueCodeFile =Admin.aspx.cs Inherits =AdminMaintainScrollPositionOnPostback =true%> 

<!DOCTYPE html>

< html>
< head runat =server>
< title> Admin< / title>
< style>
body {
font-family:Arial;
font-size:12px;
}
< / style>
< / head>
< body>
< form id =form1runat =server>
< div>
< AlternatingRowStyle BackColor =White/>
<列>
< asp:CommandField ShowEditButton =TrueShowSelectButton =True/>
< asp:BoundField DataField =programidHeaderText =programidInsertVisible =FalseReadOnly =TrueSortExpression =programidVisible =False/>
< asp:BoundField DataField =OccGroupHeaderText =Occ GroupSortExpression =OccGroup/>
< asp:BoundField DataField =ProviderHeaderText =ProviderSortExpression =Provider/>
< asp:BoundField DataField =ProgramHeaderText =ProgramSortExpression =Program/>
< asp:BoundField DataField =OnetCodeHeaderText =Onet CodeSortExpression =OnetCode/>
< asp:BoundField DataField =AddressHeaderText =AddressSortExpression =Address/>
< asp:BoundField DataField =CityHeaderText =CitySortExpression =City/>
< asp:BoundField DataField =TelephoneHeaderText =TelephoneSortExpression =Telephone>
< ItemStyle Wrap =False/>
< / asp:BoundField>
< asp:BoundField DataField =TuitionCostsDataFormatString ={0:c}HeaderText =TuitionHtmlEncode =FalseSortExpression =TuitionCosts/>
< asp:BoundField DataField =OtherCostsDataFormatString ={0:c}HeaderText =其他费用HtmlEncode =FalseSortExpression =OtherCosts/>
< asp:BoundField DataField =SpecialConditionsHeaderText =特殊条件SortExpression =SpecialConditions/>
< asp:BoundField DataField =CredentialHeaderText =CredentialSortExpression =Credential/>
< asp:CheckBoxField DataField =ActiveHeaderText =ActiveSortExpression =Active/>
< asp:BoundField DataField =DateEnteredDataFormatString ={0:d}HeaderText =输入日期HtmlEncode =FalseSortExpression =DateEntered/>
< asp:BoundField DataField =EnteredByHeaderText =Entered BySortExpression =EnteredBy/>
< asp:BoundField DataField =DateUpdatedDataFormatString ={0:d}HeaderText =更新日期HtmlEncode =FalseSortExpression =DateUpdated/>
< asp:BoundField DataField =UpdatedByHeaderText =Updated BySortExpression =UpdatedBy/>
< asp:BoundField DataField =DateActivatedDataFormatString ={0:d}HeaderText =日期激活HtmlEncode =FalseSortExpression =DateActivated/>
< asp:BoundField DataField =ActivatedByHeaderText =Activated BySortExpression =ActivatedBy/>
< asp:BoundField DataField =DateDeactivatedDataFormatString ={0:d}HeaderText =Date DeactivatedHtmlEncode =FalseSortExpression =DateDeactivated/>
< asp:BoundField DataField =DeactivatedByHeaderText =Deactivated BySortExpression =DeactivatedBy/>
< /列>
< EditRowStyle BackColor =Tomato/>
< FooterStyle BackColor =#507CD1Font-Bold =TrueForeColor =White/>
< HeaderStyle BackColor =#507CD1Font-Bold =TrueForeColor =White/>
< RowStyle BackColor =#EFF3FB/>
< SelectedRowStyle BackColor =#D1DDF1Font-Bold =TrueForeColor =#333333/>
< SortedAscendingCellStyle BackColor =#F5F7FB/>
< SortedAscendingHeaderStyle BackColor =#6D95E1/>
< SortedDescendingCellStyle BackColor =#E9EBEF/>
< SortedDescendingHeaderStyle BackColor =#4870BE/>
< / asp:GridView>
< asp:SqlDataSource ID =ITAAdminSqlDataSourcerunat =serverConnectionString =<%$ ConnectionStrings:ITAAdminConnectionString%>
DeleteCommand =DELETE FROM [programs] WHERE [programid] = @programid
InsertCommand =INSERT INTO [程序]([OccGroup],[Provider],[Program],[OnetCode],[地址] [城市] [电话] [学费] [其他费用] [特殊条款] [证件] [活动] [日期输入] [输入日期] [日期更新] [更新日期] [日期激活] ,[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] ],[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,[活动] ,[ActivatedBy] = @ActivatedBy,[DateDeactivated] = @DateDeactivated,[DeactivatedBy] = @DeactivatedBy WHERE [programid] = @programid>
< DeleteParameters>
< asp:Parameter Name =programidType =Int32/>
< / DeleteParameters>
< InsertParameters>
< asp:Parameter Name =OccGroupType =String/>
< asp:Parameter Name =ProviderType =String/>
< asp:Parameter Name =ProgramType =String/>
< asp:Parameter Name =OnetCodeType =Int32/>
< asp:Parameter Name =AddressType =String/>
< asp:Parameter Name =CityType =String/>
< asp:Parameter Name =TelephoneType =String/>
< asp:Parameter Name =TuitionCostsType =Decimal/>
< asp:Parameter Name =OtherCostsType =Decimal/>
< asp:Parameter Name =SpecialConditionsType =String/>
< asp:Parameter Name =CredentialType =String/>
< asp:Parameter Name =ActiveType =Boolean/>
< asp:参数DbType =DateName =DateEntered/>
< asp:Parameter Name =EnteredByType =String/>
< asp:参数DbType =DateName =DateUpdated/>
< asp:Parameter Name =UpdatedByType =String/>
< asp:Parameter Name =usernameType =StringDefaultValue =Anonymous/> <% - 填入Page_Init的用户名参数。使用@username而不是UpdatedBy,ActivatedBy等 - %>
< asp:参数DbType =DateName =DateActivated/>
< asp:Parameter Name =ActivatedByType =String/>
< asp:参数DbType =DateName =DateDeactivated/>
< asp:Parameter Name =DeactivatedByType =String/>
< / InsertParameters>
< UpdateParameters>
< asp:Parameter Name =OccGroupType =String/>
< asp:Parameter Name =ProviderType =String/>
< asp:Parameter Name =ProgramType =String/>
< asp:Parameter Name =OnetCodeType =Int32/>
< asp:Parameter Name =AddressType =String/>
< asp:Parameter Name =CityType =String/>
< asp:Parameter Name =TelephoneType =String/>
< asp:Parameter Name =TuitionCostsType =Decimal/>
< asp:Parameter Name =OtherCostsType =Decimal/>
< asp:Parameter Name =SpecialConditionsType =String/>
< asp:Parameter Name =CredentialType =String/>
< asp:Parameter Name =ActiveType =Boolean/>
< asp:参数DbType =DateName =DateEntered/>
< asp:Parameter Name =EnteredByType =String/>
< asp:参数DbType =DateName =DateUpdated/>
< asp:Parameter Name =UpdatedByType =String/>
< asp:Parameter Name =usernameType =StringDefaultValue =Anonymous/> <% - 填入Page_Init的用户名参数。使用@username而不是UpdatedBy,ActivatedBy等 - %>
< asp:参数DbType =DateName =DateActivated/>
< asp:Parameter Name =ActivatedByType =String/>
< asp:参数DbType =DateName =DateDeactivated/>
< asp:Parameter Name =DeactivatedByType =String/>
< asp:Parameter Name =programidType =Int32/>
< / UpdateParameters>
< / asp:SqlDataSource>
< / div>
< / form>
< / body>
< / html>


使用System;
使用System.Collections.Generic;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControls;

public partial class Admin:System.Web.UI.Page
{
保护字符串ClearDomain(字符串sItem)//格式化没有域名的用户名
{
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());


$ / code>


解决方案

是我该怎么做的。首先向你的GridView添加一个 TemplateField 来保存CheckBox,并向CheckBox添加一个 OnCheckedChanged 事件并设置 AutoPostBack 为true。然后在GridView中设置 DataKeyNames 。该值应该是您的数据库索引或标识符。在你的情况下可能 programid

 < asp:GridView ID =GridView1runat =serverDataKeyNames = programid> 
<列>
< asp:TemplateField>
< ItemTemplate>
< asp:CheckBox ID =CheckBox1runat =server
Checked ='<%#Convert.ToBoolean(Eval(sold))%>'
OnCheckedChanged =CheckBox1_CheckedChangedAutoPostBack =true/>
< / ItemTemplate>
< / asp:TemplateField>
< /列>
< / asp:GridView>

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

  protected void CheckBox1_CheckedChanged(object sender,EventArgs e)
{
//获取当前的datagrid项目从发件人
GridViewRow row =(GridViewRow)(((Control)sender).NamingContainer);

//从datakeys中获取正确的programid
int programid = Convert.ToInt32(GridView1.DataKeys [row.DataItemIndex] .Values [0]);

//将发件人转回复选框
复选框cb =发件人为复选框;

//创建sql字符串
字符串sqlString =更新程序SET ActivatedBy = @ActivatedBy WHERE(programid = @programid);

//使用(SqlCommand命令=新建SqlCommand(sqlString,连接))使用(SqlConnection connection = new SqlConnection(myConnectionString))
创建一个到数据库和命令
的连接。 )
{
//设置适当的命令类型
command.CommandType = CommandType.Text;

//替换参数
command.Parameters.Add(@ ActivatedBy,SqlDbType.Bit).Value = cb.Checked;
command.Parameters.Add(@ programid,SqlDbType.Int).Value = programid;

尝试
{
//打开数据库并执行sql字符串
connection.Open();
command.ExecuteNonQuery();
}
catch(Exception ex)
{
//捕获任何错误,如无法在命令中打开数据库或错误。用ex.Message查看
Response.Write(ex.Message);
}
}
}


My GridView has an "Active" CheckBox, to indicate whether the record is active or not. It's just a flag, a bit value in the database.

I need to UPDATE the "ActivatedBy" and "DeactivatedBy" fields when a user checks or unchecks the CheckBox (in edit mode).

I'm currently updating the "UpdatedBy" field every time a row is updated, filling it with @UserName.

But, I don't know how to programatically update either the ActivatedBy or DeactivatedBy fields only when the CheckBox is checked or unchecked respectively. This is just to record who changes the checkbox (@UserName is the working parameter).

Please assume I need the details spelled out for me. I do. ;-) I'm just learning C# and GridViews are my bane. Thank you!

<%@ 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());
    }
}

解决方案

This is how I would do it. First add an TemplateField to your GridView to hold the CheckBox and add a OnCheckedChanged event to the CheckBox and set AutoPostBack to true. Then set the DataKeyNames in the GridView. The value should be your database index or identifier. In your case probably programid. The resulting GridView would look like this.

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

Then in code behind the CheckBox1_CheckedChanged method.

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

这篇关于如何在一列中更新基于CheckBox的特定GridView列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆