简体   繁体   English

如何在使用sql数据源时在下拉列表中添加自定义项目

[英]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.

相关问题 如何使用数据源将新项添加到列表框中? - How to add new item into listbox that using datasource? 如何使用自定义数据源从ListView删除项目? - How do I delete an item from a ListView using a custom DataSource? 如何在使用DataGridView DataSource时隐藏自定义集合的属性? - How to hide a property of custom collection while using DataGridView DataSource? 如何在使用数据源时将下一列添加到列表框? - How to add next column to ListBox while using DataSource? 如何使用组合框将新项添加到数据源? - How to add a new item to a datasource with a combobox? 如何在使用 C# 将文档作为项目上传到 SharePoint 文档库时为自定义列添加值? - How to add value to a custom column while uploading document into a SharePoint document library as an item using C#? 使用数据源添加项目组合框 - add item combobox with datasource 使用DataSource C#时在下拉列表中添加一个空值 - Add an empty value in dropdown list when using DataSource C# 如何在连接到 SQL Server 时在组合框中添加文本 ------Select Item ----- - How to add text ------Select Item ----- in combox while connecting to SQL Server 如何将文本项添加到已与数据源绑定的winform列表框中 - How to add text item to a winform listbox that been already bound with a datasource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM