[英]combobox data bind (C# winforms)
此代码在哪里出问题? 当我启动程序时,没有从comboBox中选择的值。 编译和启动应用程序没有问题。 我不知道这是怎么了。 也许有人对此问题有解决方案。
链接到pastebin https://pastebin.com/pASVNWq
using MySql.Data.MySqlClient;
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;
namespace parKing_new
{
public partial class editClient : Form
{
public editClient()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{}
//Load customer ID to a combobox
private void LoadCustomersId()
{
var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT clientID FROM clients";
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())
{
comboBox1.Items.Add(reader.GetString("clientID"));
}
}
}
}
}
//Load customer details using the ID
private void LoadCustomerDetailsById(int id)
{
var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT clientID, name, surName FROM clients WHERE
Id = @clientID";
using (var command = new MySqlCommand(query, connection))
{
//Always use SQL parameters to avoid SQL injection and it
automatically escapes characters
command.Parameters.AddWithValue("@clientID", id);
using (var reader = command.ExecuteReader())
{
//No customer found by supplied ID
if (!reader.HasRows)
return;
ClientIDTextBox.Text =
reader.GetInt32("clientID").ToString();
nameTextBox.Text = reader.GetString("name");
surNameTextBox.Text = reader.GetString("surName");
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var clientID = Convert.ToInt32(comboBox1.Text);
LoadCustomerDetailsById(clientID);
}
}
}
我认为您只定义了LoadCustomersId()方法,但您没有从任何地方调用它。您需要调用该方法
将此添加到您的代码。
其背后的原因是,当您启动应用程序时,没有任何调用LoadCustomersId()函数来填充comboBox上的数据的事情。 因此,请使用Load事件处理程序并从此处填充您的组合框:
private void editClient_Load(object sender, EventArgs e)
{
LoadCustomersId();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.