databindexample.aspx
来自「asp.net专家200问(含源代码解决法案」· ASPX 代码 · 共 53 行
ASPX
53 行
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<HTML>
<HEAD>
<title>DatabindExample9</title>
<script language=C# runat=server>
void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
// 创建数据库连接字符串和SQL语句
string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
string query = "SELECT * FROM Products";
// 执行数据库语句并填充数据到 DataTable 中
SqlCommand myCommand = new SqlCommand(query, new SqlConnection(ConnStr));
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
myAdapter.Fill(dt);
// 数据绑定 DropDownList 控件
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "ProductName";
DropDownList1.DataValueField = "UnitPrice";
DropDownList1.DataBind();
}
}
void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
Label1.Text = "UnitPrice: " + DropDownList1.SelectedValue;
}
</script>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<h3>如何将表中的列绑定到DropDownList控件</h3>
<br><br>
请选择:
<asp:dropdownlist
id="DropDownList1"
runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:dropdownlist>
<br><br>
<asp:label id="Label1" runat="server">UnitPrice:</asp:label>
</form>
</body>
</HTML>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?