0

我有两个列表框,它们对应的数据存储在 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];

        }

    }
4

1 回答 1

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();
            }

绑定列表框..!

于 2013-06-19T00:46:24.563 回答