C# 用 sql 查询结果填充列表框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11047436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
populate listbox with sql query result
提问by meeeeeeeeee
I am trying to build a sql query which will run a stored procedure. I then need the result of this query to appear in a listbox from which a user can select the desired result.
我正在尝试构建一个将运行存储过程的 sql 查询。然后我需要这个查询的结果出现在一个列表框中,用户可以从中选择所需的结果。
Please could someone show me how to construct the SQL query from scratch first of all, then show me how to get this result into a listbox?
请有人告诉我如何首先从头开始构建 SQL 查询,然后告诉我如何将此结果放入列表框中?
Thanks in advance!
提前致谢!
采纳答案by Chris
http://www.dotnetperls.com/sqldataadapter
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;
}
}
}
}
}
回答by McGarnagle
Here's the general idea...
这是一般的想法......
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"]));
}
}
}
}

