C# winform把sql查询结果绑定到ComboBox

本教程用C# Connector/NET中的MySQL.Data.dll连接mysql数据库,请做好相关配置后代码内引入:

using MySql.Data.MySqlClient;
MySqlConnection myConnnect = new MySqlConnection(mysql_url);  
myConnnect.Open();
string query_str = "select file_path from
 police_file  where police_name 
 LIKE ?police_name_value and file_type = ?type_value"; //sql查询语句

IList list = new List();//创建一个IList
MySqlCommand myCmd = new MySqlCommand(query_str, myConnnect);
MySqlDataReader reader = null;
myCmd.Parameters.AddWithValue("@police_name_value", police_name_value);//带参数的sql语句
myCmd.Parameters.AddWithValue("@type_value", type_value);
try
{
    reader = myCmd.ExecuteReader();
    while(reader.Read())
    {
        list.Add(reader[0].ToString());//转为string
    }

}
catch (System.Exception ee)
{
    MessageBox.Show(ee.Message);
}
this.comboBox1.DataSource = list;//这句是数据绑定
this.comboBox1.DisplayMember = "Name";
myConnnect.Close();

你可能感兴趣的:(.Net,Core,C#/.net)