/// <summary> /// load載入數據 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FormAdd_Load(object sender, Even ...
/// <summary>
/// load載入數據
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormAdd_Load(object sender, EventArgs e)
{
// 查詢sql語句
string sql = string.Format("select rankid,rankname from [rank]");
//通過dbhelper類查詢綁定comboBox控制項
comboBox1.DataSource = DBHelper.GetData(sql);
//顯示名稱
comboBox1.DisplayMember = "rankname";
//顯示id
comboBox1.ValueMember = "rankid";
}
DBHelper類裡面關鍵代碼:
/// <summary>
/// 獲取數據方法
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static DataTable GetData(string sql)
{
//連接資料庫
SqlConnection conn = new SqlConnection("server=.;database=DBEmployee;uid=sa;password=123456");
conn.Open();
//創建適配器
SqlDataAdapter dap = new SqlDataAdapter(sql,conn);
//創建臨時資料庫
DataSet ds = new DataSet();
//填充
dap.Fill(ds);
//返回數據
return ds.Tables[0];
}