用資料庫儲存複選框狀態(使用int值)
阿新 • • 發佈:2019-02-08
前日遇到了把複選框儲存至資料庫的問題,當時用的方法極其的“醜陋”,現更正。用一個TextBox來暫存數值,權當是對資料庫的讀寫。
按鈕Get事件如下:
//通過複選框當前狀態取得相應數值protectedvoid bnGetCheckBox_Click(object sender, EventArgs e)
{
int result =0;
for (int counter =0; counter < cbl.Items.Count; counter++)
{
//如果counter項為選中狀態,則將result相應位置為1
if (cbl.Items[counter].Selected ==true)
{
int temp =1;
temp = temp << counter;
result = result | temp;
}
}
tbResult.Text = result.ToString();
}
按鈕Set事件如下:
//通過數值設定複選框狀態protectedvoid bnSetCheckBox_Click(object
{
//取值
int input;
if (!Int32.TryParse(tbResult.Text, out input))
input =0;
//設定
for (int counter =0; counter < cbl.Items.Count; counter++)
{
//將1左移counter位,用於檢查
int temp =1;
temp = temp << counter;
//如果給定數值中第counter位值為1,則將相應CheckBox設為選中
if ((temp & input) == temp)
cbl.Items[counter].Selected =true;
}
}