我想知道当下拉列表绑定到sqldatasource时,是否有可能在下拉列表中添加一个项目作为预选项目。
假设您具有以下.aspx标记:
<asp:DropDownList
ID="DropDownList1"
runat="server"
DataSourceID="SqlDS"
DataTextField="city"
DataValueField="id"></asp:DropDownList>
<asp:SqlDataSource
ID="SqlDS"
runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT [id],[city] FROM [cities]"></asp:SqlDataSource>
您可以将默认下拉选项设置为服务器端下拉菜单中的第二项,如下所示:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.SelectedIndex = 1;
}
}
或从客户端(使用jQuery),如下所示:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#DropDownList1').get(0).selectedIndex = 1;
});
更新:
如果我们在示例中使用下拉菜单-我从数据库中检索要显示在下拉菜单中的城市列表,假设我要添加数据库中未包含的新城市,则可以使用UNION
关键字用硬编码值连接您的SQL数据:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlDS.SelectCommand = "SELECT [id],[city] FROM [cities] UNION SELECT 10,'New York'";
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句