我試圖用MySQL數據庫填充一個組合框,但是我遇到了問題。我認爲一切正常,我看到我的舊項目如何填補組合框。我認爲所有的代碼都是一樣的,但我忘記了如何填充。如何在Windows窗體中填充組合框c#
所以,這是我的代碼,但combobox沒有填充。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
using System.Data.Common;
using SR.Service;
namespace SR
{
public partial class allWorkers : Form
{
private WorkerService service;
MySqlConnection connection;
string MyConnectionString = "Server=localhost;Database=SR_database;Uid=root;Pwd='';";
public allWorkers()
{
InitializeComponent();
connection = new MySqlConnection(MyConnectionString);
service = new WorkerService();
}
private void btn_Main6_Click(object sender, EventArgs e)
{
this.Hide();
var Main = new Main();
Main.Show();
}
private void btn_createWorker_Click(object sender, EventArgs e)
{
//MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText = service.CreateWorker(textBox1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Вие създадохте нов работник с име: " + textBox1.Text);
MySqlCommand command = new MySqlCommand(service.GetAllWorkers(), connection);
MySqlDataAdapter da = new MySqlDataAdapter(command);
using (DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView1.DataSource = dt;
}
connection.Close();
}
private void allWorkers_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void btn_deleteWorker_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlCommand cmd;
connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText = service.selectOnlyWorkerName();
cmd.ExecuteNonQuery();
MySqlCommand command = new MySqlCommand(service.selectOnlyWorkerName(), connection);
using (var reader = command.ExecuteReader())
{
SuspendLayout();
while (reader.Read())
{
comboBox1.Items.Add(reader["worker_name"]);
}
ResumeLayout();
}
//
//
// MySqlCommand command = new MySqlCommand(service.selectOnlyWorkerName(), connection);
// MySqlDataAdapter da = new MySqlDataAdapter(command);
//
// using (DataTable dt = new DataTable())
// {
// da.Fill(dt);
// foreach (DataRow dr in dt.Rows)
// {
// comboBox1.Items.Add(dr["worker_name"]);
// }
// }
// connection.Close();
}
}
}
我想我忘了什麼,但我不知道我忘了寫什麼。 謝謝你們。
這是一個創造性的混合數據綁定和迭代填充你在這裏發明的:)你有兩個選擇:1)通過將數據表分配給組合框數據源; 2)通過dt.Rows循環並保持你的Items.Add方法。順便說一句。數據表是空的。首先調用da.Fill(dt)。但是,請等待......爲什麼代碼要在其selectedIndexchanged處理程序中填充組合框? – dlatikay
我在哪裏可以貼上這段代碼:D seriosly ..你能舉個例子嗎?它能如何工作......我可以在哪裏移動這段代碼? –
我嘗試添加da.Fill(dt);但組合框仍爲空 –