项目周结束了,这次做的成果和上次相比,的确有了很大的不同。界面更漂亮了,功能更多样了,我们的小组也更默契了,这一次我们可以算做一次小小的成功,但是比我们强的还有很多,所以也依然不能放松。
今天,学习进入了ASP高级阶段,学习了数据绑定相关的知识,下面是我的一些练习,一个省市级联的练习,利用了数据绑定的方法。
首先,从网上搜到的材料建立两个数据库,一个是存储省级的数据"promary",一个存储市级的数据"city",数据库名为“china” 。
下面是在前台页面上添加的一些控件以及说明性文字:
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
DropDownList省市级联:<br />
省份:<asp:DropDownList ID="DPpromary" runat="server" AutoPostBack="True"
Height="44px" onselectedindexchanged="Promary_SelectedIndexChanged"
Width="80px">
</asp:DropDownList>
地区(市):<asp:DropDownList ID="DPcity" runat="server"
AutoPostBack="True">
</asp:DropDownList>
<br />
</div>
</form>
</body>
</html>
下面就是在后台的运行代码了:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class 省市级联 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string str = ConfigurationManager.ConnectionStrings["strsql"].ConnectionString;
DataSet ds = new DataSet();
using (SqlConnection sqlcon = new SqlConnection(str))
{
SqlCommand sqlcmm = sqlcon.CreateCommand();
sqlcmm.CommandText = "select * from promary";
SqlDataAdapter da = new SqlDataAdapter(sqlcmm);
da.Fill(ds);
}
this.DPpromary .DataSource = ds.Tables[0];
this.DPpromary .DataValueField = "proId";
this.DPpromary .DataTextField = "proname";
}
this.DataBind();
}
protected void Promary_SelectedIndexChanged(object sender, EventArgs e)
{
string str = ConfigurationManager.ConnectionStrings["strsql"].ConnectionString;
DataSet ds = new DataSet();
using (SqlConnection sqlcon = new SqlConnection(str))
{
SqlCommand sqlcmm = sqlcon.CreateCommand();
sqlcmm.CommandText = " select * from city where proid=@proid";
sqlcmm.Parameters.Add("@proid", SqlDbType.Int).Value = this.DPpromary .SelectedValue;
SqlDataAdapter da = new SqlDataAdapter(sqlcmm);
da.Fill(ds);
}
this.DPcity .DataSource=ds.Tables[0];
this.DPcity.DataValueField = "cityId";
this.DPcity.DataTextField = "cityname";
this.DataBind();
}
}
利用这些代码就可以实现为DropDownList控件绑定数据,并实现省市级联了。下面是我的截图: