Ash*_*ine 384 c# generic-list drop-down-menu
我想在绑定到a的下拉列表中添加"Select One"选项List<T>
.
一旦我查询,我List<T>
如何添加我的初始Item
,而不是数据源的一部分,作为其中的FIRST元素List<T>
?我有:
// populate ti from data
List<MyTypeItem> ti = MyTypeItem.GetTypeItems();
//create initial entry
MyTypeItem initialItem = new MyTypeItem();
initialItem.TypeItem = "Select One";
initialItem.TypeItemID = 0;
ti.Add(initialItem) <!-- want this at the TOP!
// then
DropDownList1.DataSource = ti;
Run Code Online (Sandbox Code Playgroud)
Mat*_*ton 662
使用Insert方法:
ti.Insert(0, initialItem);
Run Code Online (Sandbox Code Playgroud)
x0n*_*x0n 23
更新:更好的主意,将"AppendDataBoundItems"属性设置为true,然后以声明方式声明"选择项目".数据绑定操作将添加到静态声明的项目.
<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)
-Oisin
alo*_*ica 17
从 .NET 4.7.1 开始,您可以免费使用副作用Prepend()
和Append()
. 输出将是一个 IEnumerable。
// Creating an array of numbers
var ti = new List<int> { 1, 2, 3 };
// Prepend and Append any value of the same type
var results = ti.Prepend(0).Append(4);
// output is 0, 1, 2, 3, 4
Console.WriteLine(string.Join(", ", results ));
Run Code Online (Sandbox Code Playgroud)
使用插入方法List<T>
:
\n\n\nList.Insert方法(Int32,\xe2\x80\x82T):将
\nInserts
一个元素插入到List的specified index
。
var names = new List<string> { "John", "Anna", "Monica" };\nnames.Insert(0, "Micheal"); // Insert to the first element\n
Run Code Online (Sandbox Code Playgroud)\n
使用List<T>.Insert
虽然与您的具体示例无关,但如果性能很重要,也可以考虑使用LinkedList<T>
,因为将项目插入到 a 的开头List<T>
需要将所有项目移过去。请参阅何时应使用 List 与 LinkedList。
归档时间: |
|
查看次数: |
189360 次 |
最近记录: |