在列表框中选择项目

时间:2013-05-14 14:08:34

标签: c#-4.0 listboxitem

我有两个列表框,它们的相应数据存储在SQL Server中。我能够从SQL Server加载ListBox1的数据。但是我无法从ListBox 1中将所选项目的相应数据填充到ListBox 2.但是当我单击Listbox 1中的项目时,Listbox2中不会显示任何数据。

private void Form2_Load(object sender, EventArgs e)
        {
            SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cs;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT memo FROM new";
        DataSet objDS = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;

       // cs.Open();
        da.Fill(objDS);

        //cs.Close();

        listMemo.ValueMember = "memo";
        listMemo.DisplayMember = "memo";
        listMemo.DataSource = objDS.Tables[0];

    }


    private void listMemo_SelectedIndexChanged(object sender, EventArgs e)
    {
       // string memo = Convert.ToInt32(listMemo.SelectedValue.ToString());
        if (listMemo.SelectedValue.ToString() != "")
        {
            string memo = Convert.ToString(listMemo.SelectedValue.ToString());
            filltext(memo);
        }


    }


    private void filltext(string memo)
    {
        SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd");
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cs;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT text FROM new WHERE memo = '"+ listMemo.SelectedValue.ToString()  +"'" ;
        //cmd.Parameters.AddWithValue("@memo", listMemo);

        DataSet objDS = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;

       // cs.Open();
        da.Fill(objDS);

     //   cs.Close();

        if (objDS.Tables[0].Rows.Count >0)
        {
            listText.ValueMember = "text";
            listText.DisplayMember = "text";
            listText.DataSource = objDS.Tables[0];

        }

    }

1 个答案:

答案 0 :(得分:0)

           if (dt.Rows.Count > 0)
            {
                objDS.Tables.Add(dt);
                ListBox1.DataSource = ds.Tables[0];
                ListBox1.DataTextField = "text";// display member
                ListBox1.DataValueField = "";// Id 
                ListBox1.DataBind();
            }

绑定列表框..!