复选框的值为0和-1?

时间:2013-03-13 13:26:54

标签: asp.net vb.net .net-1.1 asp.net-1.1

我的webapp上有一些复选框,还有一个保存按钮。当我单击“保存”按钮时,我将复选框的checked状态保存到数据库中。

如果未选中复选框,我会在数据库中获得0。但是,如果它们是checked,我会在数据库中获得-1。我期待着1。被检查状态的-1是正常的吗?

示例代码:

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

电话:

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

3 个答案:

答案 0 :(得分:3)

很多将取决于其间的代码,但布尔值true通常表示为整数值-1。这一切都取决于您在持久化之前如何处理该值。如果您需要进一步的帮助,有些代码会很有用。


编辑:添加的代码显示您依赖于从布尔到整数的隐式转换,从而产生此-1值。在VB中,根据版本,您可以使用Iif(checkbox1.Checked, 1, 0)If(checkbox1.Checked, 1, 0)。或者,将值保留为布尔值,并保存到适当的基础DBMS数据类型(如果有) - 例如,在SQL Server中,这将是bit数据类型。

答案 1 :(得分:1)

这些在.NET中是真值和假值,但数据库可能以不同方式表示这些值。例如,Access uses -1 as a "true" value.

答案 2 :(得分:0)

我想你需要使用下面的代码

    Sql = CheckBoolean(Checkbox.checked)
Function CheckBoolean(Value As Boolean)
    If Value Then Return "-1"
    Return "0"
End Function
相关问题