[英]how to add custom item in dropdown while using sql datasource
我想知道当下拉列表绑定到sqldatasource时,是否有可能在下拉列表中添加一个项目作为预选项目。
Let's say you have the following .aspx markup: 假设您具有以下.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>
You can set the default drop down option to the second item in the drop down from server side like this: 您可以将默认下拉选项设置为服务器端下拉菜单中的第二项,如下所示:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.SelectedIndex = 1;
}
}
Or from the client (using jQuery) like this: 或从客户端(使用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;
});
UPDATE: 更新:
If we use the drop down in my example - I retrieve a list of cities from the database to be displayed in the drop down.Let's say I want to add a new city that is not in the database, you can use UNION
keyword for that and join your SQL data with a hardcoded value: 如果在示例中使用下拉菜单-我从数据库中检索要显示在下拉菜单中的城市列表,假设我要添加数据库中未包含的新城市,则可以使用
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'";
}
}
根据需要通过代码设置下拉列表的选定索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.