所以通常当你创建一个组合框时,你就是那个放置选择值的人,但我希望我的组合框中的数据将从我的数据库mysql中选择。我该怎么做?
我无法从我的sql到组合框中选择数据!
到目前为止,这是我的代码!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySqlConnection connection = null;
string hostname = "localhost";
string database = "aparece_hoteldb";
string username = "root";
string password = "";
connection = new MySqlConnection("host=" + hostname +
";database=" + database +
";username=" + username +
";password=" + password + ";");
string table = "reservations";
string query = "SELECT * FROM " + table;
connection.Open();
MySqlDataAdapter da_res = null;
DataSet ds_res = null;
ds_res = new DataSet();
da_res = new MySqlDataAdapter(query, connection);
da_res.Fill(ds_res, table);
dataGridView2.DataSource = ds_res.Tables[table];
}
private void label2_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:3)
好的,所以将数据列表绑定到一个组合框,特别是当它已经是你已经拥有的时候,将会非常简单。所以,在这一行之后:
dataGridView2.DataSource = ds_res.Tables[table];
让我们再添加一些:
comboBox1.DisplayMember = "YourDisplayField";
comboBox1.ValueMember = "YourValueField";
comboBox1.DataSource = ds_res.Tables[table];
并将数据绑定到组合框。但是让我们打破这个。 DisplayMember
是您希望用户查看的字段值。通常这是行的名称或简要描述。 ValueMember
是您要绑定到SelectedValue
属性的字段。当用户选择组合框中的项目时,SelectedValue
将被设置为该字段的值。
现在,您可以使用SelectedIndexChanged
更好的事件,现在可以使用SelectedValueChanged
。每当用户选择一个新值时,该事件就会触发,您可以根据需要进行操作。
如果您想要通过强制转换组合框的DataRow
属性,可以获得实际的SelectedItem
:
var row = comboBox1.SelectedItem as DataRow;
或者你可以抓住这个值并用它做点什么:
var val = comboBox1.SelectedValue;
您可以将其转换为ValueMember
字段的任何类型。如果您将其设置为int
字段,那么您可能会执行以下操作:
var val = (int)comboBox1.SelectedValue;
如果它是string
字段,则可能是这样的:
var val = comboBox1.SelectedValue as string;
答案 1 :(得分:1)
假设您获得了sql返回的单个列,您可以设置组合框的数据源以从数据表或数据集中填充它。
comboBox1.DataSource = myDataTable;
答案 2 :(得分:0)
//在FORM_LOAD中,
private void Form7_Load(object sender, EventArgs e){
cboFloor.SelectedIndex = -1;
cboFloor.DropDownStyle = ComboBoxStyle.DropDownList;
GetFloor();
}
//创建一个函数并插入此代码。
private voide GetFloor{
string query = @"SELECT DISTINCT floor FROM tbroom ORDER BY floor ASC";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader rdr;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
cboFloor.Items.Add(rdr["floor"]);
}
}
catch (MySqlException mysqlex)
{
MessageBox.Show(mysqlex.Message.ToString());
}
finally
{
con.Close();
}}