VB.net - 使Gridview复选框字段更新数据库中的boolean字段

时间:2011-02-07 22:14:29

标签: sql vb.net gridview checkbox boolean

关于此问题有很多问题,但是我无法使用其中任何一个的答案来解决我的问题(经过多次尝试......)

我正在vb.net中创建一个asp.net Web应用程序。我的页面上有一个SqlDataSource和一个GridView。

我想更改由Gridview复选框表示的DoNotMail布尔值,并在数据库中自动更新,如果复选框从0(False,Will Mail)检查到1(True,Will not Mail)这里是代码I用过的。

对于我添加的default.aspx.vb代码:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    lastname.Focus()
    If Page.IsPostBack Then
        Response.Write("The DoNotMail value has been changed in the database for the selected field")
    End If

End Sub

Public Sub checkbox1_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
    With Me.SqlDataSource1
        Dim box As CheckBox = DirectCast(sender, CheckBox)
        If box.Checked = True Then
            donotmail.SelectedValue = 1

            .ConnectionString = ConfigurationManager.AppSettings("AgentLeadsConnectionString").ToString
            .UpdateCommand = "UPDATE MktDataLeads_scrubbed set donotmail=@donotmail"
        Else
            donotmail.SelectedValue = 0

            .ConnectionString = ConfigurationManager.AppSettings("AgentLeadsConnectionString").ToString
            .UpdateCommand = "UPDATE MktDataLeads_scrubbed set donotmail=@donotmail"
        End If
    End With

End Sub

对于default.aspx页面,我添加了:

                 <asp:TemplateField HeaderText="DoNotMail" SortExpression="DoNotMail">     
                 <ItemTemplate>         
                 <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="checkbox1_CheckedChanged" Checked='<%# Bind("DoNotMail") %>'
                               Enabled="true" />     
                 </ItemTemplate>     
                 <EditItemTemplate>         
                 <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="checkbox1_CheckedChanged" Checked='<%# Bind("DoNotMail") %>' />     
                 </EditItemTemplate>       
                 </asp:TemplateField> 

1)我很确定我在更新命令上的语法在默认的代码隐藏部分中是不正确的。有谁知道正确的语法?
2)我得到错误:当我在代码隐藏部分下添加“Handles CheckBox1.CheckedChanged”时,CheckBox1带有下划线并出现以下错误:“Handles子句需要在包含类型或其基本类型之一中定义的WithEvents变量” 。我怎么摆脱它?我刚刚删除了该行并在没有它的情况下运行了代码。 3)单击复选框后,“所选字段的数据库中的DoNotMail值已更改”文本显示在页面顶部但如果我重新运行搜索donotmail = 1,则记录不显示因为新的价值永远不会更新。

我很难过。有人可以帮忙吗?非常感谢:)

感谢响应尼克! UPDATE语句不起作用b / c它没有WHERE子句。它将按原样更新整个表。该表没有主键。表格FROM [AgentLeads]。[dbo]。[MktDtaLeads_Scrubbed] - [姓氏],[名字],[中间名],[后缀],[地址第1行],[地址第2行] ,[City],[ST],[ZipCode],[Email Address],[Phone Nbr],[Toll Free Nbr],[InsertDate],[SentDate],[DoNotMail]

其中AgentLeads是数据库,MktDtaLeads_Scrubbed是表。如何指定行?我会这样说:

.UpdateCommand =“UPDATE MktDataLeads_scrubbed set donotmail = @ donotmail”WHERE [last name] = @ lastname.selectedrow AND [first name] = @ firstname.selectedrow AND [Address Line 1] = @ Address Line 1.selectedrow

当用户点击按钮时,是否可以在整个gridview上进行双向同步,这样每次更改行时都不必进行更新?因为用户可能会选中该框,然后选中另一个框,然后取消选中一个框,这将是很多更新......

3 个答案:

答案 0 :(得分:1)

您需要使用GridView.RowCommand event

确保将OnRowCommand侦听器添加到GridView,然后相应地更新

Public Sub gridview1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
     If e.CommandName = "UpdateDoNotMail" Then
        With Me.SqlDataSource1
           Dim box As CheckBox = DirectCast(sender, CheckBox)
           If box.Checked = True Then
               donotmail.SelectedValue = 1

               .ConnectionString = ConfigurationManager.AppSettings("AgentLeadsConnectionString").ToString
               .UpdateCommand = "UPDATE MktDataLeads_scrubbed set donotmail=@donotmail"
           Else
               donotmail.SelectedValue = 0

               .ConnectionString = ConfigurationManager.AppSettings("AgentLeadsConnectionString").ToString
               .UpdateCommand = "UPDATE MktDataLeads_scrubbed set donotmail=@donotmail"
           End If
       End With
    End If
End Sub

和TemplateField

             <asp:TemplateField HeaderText="DoNotMail" SortExpression="DoNotMail">     
             <ItemTemplate>         
             <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" CommandName="UpdateDoNotMail" Checked='<%# Bind("DoNotMail") %>'
                           Enabled="true" />     
             </ItemTemplate>     
             <EditItemTemplate>         
             <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" CommandName="UpdateDoNotMail" Checked='<%# Bind("DoNotMail") %>' />     
             </EditItemTemplate>       
             </asp:TemplateField> 

答案 1 :(得分:0)

以下是default.aspx上的GridView代码:

我使用了本页详细介绍的代码变体,并将其运行起来! vb.net SQL query works in SQL server but not when called from checkbox

