title: vb.net SQL query works in SQL server but not when called from checkbox
body: <p>I've got a datagrid with checkboxes which calls a routine called checkbox_CheckedChanged. So far, so good. I've managed to get it to work out the value of another column in the dataview, which allows me to ascertain the id of the row I'm dealing with.</p>
  
  <p>I'm trying to get it to change the value of the column which defines the initial value of the checkboxes, but the SQL I've written doesn't work when called by vb.net - it does work when entered manually into SQL server, however.</p>
  
  <p>Here's my code behind:</p>
  
  <pre><code>Public Sub checkbox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) 'Handles checkbox.CheckedChanged
      Dim connectionString As String = WebConfigurationManager.ConnectionStrings("edinsec").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 msgId As Integer = unreadMessages.Rows(dgRow.DataItemIndex).Cells(0).Text
  
      Dim insertSQL As String
  
      If box.Checked = True Then
    insertSQL = "UPDATE messages"
    insertSQL &amp;= "SET readit = 0"
    insertSQL &amp;= "WHERE msgid = @msgId"
      Else
    insertSQL = "UPDATE messages"
    insertSQL &amp;= "SET readit = 1"
    insertSQL &amp;= "WHERE msgid = @msgId"
      End If
  
      Using con As New SqlConnection(connectionString)
    Dim cmd As New SqlCommand(insertSQL, con)
    cmd.Parameters.AddWithValue("@msgId", msgId)
    Try
        con.Open()
        cmd.ExecuteNonQuery()
    Catch Err As SqlException
        MsgBox("Error", 65584, "Insertion Error")
    End Try
    con.Close()
      End Using
  
  End Sub
  </code></pre>
  
  <p>The idea is that when clicked, the checkbox will flip the 'readit' value in the database to its opposite. It keeps jumping to the SqlException however, so I'm seeing the error message.</p>
  
  <p>The aspx code for the checkboxes is this:</p>
  
  <pre><code>          &lt;asp:TemplateField HeaderText="readit" SortExpression="readit"&gt;
      &lt;ItemTemplate&gt;
          &lt;asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="checkbox_CheckedChanged" Checked='&lt;%# Bind("readit") %&gt;' 
              Enabled="true" /&gt;
      &lt;/ItemTemplate&gt;
      &lt;EditItemTemplate&gt;
          &lt;asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="checkbox_CheckedChanged" Checked='&lt;%# Bind("readit") %&gt;' /&gt;
      &lt;/EditItemTemplate&gt;
        &lt;/asp:TemplateField&gt;
  </code></pre>
  
  <p>Any help would be much appreciated. Visual Studio (2008) gives <em>zero</em> feedback on SQL errors in this situation, which is pretty infuriating.</p>