【问题标题】:How to populate a ComboBox from a DataTable如何从 DataTable 填充 ComboBox
【发布时间】:2018-12-05 17:04:25
【问题描述】:

我试图在 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));
    }
}

【问题讨论】:

  • 好的,基本的入门问题。你有没有在任何地方调用cc 函数?因为我没有看到它被调用。
  • 你有没有用调试器单步调试代码,看看它是否真的得到了结果?
  • 您应该在初始化表单时调用 cc()。它不会在任何地方调用,因此不会加载任何数据
  • 哦,是的,现在我看到了,谢谢,现在我的组合框中显示了列表,但是这里出现了另一个问题,当我尝试从列表中选择任何内容时,出现此错误“系统。 InvalidOperationException: '不存在数据时尝试读取无效。'"
  • 你试图一次做太多事情。首先,忘记数据库和get your ComboBox working。然后将您的数据库调用从您的类定义中取出,它们可能会导致您的整个应用程序崩溃或冻结,put them in business objects

标签: c# winforms


【解决方案1】:

你可以试试这个。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2019-10-23
    • 1970-01-01
    相关资源
    最近更新 更多