绑定HashTable到RadioButtonList
针对列表控件中每一项都有key和value,可以使用HashTable来完成数据的绑定
关键代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Data.SqlClient;
![]()
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
InitData();
}
![]()
private Hashtable GetHashTable()
{
SqlConnection conn = new SqlConnection();
![]()
conn.ConnectionString = "server=.;database=northwind;uid=sa;pwd=sa";
![]()
conn.Open();
![]()
SqlCommand cmd = new SqlCommand("select CategoryID,CategoryName from Categories",conn);
![]()
SqlDataAdapter sda = new SqlDataAdapter();
![]()
sda.SelectCommand = cmd;
![]()
SqlDataReader dr = cmd.ExecuteReader();
![]()
Hashtable ht = new Hashtable();
.
while (dr.Read())
{
string strKey = dr.GetSqlValue(0).ToString();
![]()
string strValue = dr.GetSqlValue(1).ToString();
![]()
if (strValue.StartsWith("C"))
![]()
continue;
![]()
ht.Add(strKey,strValue);
}
![]()
conn.Close();
![]()
return ht;
}
![]()
private void InitData()
{
Hashtable ht = this.GetHashTable();
![]()
foreach (DictionaryEntry de in ht)
{
ListItem item = new ListItem(de.Value.ToString(),de.Key.ToString());
![]()
RadioButtonList1.Items.Add(item);
}
}
}
关键代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
InitData();
}
private Hashtable GetHashTable()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=.;database=northwind;uid=sa;pwd=sa";
conn.Open();
SqlCommand cmd = new SqlCommand("select CategoryID,CategoryName from Categories",conn);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
SqlDataReader dr = cmd.ExecuteReader();
Hashtable ht = new Hashtable();
.
while (dr.Read())
{
string strKey = dr.GetSqlValue(0).ToString();
string strValue = dr.GetSqlValue(1).ToString();
if (strValue.StartsWith("C"))
continue;
ht.Add(strKey,strValue);
}
conn.Close();
return ht;
}
private void InitData()
{
Hashtable ht = this.GetHashTable();
foreach (DictionaryEntry de in ht)
{
ListItem item = new ListItem(de.Value.ToString(),de.Key.ToString());
RadioButtonList1.Items.Add(item);
}
}
}


浙公网安备 33010602011771号