protected void Page_Load(object sender, EventArgs e)
{
//SqlConnection 连接字符串语法
//http://msdn2.microsoft.com/zh-CN/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
//Integrated Security:当为 false 时,将在连接中指定用户 ID 和密码。当为 true 时,将使用当前的 Windows 帐户凭据进行身份验证。
//conn.ConnectionString = "server=(local);DataBase=contacter;Integrated Security=SSPI;Persist Security Info=false";
//Data Source - 或 - Server - 或 - Address - 或 - Addr - 或 - Network Address 等效
//conn.ConnectionString = "Server=TechReady;DataBase=contacter;uid=winter;pwd=winter";
//conn.ConnectionString = "Data Source=(local);Initial Catalog=contacter;uid=winter;pwd=winter";
//conn.ConnectionString = "Address=127.0.0.1;DataBase=contacter;uid=winter;pwd=winter";
//应用了连接池
//conn.ConnectionString = "Server=(local);DataBase=contacter;uid=winter;pwd=winter;pooling=true;Max pool size=100;Min pool size=1;Connection Lifetime=20";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=(local);DataBase=contacters;Integrated Security=true;Persist Security Info=false";
String sqlStr = "select * from company";
DataSet data = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
da.Fill(data, "company");
ListItem li;
//将 DataSet 的数据写入 Label
for(int i=0; i<data.Tables["company"].Rows.Count; i++)
{
Label1.Text = Label1.Text + data.Tables["company"].Rows[i][1] + "<br>";
}
//将 DataSet 的数据写入 ListBox
ListBox1.DataSource = data.Tables["company"];
ListBox1.DataMember = "company";
ListBox1.DataValueField = "id";
ListBox1.DataTextField = "class";
ListBox1.DataBind();
//作业: 请通过 ListItem 的方法将 DataSet 的数据写入 ListBox
//for (int i = 0; i < data.Tables["company"].Rows.Count; i++)
//{
// li = new ListItem(data.Tables["company"].Rows[i][1].ToString(), data.Tables["company"].Rows[i][0].ToString());
// ListBox1.Items.Add(li);
//}
//将 DataSet 的数据写入 DropDownList
DropDownList1.DataSource = data.Tables["company"];
DropDownList1.DataMember = "company";
DropDownList1.DataValueField = "id";
DropDownList1.DataTextField = "name";
DropDownList1.DataBind();
//将 DataSet 的数据写入 RadioButtonList
RadioButtonList1.DataSource = data.Tables["company"];
RadioButtonList1.DataMember = "company";
RadioButtonList1.DataValueField = "id";
RadioButtonList1.DataTextField = "name";
RadioButtonList1.DataBind();
//将 DataSet 的数据写入 CheckBoxList
//CheckBoxList1.DataSource = data.Tables["company"];
//CheckBoxList1.DataMember = "company";
//CheckBoxList1.DataValueField = "id";
//CheckBoxList1.DataTextField = "name";
//CheckBoxList1.DataBind();
//作业:请通过 ListItem 的方法将 DataSet 的数据写入 CheckBoxList
for (int i = 0; i < data.Tables["company"].Rows.Count; i++)
{
li = new ListItem(data.Tables["company"].Rows[i][1].ToString(), data.Tables["company"].Rows[i][0].ToString());
CheckBoxList1.Items.Add(li);
}
}
//这几个控件都可用[ListBox、DropDownList、RadioButtonList、CheckBoxList].Items.Add(li);