Question

I have some checkboxes on my webapp, and a save button. When I click the save button, I save the checked state of the checkboxes to the database.

When the checkboxes are not checked, I get 0's in the database. However, when they are checked, I get -1's in the database. I was expecting 1's. Are the -1's normal for checked states?

Sample code:

Function ProcessAction(ByVal checkbox1 As Integer, ByVal checkbox2 As Integer) As Integer

    connection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))

    command = New SqlCommand("stored_procedure_name_here", connection)
    command.CommandType = CommandType.StoredProcedure

    command.Parameters.Add(New SqlParameter("@id", SqlDbType.Int, 4)).Value = 100
    command.Parameters.Add(New SqlParameter("@checkbox1", SqlDbType.Int, 4)).Value = checkbox1
    command.Parameters.Add(New SqlParameter("@checkbox2", SqlDbType.Int, 4)).Value = checkbox2

    command.Connection.Open()
    command.ExecuteNonQuery()
    command.Connection.Close()

    Return 1
End Function

The call:

Sub ButtonClick(ByVal Source As Object, ByVal E As EventArgs)
    ProcessAction(checkbox1.Checked, checkbox2.Checked)
End Sub
Was it helpful?

Solution

A lot will depend on the code in between, but a Boolean true value is conventionally represented as the integer value -1. It all depends on how you are handling the value before it gets persisted. Some code would be useful if you need further help.


EDIT: The code added shows you are relying on an implicit cast from Boolean to integer, resulting in this -1 value. In VB, depending on the version, you could use Iif(checkbox1.Checked, 1, 0) or If(checkbox1.Checked, 1, 0). Alternatively, keep the value as a Boolean, and save to the appropriate underlying DBMS data type if there is one - for example, in SQL Server, this would be a bit data type.

OTHER TIPS

These would be true and false values in .NET, but the database may represent those values differently. For instance, Access uses -1 as a "true" value.

I think u need to use code like below

    Sql = CheckBoolean(Checkbox.checked)
Function CheckBoolean(Value As Boolean)
    If Value Then Return "-1"
    Return "0"
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top