有关于checklistbox的问题

时间:2014-02-28 08:49:08

标签: c# sql-server winforms

我有一个checkedListBox和一个TextBox ...当我在checkedListBox中检查项目时,它显示了TextBox中相应项目的值...当我在checkedListBox中检查多个项目时,它显示了各个项目的值在TextBox中分隔{,}“逗号”

现在我的问题是,当我取消选中textBox中的项目时,它必须从textBox中删除相应未检查项目的值...还请告诉我如何从结尾处删除“逗号”{,}文本框以编程方式

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
        SqlCommand command = new SqlCommand("Select * FROM address_book ", connection);

        try
        {
            connection.Open();
            {
                SqlDataReader drd = command.ExecuteReader();

                while (drd.Read())
                {
                    this.checkedListBox1.Items.Add(drd.GetString(0).ToString());
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }

        connection.Close();
    }

    private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from address_book where name='" + checkedListBox1.Text + "'", con);
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            textBox1.Text += Convert.ToString(dr["id"] + ",");
        }
        dr.Close();
    }

    private void textBox1_Enter(object sender, EventArgs e)
    {
        ToolTip tt = new ToolTip();
        tt.SetToolTip(textBox1, "sorry");
    }
}

2 个答案:

答案 0 :(得分:0)

要删除,

textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);

但我最好将我的dr [“id”]保留在List中并创建一个小函数,它遍历列表并返回逗号分隔的字符串。添加和删​​除项目应该在该集合中进行。

答案 1 :(得分:0)

首先,如果您想要显示"已选中"则不应使用SelectedIndexChanged事件。项目。请改用ItemCheck

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)

然后使用CheckedListBox.CheckedItems来检索所有已检查的项目:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    StringBuilder stringBuilder = new StringBuilder();

    foreach (var item in checkedListBox1.CheckedItems)
    {
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand(string.Format("select * from address_book where name='{0}'", item), con);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            stringBuilder.Append(Convert.ToString(dr["id"] + ","));
        }
        dr.Close();
    }

    textBox1.Text = stringBuilder.ToString().TrimEnd(',');
}

请记住使用string.TrimEnd()修剪最后一个逗号。

嗯,这不是最有效的方法,因为当其中一个项目发生变化时,您需要检查每个检查项目。您可以使用Dictionary来维护名称ID对 - 至少在取消选中项目时不需要执行SQL查询,对吧? :)