0

I have 1 table named CivilStatus

CivilStatus has these columns, all with bit data type:

  • Single (bit)
  • Married (bit)
  • Widow (bit)
  • Separated (bit)
  • Live-in (bit)

Now, I created a project in VB.NET with a CheckedListBox in it named clbCivilStatus. Inside the CheckedListBox items property are the collection I listed above. This is the code I made to put values in my table using a stored procedure:

Dim single as Boolean
Dim married as Boolean
Dim widow as Boolean
Dim separated as Boolean
Dim livein as Boolean

single = IIf(clbCivilStatus.SelectedItem(0), 1, 0)
married = IIf(clbCivilStatus.SelectedItem(1), 1, 0)
widow = IIf(clbCivilStatus.SelectedItem(2), 1, 0)
separated = IIf(clbCivilStatus.SelectedItem(3), 1, 0)
livein = IIf(clbCivilStatus.SelectedItem(4), 1, 0)

 Dim strConn As String = "my sql connection"
            Dim sqlCon As SqlConnection

            sqlCon = New SqlConnection(strConn)

            Using (sqlCon)

                Dim sqlComm As New SqlCommand

                sqlComm.Connection = sqlCon

                sqlComm.CommandText = "Insert"
                sqlComm.CommandType = CommandType.StoredProcedure

sqlComm.Parameters.AddWithValue("Single", single)
sqlComm.Parameters.AddWithValue("Married", married)
sqlComm.Parameters.AddWithValue("Widow", widow)
sqlComm.Parameters.AddWithValue("Separated", separated)
sqlComm.Parameters.AddWithValue("LiveIn", livein)

   sqlComm.ExecuteNonQuery()

    End Using

...but visual studio gives me this error:

InvalidCastException was unhandled

Conversion from type 'Char' to type 'Boolean' is not valid.

I want Boolean values in my database, is there a way to do this using a CheckedListBox?

4

1 回答 1

0

您的代码正在使用 property SelectedItem(x),但这是对SelectedItem列表中唯一一个元素的字符串中的第 x 个字符的引用。
它不是与列表中的 x 项关联的复选框的值。

要获取复选框的值,您需要使用GetItemCheckState并将其与枚举 CheckState.Checked 进行比较

single = IIf(clbCivilStatus.GetItemCheckState(0) = CheckState.Checked, 1, 0)
married = IIf(clbCivilStatus.GetItemCheckState(1) = CheckState.Checked, 1, 0)
widow = IIf(clbCivilStatus.GetItemCheckState(2) = CheckState.Checked, 1, 0)
separated = IIf(clbCivilStatus.GetItemCheckState(3) = CheckState.Checked, 1, 0)
livein = IIf(clbCivilStatus.GetItemCheckState(4) = CheckState.Checked, 1, 0)
于 2014-10-20T09:40:40.430 回答