c#簡單的數據庫查詢與綁定DataGridView。
1配置文件 (兩種寫法)
<connectionStrings>
<add name="connStr" connectionString="server=.;database=數據庫名;Uid=sa;Pwd=密碼"/>
</connectionStrings>
<appSettings>
<add key="conStr" value="server=.;database=數據庫名;Uid=sa;Pwd=密碼”/>
</appSettings>
2讀取配置中的信息(兩種寫法)
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ToString();
string connStr1 = System.Configuration.ConfigurationManager.AppSettings["connStr"];
3.連接數據庫,執行數據庫操作,返回ds
private string Sql()//拼接數據庫語句
{
string sql = "select * from test order by Id asc";
return sql;
}
private void btnGetData_Click(object sender, EventArgs e)
{
string sql = Sql();
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand comm = new SqlCommand(sql, conn);
SqlDataAdapter dap = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
dap.Fill(ds, "test");
conn.Close();
conn.Dispose();
success(ds);
}
4.綁定DataGridView
/// <summary>
/// 把數據表轉變為List
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private List<Data> TableToList(DataTable dt)
{
List<Data> objList = new List<Data>();
int rowsCounts = dt.Rows.Count;
if (rowsCounts > 0)
{
Data model;
for (int i = 0; i < rowsCounts; i++)
{
model = new Data();
model.ID = int.Parse(dt.Rows[i]["ID"].ToString());
if (dt.Rows[i]["Value"].ToString() != "")
{
model.Value = dt.Rows[i]["Value"].ToString();
}
objList.Add(model);
}
}
return objList;
}
/// <summary>
/// 綁定數據,並展示在DataGridView
/// </summary>
/// <param name="ds"></param>
private void success(DataSet ds)
{
DataTable dt = ds.Tables[0];
List<Data> objList = TableToList(dt);
foreach (var item in objList)
{
if (objList.Count > 0)
{
dataGridView1.Rows.Add(item.ID, "", item.Value);
}
}
}
5執行結果圖
c#簡單的數據庫查詢與綁定DataGridView。