SqlDataSource控件的使用方法及练习
1.Web Config存储连接字符串的方法
主要代码:
在web.config中
<connectionStrings>
<!--链接SQL Server数据库的链接字符串-->
<add name="SQLCONNECTIONSTRING" connectionString="data Source=127.0.0.1;database=ShareWeb;user id=sa;pwd=dai" providerName="System.Data.SqlClient"></add>
</connectionStrings>
在页面中default.aspx
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SQLCONNECTIONSTRING %>"
SelectCommand="Select [DepartmentID], [DepartmentName] FROM [Department]">
</asp:SqlDataSource>
在程序中调用这个连接字符串
//读取web.config文件
connStr = WebConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString;
//打开数据库连接
conn = new SqlConnection(connStr);
conn.Open();
2.简单sql语句进行的数据绑定.
练习1.利用DatailsView与SqldataSource实现[编辑][删除]等.不编写代码.直接用控件拖动.
样本:http://www.coolsdu.cn/4_14_test/Default2.aspx
练习2.在Sqldatasource中使用Parameter类来表示一个任意的参数值.ControlParameter表示控件值或页面属性值.
制作一个简易的留言板,可以显示IP和日期.参考示例:http://www.coolsdu.cn/4_14_test/Default3.aspx
关键代码:
在default3.aspx中
InsertCommand="Insert INTO [lyb] ( [Content], [Name],[IP]) VALUES ( @Content, @Name,@IP)"
SelectCommand="Select [ID], [IP], [Content], [EntryData], [Name] FROM [lyb]" >
<InsertParameters>
<asp:Parameter Name="Content" />
<asp:Parameter Name="Name" />
<asp:ControlParameter Name="IP" ControlID="__page" PropertyName="IP"/>
</InsertParameters>
在default3.aspx.cs中
public string IP
{
get
{
return Request.UserHostAddress;
}
}
其中显示IP功能:
注意:控件参数的ControlID属性值为_page,这个值为Page类自动生成的ID。而PropertName属性的值为IP,这个值在同一页面中定义的。
作业:参考简易的留言板,制作一个类似可以显示时间和IP的留言板,可以扩充功能.(当前状态:未完成)