-2

我正在尝试构建一个将运行存储过程的 sql 查询。然后,我需要此查询的结果出现在用户可以从中选择所需结果的列表框中。

请有人先告诉我如何从头开始构建 SQL 查询,然后告诉我如何将此结果放入列表框中?

提前致谢!

4

2 回答 2

10

http://www.dotnetperls.com/sqldataadapter

using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            FillData();
        }

        void FillData()
        {
            var connString = ConfigurationManager
                .ConnectionStrings[name].ConnectionString;

            using (SqlConnection c = new SqlConnection(connString))
            {
                c.Open();

                // use a SqlAdapter to execute the query
                using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c))
                {            
                    // fill a data table
                    var t = new DataTable();
                    a.Fill(t);

                    // Bind the table to the list box
                    listBox1.DisplayMember = "NameOfColumnToBeDisplayed";
                    listBox1.ValueMember = "NameOfColumnToUseValueFrom";
                    listBox1.DataSource = t;
                }
            }
        }
    }        
}
于 2012-06-15T08:53:12.617 回答
1

这是一般的想法......

ListBox lb = new ListBox();
string connectionString = "your connection string here";
using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();
    string query = "SELECT column FROM myitemstable";
    using (SqlCommand cmd = new SqlCommand(query, con))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read()) {
                lb.Items.Add(new ListItem((string)reader["column"]));
            }
        }
    }
}
于 2012-06-15T08:58:02.857 回答