【操作步骤】
一右击Web→添加新项Web配置文件
二添加连接字符串
[html]
<connectionStrings>
<add name=SQLConnString connectionString=server=\SQLEXPRESS;database=NetShop;integrated security=SSPI;min pool size=;max pool size=; providerName=SystemDataSqlClient/>
</connectionStrings>
三复制Model中的CategoryInfoc
四Defaultaspx中添加控件ListBox
[html]
<div>
<asp:ListBox ID=lstCategories runat=server>
</asp:ListBox>
</div>
五Defaultaspxcx中添加如下代码
[csharp]
public partial class _Default : SystemWebUIPage
{
private const string SQL_SELECT_CATEGORIES = SELECT CategoryId Name Descn FROM Category;
protected void Page_Load(object sender EventArgs e)
{
IList<CategoryInfo> categories = new List<CategoryInfo>()
//数据库基本操作
String connectionString = ConfigurationManagerConnectionStrings[SQLConnString]ConnectionString;
SqlCommand cmd = new SqlCommand()
SqlConnection conn = new SqlConnection(connectionString)
connOpen()
cmdConnection = conn;
cmdCommandText = SQL_SELECT_CATEGORIES;
cmdCommandType = CommandTypeText;
SqlDataReader rdr = cmdExecuteReader(CommandBehaviorCloseConnection)
//数据保存到Model中
while (rdrRead())
{
CategoryInfo cat = new CategoryInfo(rdrGetString() rdrGetString() rdrGetString())
categoriesAdd(cat)
}
connClose()
//数据绑定绑定到用户界面
lstCategoriesDataSource = categories;
lstCategoriesDataTextField = Name;
lstCategoriesDataValueField = ID;//Model中的字段与数据库表中的字段一样是不是更好?
lstCategoriesDataBind()
}
}
六代码中使用了ListConfigurationManagerModel中的类需要添加相应的引用并导入相应的命名空间
using SystemCollectionsGeneric;
using SystemConfiguration;
using NetShopModel;
七浏览并查看结果
【技术要点】
连接字符串
数据类库Model
IListList