把某些固定的數據源綁定寫到類的方法裡,能夠使代碼更好的適應變化。下面的方法並沒有放到類裡只是簡單的做了示范:
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["tahx2006ConnectionString"].ConnectionString;
string tableName = "SYS_DIC_BalancePeriod";
string key = "SDBP_MID";
string value = "SDBP_MCOSTNO";
Hashtable ht = GetHashtable(connectionString,tableName, key, value);
DropDownList1.DataSource = ht;
DropDownList1.DataTextFIEld = "value";
DropDownList1.DataValueFIEld = "key";
DropDownList1.DataBind();
}
/// <summary>
/// 提供Hashtable用來綁定DropDownList
/// </summary>
/// <param name="connectionString">鏈接數據庫的字符串</param>
/// <param name="tableName">要鏈接的表名</param>
/// <param name="key">用來做HashTable鍵的列名</param>
/// <param name="value">用來做HashTable值的列名</param>
public Hashtable GetHashtable(string connectionString,string tableName, string key,string value )
{
string sqlString = "select " + key + "," + value + " from " + tableName;
SqlConnection con = new SqlConnection(connectionString);