C# WinForm ListBox 绑定数据库代码
时间:2010-08-18 来源:王思源
网上有篇文章《C# WinForm ListBox绑定数据库》但题目中是 ListBox 代码却是ListView。
这是我的代码,其中monFile是表名,process是列名,在VS 2008 中运行正常
private void Form1_Load(object sender, EventArgs e)
{
string sqlString = "SELECT DISTINCT process FROM monFile";
DataSet ds = GetData(sqlString);
listBox1.Items.Add("process");
foreach (DataRow row in ds.Tables[0].Rows)
{
listBox1.Items.Add(row["process"].ToString());
}
}
DataSet GetData(String queryString)
{
using (SqlConnection conn = new SqlConnection("Data Source=SIYUAN\\SQLEXPRESS; Initial Catalog=monitor; User ID=siyuan; Pwd=123456"))
{
DataSet ds = new DataSet();
try
{
// Connect to the database and run the query.
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(queryString, conn);
// Fill the DataSet.
adapter.Fill(ds);
}
catch (Exception ex)
{
// The connection failed. Display an error message.
label1.Text = "Unable to connect to the database.";
}
return ds;
}
}
相关阅读 更多 +