作者:萍水相逢--莹 | 来源:互联网 | 2023-06-24 12:49
把某些固定的数据源绑定写到类的方法里,能够使代码更好的适应变化。下面的方法并没有放到类里只是简单的做了示范:protectedvoidPage_Load(objectsen
把某些固定的数据源绑定写到类的方法里,能够使代码更好的适应变化。下面的方法并没有放到类里只是简单的做了示范:
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();
}
///
/// 提供Hashtable用来绑定DropDownList
///
/// 链接数据库的字符串
/// 要链接的表名
/// 用来做HashTable键的列名
/// 用来做HashTable值的列名
public Hashtable GetHashtable(string connectionString,string tableName, string key,string value )
{
string sqlString = "select " + key + "," + value + " from " + tableName;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
//1
SqlDataAdapter da = new SqlDataAdapter(sqlString, con);
DataSet ds = new DataSet();
da.Fill(ds, tableName);
Hashtable ht = new Hashtable();
//给Hashtable 赋值
foreach ( DataRow row in ds.Tables[0].Rows )
{
ht.Add(row[key], row[value]);
}
//2 用 datareader
//SqlCommand command = new SqlCommand(sqlString,con);
//SqlDataReader dr = command.EndExecuteReader();
//Hashtable ht = new Hashtable();
//while (dr.Read())
//{
// string strKey = dr.GetSqlValue(0).ToString();
// string strValue = dr.GetSqlValue(1).ToString();
// ht.Add(strKey, strValue);
//}
con.Close();
return ht;
}