c# checklistbox的用法

发布时间:2009年08月14日      浏览次数:1222 次
1、添加项:
checkedListBox1.Items.Add("蓝色");
checkedListBox1.Items.Add("红色");
checkedListBox1.Items.Add("黄色");
2、判断第0项是否选中
if (checkedListBox1.GetItemChecked(0))
3、设置第0项是否选中
checkedListBox1.SetItemChecked(0, true);
4、设置全选
添加一名为select_all的checkbox控件
private void select_all_CheckedChanged(object sender, EventArgs e)
{
if(select_all.Checked)
for (int j = 0; j < checkedListBox1.Items.Count; j++)
checkedListBox1.SetItemChecked(j, true);
else
for (int j =0; j < checkedListBox1.Items.Count; j++)
checkedListBox1.SetItemChecked(j, false);
}
5、得到全部选中的值:
private void linkLabel_yes_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
panel_friend.Visible = false;
button_friend.Text = "好友面板";
sms_str = null;
for (int j = 0; j < checkedListBox1.Items.Count; j++)
if(checkedListBox1.GetItemChecked(j))
{
//do
}
}

6、数据绑定
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack) //这句很重要,如果不加,则每次加载时都要执行一次绑定,易丢失数据.
{
//创建链接;
SqlConnection con = DB.createConnection(); //不再用 new
con.Open();
SqlCommand cmd = new SqlCommand("select * from [personlike]",con);
SqlDataReader sdr = cmd.ExecuteReader();
this.CheckBoxList1.DataTextField = "likeContent";
this.CheckBoxList1.DataValueField = "ID";
this.CheckBoxList1.DataSource = sdr;
this.CheckBoxList1.DataBind();
sdr.Close(); //关闭记录集
con.Close(); //关闭链接
}
}
//单击按钮读取所做的操作(数据),用Response.Write()方法显示.
protected void Button1_Click(object sender, EventArgs e)
{
for(int i=0;i<=this.CheckBoxList1.Items.Count-1;i++)
{
if(this.CheckBoxList1.Items[i].Selected)
{
Response.Write(this.CheckBoxList1.Items[i].Value.ToString() +"-"+this.CheckBoxList1.Items[i].Text + "<br>");
}
}
}
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!