views:

934

answers:

2

i have 50 checkboxes for 50 american states. The user can choose all 50 or only 1( so basically any number he wants). Based on his choice, I want to insert or update the table in sql server 2008. e.g-

Color = blue and chk1=check, chk2= check and chk3 = check (chk = checkbox). now the user wants to ad 10 more states to this or remove these 3 and add 5 more. so u basically get the idea. the table in database looks like this - ID Color State_id there is a table called states, so stateid shall come from there. so how do i do a loop insert or update in vb.net?

A: 

I would use bitwise operation and a long variable in .net (mixed with an enum for the flag)

one field in the db and way easier to play with what the user select

small sample

Enum state As Long '64 enum maxium since long = 64 bits

ALABAMA = 1
ALASKA = 2
NEVADA = 4
ARIZONA = 8
ARKANSAS = 16
CALIFORNIA = 32
COLORADO = 64
CONNECTICUT = 128
DELAWARE = 256
'etc etc etc

End Enum

Module Module1

Sub Main()
    Dim userselect As state = 0

    Console.WriteLine("your checked box state")
    Console.WriteLine("in this case im using the order of the enum for selecting")
    Dim checkbox = New Boolean() {True, False, False, True, False, False, True, False, False}

    For i = 0 To checkbox.Length - 1
        userselect = CType(userselect + If(checkbox(i), (2 ^ (i + 1)), 0), state)
    Next

    For Each s As state In [Enum].GetValues(GetType(state))
        If (userselect And s) > 0 Then
            Console.WriteLine("selected " & s.ToString)
        End If
    Next

    Console.WriteLine("Value of userselect is " & userselect.ToString)

    Console.ReadKey()

End Sub

End Module

OUTPUT:

selected NEVADA
selected ARIZONA
selected COLORADO
Value of userselect is 76
Fredou
could u explain more or give a link i could read with an example?
reger
give me a few minutes to create a small example
Fredou
A: 

I would use a data source and a checkboxlist. You already have your states in a datatable, populate a checkboxlist with a databound selection from a SqlDataSource (or datatable of your own choosing). Then when you click your button just iterate through the following loop:

Dim dt as New myTypedDataTable  ' constructed from datasource

Dim color as String = "Blue"    ' Filled however you set color

For Each item As ListItem In Me.CheckBoxList1.Items
    If item.Selected Then
        Dim row as myTypedDataTableRow = dt.NewmyTypedDataTableRow
        row.Color = color
        row.State_id = item.Value
        dt.Rows.Add(row)
    End If
Next

Once you've got the datatable filled with the rows in question you could either use the SqlDataSource to perform an insert operation or perform the insert operation atomically. There are several ways to accomplish it, but this is probably the simplest way to iterate through the items given the data structure you described.

Joel Etherton