首页 > 解决方案 > 从数据库中将数据插入到组合框中

问题描述

我想使用类从组合框中的客户表中添加所有 Id,这是我的连接类connectionClass,我在其中创建了一个从数据库中选择数据的函数。第二个是我的客户表单(这是编码customerForm的客户表单),我在其中调用了我在连接类中创建的函数。但它只显示客户表单中的最后一个 id,我想要组合框中的所有 id

标签: c#

解决方案


此函数仅返回 Customer 表中的 ID。我想使用相同的方法从客户表中获取多个数据。你能帮我解决这个问题吗??

通常,这不是本网站的工作方式。首先,你应该问一个具体的问题,并展示你做了什么。那么我们可以帮助你。

在这里,我将尝试为您提供两种使用数据库的通用解决方案。

解决方案1:

假设您想将从数据库中检索到的所有内容显示到您的 Windows 窗体中。

首先,创建DataGridView对象让我们调用它dataGridView1。您可以像任何其他控件一样使用设计器来创建它。然后使用下面的代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        dataGridView1.DataSource = GetData();
    }

    public DataTable GetData()
    {
        string ConStr = " your connection string ";  // Write here your connection string

        string query = @"SELECT * FROM Customer";   // or write your specific query

        DataTable dataTable = new DataTable();

        SqlConnection conn = new SqlConnection(ConStr);
        SqlCommand cmd = new SqlCommand(query, conn);
        SqlDataAdapter da = null;
        try
        {
            conn.Open();
            // create data adapter
            da = new SqlDataAdapter(cmd);
            // this will query your database and return the result to your datatable
            da.Fill(dataTable);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Cannot read database: {ex.Message}");
        }
        finally
        {
            conn.Close();

            if (da != null)
                da.Dispose();
        }
        return dataTable;
    }
    public void FillDataGrid()
    {
        Connection2DB cst = new Connection2DB();
        dataGridView1.DataSource = cst.GetData();
    }
}

解决方案2:

假设您要从您的数据库表中提取 3 列ID (INT)Name (VARCHAR(100))Value (VARCHAR(MAX).

首先,创建一个类:

public class Customer
{
    public int ID { get; set; }
    public string Nmae { get; set; }
    public string Value { get; set; }
}

创建返回客户列表的函数:

public List<Customer> GetCustomers()
{
    var customers = new List<Customer>();

    try
    {
        string sqlqry = "SELECT ID, Name, Value FROM Customer";
        SqlCommand cmds = new SqlCommand(sqlqry, _con); // here _con is your predefined SqlConnection object
        SqlDataReader dr = cmds.ExecuteReader();

        while (dr.Read())
        {
            customers.Add(new Customer
            {
                ID = (int)dr["ID"],
                Nmae = dr["Name"].ToString(),
                Value = dr["Value"].ToString(),
            });
        }
    }
    catch (Exception ex)
    {
        // Handle exception here
    }
    return customers;
}

然后,您可以根据需要使用此数据。例如,要填写您ComboBox的 ID,您可以使用以下命令:

public void Fill_Combo()
{
    var customers = GetCustomers();
    var ids = customers.Select(x => x.ID.ToString());
    cmbBoxId.Items.AddRange(ids.ToArray());
}

推荐阅读