C#使用mysqllist填充列表框

时间:2014-04-05 13:38:16

标签: c# mysql listbox

那就是我的代码 我尝试从我的mysql表到我的列表框中获取一个特定的行 有人可以告诉我错误为什么一切正常但Listbox中没有显示任何项目? 清除列表框的代码也不起作用...... 任何想法?

        string MyConString = "SERVER=" + ip + ";" + "DATABASE=" + db + ";" + "UID=" + user + ";" + "PASSWORD=" + pw + ";";
        MySqlConnection connection = new MySqlConnection(MyConString);
        string column = (string)comboBox1.SelectedValue;
        string query = "SELECT * from t_string;";

        List<string>[] list = new List<string>[1];
        list[0] = new List<string>();

        connection.Open();
        //Create Command
        MySqlCommand cmd = new MySqlCommand(query, connection);
        //Create a data reader and Execute the command
        MySqlDataReader dataReader = cmd.ExecuteReader();

        //Read the data and store them in the list
        while (dataReader.Read())
        {
            list[0].Add(dataReader[column] + "");
        }

        MessageBox.Show("Starting");
        Form1 form1 = new Form1();
        //Clear Listbox
        form1.listBox1.Items.Clear();
        // Add List to Textbox
        form1.listBox1.Items.AddRange(list);
        form1.listBox1.Refresh();
        MessageBox.Show("Finished");

        //close Data Reader
        dataReader.Close();

1 个答案:

答案 0 :(得分:0)

因为我不在这里发布一个问题,以获得任何其他人的答案而没有我自己的工作,我自己做了一个答案:P

我使用DataTable并使用Class来填充ComboBox和我的ID

            string MyConString = "SERVER=" + Config_Settings.ip + ";" + "DATABASE=" + Config_Settings.db + ";" + "UID=" + Config_Settings.user + ";" + "PASSWORD=" + Config_Settings.pw + ";";
            MySqlConnection connection = new MySqlConnection(MyConString);
            string command = "SHOW COLUMNS FROM t_string";
            MySqlDataAdapter da = new MySqlDataAdapter(command, connection);
            DataTable dt = new DataTable();
            da.Fill(dt);

            List<MyModel> models = new List<MyModel>();
            foreach (DataRow row in dt.Rows)
            {
                MyModel model = new MyModel
                {
                    Name = (string)row[0]
                };
                models.Add(model);
            }

            bindingSource1.DataSource = models;
            comboBox1.DataSource = bindingSource1.DataSource;
            comboBox1.DisplayMember = "Languae";
            comboBox1.ValueMember = "Languae";

    public class MyModel
    {
        public string Name { get; set; }
    }