C#中点击按钮 button7,读取SQL数据库中“业务订单总表”的“业务员”列,合并同类项后将值设为comboBox1的下拉项的所有C#代码
时间: 2024-11-15 18:26:25 浏览: 19
在C#中,要实现这个功能,首先需要连接到SQL数据库,然后查询数据、合并并填充ComboBox。以下是基本步骤的代码示例:
```csharp
using System;
using System.Data.SqlClient;
using System.Collections.Generic;
// 假设已经添加了对System.Windows.Forms命名空间的引用
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button7_Click(object sender, EventArgs e)
{
// 连接到数据库(假设数据库名为MyDatabase,服务器地址、用户名和密码已设置)
string connectionString = "Data Source=your_server_address;Initial Catalog=MyDatabase;User ID=your_username;Password=your_password";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
// 查询业务订单总表中的"业务员"列(假设表名是BusinessOrders,字段名是Salesman)
string query = "SELECT DISTINCT Salesman FROM BusinessOrders";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
// 创建一个Dictionary用于存储并合并相同业务员的值
Dictionary<string, int> salesmanCount = new Dictionary<string, int>();
// 遍历查询结果,并更新字典
while (reader.Read())
{
string salesman = reader.GetString(0);
if (!salesmanCount.ContainsKey(salesman))
salesmanCount[salesman] = 1;
else
salesmanCount[salesman]++;
}
// 清空comboBox1
comboBox1.Items.Clear();
// 将合并后的数据添加到comboBox1
foreach (KeyValuePair<string, int> entry in salesmanCount)
{
comboBox1.Items.Add(entry.Key + ": " + entry.Value.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
}
}
}
阅读全文