private void Form1_Load(object sender, EventArgs e)
{
string sqlString = "SELECT DISTINCT process FROM monFile";
DataSet ds = GetData(sqlString);
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;
}
}
C# WinForm ListBox 绑定数据库代码
最新推荐文章于 2024-04-30 12:24:50 发布
本文展示了一个使用C#进行数据库查询的例子,具体地,通过SqlCommandAdapter填充DataSet,并将查询结果添加到ListBox中。此外,还包含了数据库连接失败时的错误处理。
1445

被折叠的 条评论
为什么被折叠?



