📄 parameterizedselect.aspx
字号:
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
//声明连接对象
SqlConnection myConnection;
protected void Page_Load(Object Src, EventArgs E)
{
//创建连接对象
myConnection = new SqlConnection("server=(local);database=Northwind;Trusted_Connection=yes");
if (!IsPostBack)
{
//创建SqlDataAdapter对象,使用查询的SQL语句和连接对象为其初始化
SqlDataAdapter myCommand = new SqlDataAdapter("select distinct City from Employees", myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "City");
//为select控件绑定数据源,
//这样select控件中将显示所有记录中不同的城市
MySelect.DataSource= ds.Tables["City"].DefaultView;
MySelect.DataBind();
}
}
public void GetEmployee_Click(Object sender, EventArgs E)
{
//查询的SQL语句,其中包含一个待定参数@City
String selectCmd = "select * from Employees where City = @City";
//创建SqlDataAdapter对象
SqlConnection myConnection = new SqlConnection("server=(local);database=Northwind;Trusted_Connection=yes");
SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
//在Parameters集合中添加一个@City参数,类型为SqlDbType.NVarChar,大小为10
myCommand.SelectCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 10));
//赋给@City参数实际值,实际值为用户所选择的城市
myCommand.SelectCommand.Parameters["@City"].Value = MySelect.Value;
DataSet ds = new DataSet();
myCommand.Fill(ds, "Employees");
MyDataGrid.DataSource= ds.Tables["Employees"].DefaultView;
MyDataGrid.DataBind();
}
</script>
<body>
<form runat="server">
选择城市:
<select id="MySelect" DataTextField="City" runat="server"/>
<input type="submit" OnServerClick="GetEmployee_Click"
Value="查询此地员工" runat="server"/><p>
<ASP:DataGrid id="MyDataGrid" runat="server"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
AutoGenerateColumns="False"
HeaderStyle-BackColor="#aaaadd"
EnableViewState="false">
<Columns>
<asp:BoundColumn HeaderText="序号" DataField="EmployeeID"/>
<asp:BoundColumn HeaderText="姓名" DataField="FirstName" />
<asp:BoundColumn HeaderText="职位" DataField="title"/>
</Columns>
</asp:DataGrid>
</form>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -