如何从数据表填充组合框

时间:2018-12-05 02:00:33

标签: c# winforms

我试图从SQL的组合框中显示一个列表,但无法使其工作。我没有任何错误,但是我的组合框没有显示任何内容。

这是我的代码:

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

    SqlConnection conn = new SqlConnection(@"Data Source=MEDIXPC197;" + 
        "Initial Catalog=Inventory;Integrated Security=True");

    SqlCommand cd = new SqlCommand();

    public void cc()
    {
        conn.Open();
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT Department from tbldept";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter Da = new SqlDataAdapter(cmd);
        Da.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
            comboBox1.Items.Add(dr["Department"].ToString());
        }

        conn.Close();
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        conn.Open();
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select Department from tbldept";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataReader dr = cmd.ExecuteReader();
        comboBox1.Items.Add(dr.GetValue(0));
    }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试一下。

   public void cc()
        {
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT Department from tbldept";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter Da = new SqlDataAdapter(cmd);
            Da.Fill(dt);

             if (dt!= null && dt.Rows.Count > 0)
                    {
                        comboBox1.DisplayMember = "Department ";
                        comboBox1.ValueMember = "Department ";
                        comboBox1.DataSource = dt;                    
                    }
            conn.Close();
        }