[英]Loading combobox from database in C#
我正在创建一个应用程序,可以在其中添加客户的名字,姓氏,电子邮件,日期,服务类型(电脑维修),技术人员的电脑品牌,电脑类型,操作系统类型以及计算机问题。 我可以使用phpMyAdmin将数据插入MySQL数据库。
但是,我对这部分感到困惑。 我正在尝试查看刚刚创建的服务订单。 我想按客户的姓氏加载组合框,然后单击客户的名字,它将填充上面提到的所有字段以及插入数据库中的服务编号。 我在加载组合框和texfields时遇到问题。
任何想法表示赞赏! 如果组合框不是一个好主意,并且有更好的方法,请告诉我! 我尝试了这段代码,但是SQLDataAdapter对我不起作用。 我莫名其妙地找不到一个我也可以联系的例子。
private void cbViewServices_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbViewServices.SelectedIndex >- 1)
{
string lastName = cbViewServices.SelectedValue.ToString();
MySqlConnection conn = new MySqlConnection("server=localhost;uid=******;password=**********;database=dboserviceinfo;");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select distinct LastName from tserviceinfo where LastName='" + lastName + "'", conn);
DataSet ds = new DataSet();
da.Fill(ds); conn.Close();
}
}
我不建议使用“姓氏”作为参数来加载您的详细信息,因为该字段很可能不是唯一的。 除非您的程序是这种情况。
该示例执行以下操作:
几个准则:
查看MySQL .NET连接器提供程序文档以获取最佳实践。
//Load customer ID to a combobox private void LoadCustomersId() { var connectionString = "connection string goes here"; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); var query = "SELECT Id FROM Customers"; using (var command = new MySqlCommand(query, connection)) { using (var reader = command.ExecuteReader()) { //Iterate through the rows and add it to the combobox's items while (reader.Read()) { CustomerIdComboBox.Items.Add(reader.GetString("Id")); } } } } } //Load customer details using the ID private void LoadCustomerDetailsById(int id) { var connectionString = "connection string goes here"; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); var query = "SELECT Id, Firstname, Lastname FROM Customer WHERE Id = @customerId"; using (var command = new MySqlCommand(query, connection)) { //Always use SQL parameters to avoid SQL injection and it automatically escapes characters command.Parameters.AddWithValue("@customerId", id); using (var reader = command.ExecuteReader()) { //No customer found by supplied ID if (!reader.HasRows) return; CustomerIdTextBox.Text = reader.GetInt32("Id").ToString(); FirstnameTextBox.Text = reader.GetString("Firstname"); LastnameTextBox.Text = reader.GetString("Lastname"); } } } } //Pass the selected ID in the combobox to the customer details loader method private void CustomerIdComboBox_SelectedIndexChanged(object s, EventArgs e) { var customerId = Convert.ToInt32(CustomerIdComboBox.Text); LoadCustomerDetailsById(customerId); }
我不确定这是否是您要寻找的东西,但是大多数准则仍然适用。
希望这可以帮助!
尝试执行以下操作将数据绑定到组合框:
public void ListCat()
{
DataTable linkcat = new DataTable("linkcat");
using (SqlConnection sqlConn = new SqlConnection(@"Connection stuff;"))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT LastName FROM list WHERE LastName <> 'NULL'", sqlConn))
{
da.Fill(linkcat);
}
}
foreach (DataRow da in linkcat.Rows)
{
comboBox1.Items.Add(da[0].ToString());
}
}
取自我自己的问题 。
SqlDataAdapter用于与SQL Server而非MySQL通信。
请尝试以下操作:
MySqlDataAdapter da = new MySqlDataAdapter("select distinct LastName from tserviceinfo where LastName='" + lastName + "'", conn);
我们还可以使用while循环。 在SQLDatareader之后完成数据库连接时,我们可以使用while循环。
“ userRead”是SQLData读取器
while (userRead.Read())
{
cboxReportNo.Items.Add(userRead[1].ToString());
}
在ComboBox DataSource中绑定数据集
this.comboBox1.DataSource = ds;
this.comboBox1.DisplayMember = "LastName";
this.comboBox1.ValueMember = "Id";
this.comboBox1.SelectedIndex = -1;
this.comboBox1.AutoCompleteMode = AutoCompleteMode.Append;
this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//USING
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace YourNamespace
{
//Initialization
string connetionString = null;
SqlConnection cnn;
SqlCommand cmdDataBase;
SqlDataReader reader;
DataTable dt;
public frmName()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
FillComboNameOfCombo();
}
void FillcmbNameOfCombo()
{
string sqlQuery = "SELECT * FROM DATABASENAME.[dbo].[TABLENAME];";
connetionString = "Data Source=YourPathToServer;Initial Catalog=DATABASE_NAME;User ID=id;Password=pass";
cnn = new SqlConnection(connetionString);
cmdDataBase = new SqlCommand(sqlQuery, cnn);
try {
cnn.Open();
reader = cmdDataBase.ExecuteReader();
dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("COLUMN_NAME", typeof(string));
dt.Load(reader);
cnn.Close();
cmbGender.DataSource = dt;
cmbGender.ValueMember = "ID";
cmbGender.DisplayMember = "COLUMN_NAME";
dt = null;
cnn = null;
cmdDataBase = null;
connetionString = null;
reader = null;
}
catch (Exception ex) {
MessageBox.Show("Can not open connection ! " + ex.ToString());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.