对于我添加的default.aspx.vb代码:

    Public Sub checkbox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) 'Handles checkbox.CheckedChanged
    Dim connectionString As String = ConfigurationManager.ConnectionStrings("AgentLeadsConnectionString").ConnectionString


    Dim box As CheckBox = DirectCast(sender, CheckBox)
    Dim tblcell As TableCell = CType(box.Parent, TableCell)
    Dim dgRow As GridViewRow = CType(tblcell.Parent, GridViewRow)

    Dim lastname As String = [last name].Rows(dgRow.DataItemIndex).Cells(0).Text
    Dim firstname As String = [first name].Rows(dgRow.DataItemIndex).Cells(0).Text
    Dim address As String = [Address Line1].Rows(dgRow.DataItemIndex).Cells(0).Text

    Dim insertSQL As String

    If box.Checked = True Then
        insertSQL = "UPDATE MktDataLeads_scrubbed "
        insertSQL &= "SET donotmail=1 "
        insertSQL &= "WHERE [last name]= @lastname AND [first name]=@firstname AND [Address Line1]=@address "
    Else
        insertSQL = "UPDATE MktDataLeads_scrubbed "
        insertSQL &= "SET donotmail=0 "
        insertSQL &= "WHERE [last name]= @lastname AND [first name]=@firstname AND [Address Line1]=@address "
    End If

    Using con As New SqlConnection(connectionString)
        Dim cmd As New SqlCommand(insertSQL, con)
        cmd.Parameters.AddWithValue("@donotmail", donotmail)
        Try
            con.Open()
            cmd.ExecuteNonQuery()
        Catch Err As SqlException
            MsgBox("Error", 65584, "Insertion Error")
        End Try
        con.Close()
    End Using

End Sub

对于gridview,我使用了相同的代码:

             <asp:TemplateField HeaderText="DoNotMail" SortExpression="DoNotMail">     
             <ItemTemplate>         
             <asp:CheckBox ID="CheckBox" runat="server" AutoPostBack="true" OnCheckedChanged="checkbox_CheckedChanged" Checked='<%# Bind("DoNotMail") %>'
                           Enabled="true" />     
             </ItemTemplate>     
             <EditItemTemplate>         
             <asp:CheckBox ID="CheckBox" runat="server" AutoPostBack="true" OnCheckedChanged="checkbox_CheckedChanged" Checked='<%# Bind("DoNotMail") %>' />     
             </EditItemTemplate>       
             </asp:TemplateField>

答案 2 :(得分:0)

我最终获得了通过ID名称向数据库添加主键列的权限,以便更轻松地调用每个记录,并通过从db(更快)调用存储过程而不是运行SQL命令来优化代码守则背后(较慢)。

对于default.aspx.vb,我把:

Public Sub checkbox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) 'Handles checkbox.CheckedChanged 
    With Me.SqlDataSource1
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("AgentLeadsConnectionString").ConnectionString


        .UpdateParameters.Clear()

        .ConnectionString = ConfigurationManager.AppSettings("AgentLeadsConnectionString").ToString
        .UpdateCommand = "up_UpdateMktDataLeads"
        .UpdateParameters.Add("donotmail", Me.donotmail.Text)
        .UpdateCommandType = SqlDataSourceCommandType.StoredProcedure

    End With

    GridView2.DataBind()

End Sub

这是后面代码的存储过程:

     PROCEDURE [dbo].[up_UpdateMktLeadsDoNotMail]

           @ID integer, 
           @DoNotMail bit

     AS

     UPDATE [dbo].[MktDtaLeads_Scrubbed]

     SET [DoNotMail] = @DoNotMail

     WHERE [ID] = @ID

这是default.aspx上GridView的前端编码:

        <asp:GridView ID="GridView2" runat="server" CellPadding="2" 
            DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" 
            AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="Last Name" HeaderText="Last Name" 
                    SortExpression="Last Name" />
                <asp:BoundField DataField="First Name" HeaderText="First Name" 
                    SortExpression="First Name" />
                <asp:BoundField DataField="Address Line 1" HeaderText="Addr 1" 
                    SortExpression="Address Line 1" />
                <asp:BoundField DataField="Address Line 2" HeaderText="Addr 2" 
                    SortExpression="Address Line 2" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:BoundField DataField="ST" HeaderText="ST" SortExpression="ST" />
                <asp:BoundField DataField="ZipCode" HeaderText="ZipCode" 
                    SortExpression="ZipCode" />
                <asp:BoundField DataField="Email Address" HeaderText="Email Addr" 
                    SortExpression="Email Address" />
                <asp:BoundField DataField="Phone Nbr" HeaderText="Phone Nbr" 
                    SortExpression="Phone Nbr" />

             <asp:TemplateField HeaderText="DoNotMail" SortExpression="DoNotMail">     
             <ItemTemplate>         
             <asp:CheckBox ID="CheckBox" runat="server" AutoPostBack="true" OnCheckedChanged="checkbox_CheckedChanged" Checked='<%# Bind("DoNotMail") %>'
                           Enabled="true" />     
             </ItemTemplate>     
             <EditItemTemplate>         
             <asp:CheckBox ID="CheckBox" runat="server" AutoPostBack="true" OnCheckedChanged="checkbox_CheckedChanged" Checked='<%# Bind("DoNotMail") %>' />     
             </EditItemTemplate>       
             </asp:TemplateField>

            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" Font-Size="Smaller" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>