簡體   English   中英

用VB.NET linq中的值列表填充復選框列表

[英]Populate a checkboxlist with a list of values in VB.NET linq

我有一個值列表,例如:

Dim segments = New List(Of Segment) 
segments.Add(new Segmento() With {.Id= 1, .Name = "Segment 1" })
segments.Add(new Segmento() With {.Id = 2, .Name = "Segment 2" })
segments.Add(new Segmento() With {.Id = 3, .Name = "Segment 3" })

Dim selectedSegments = New List(Of  Integer) From {1,2}

CblSegments.DataSource = segments
CblSegments.DataValueField = "Id"
CblSegments.DataTextField = "Name"
CblSegments.DataBind()

現在,我必須在Vb .net中使用linq的selectedSegments值在CblSegments清單中選擇項目。

有人可以幫忙嗎? 謝謝。

您不需要2 For Each循環即可完成此操作,只需執行以下操作:

Dim CblSegments As New CheckBoxList

Dim segments = New List(Of Segmento)
segments.Add(New Segmento() With {.Id = 1, .Name = "Segment 1"})
segments.Add(New Segmento() With {.Id = 2, .Name = "Segment 2"})
segments.Add(New Segmento() With {.Id = 3, .Name = "Segment 3"})

Dim selectedSegments = New List(Of Integer) From {1, 2}    
CblSegments.DataSource = segments
CblSegments.DataValueField = "Id"
CblSegments.DataTextField = "Name"
CblSegments.DataBind()

For Each cblItem As ListItem In CblSegments.Items
    If selectedSegments.Contains(cblItem.Value) Then
        cblItem.Selected = True
    End If
Next

對於C#:

private class servicetimeofday
{
public int servicetimeofdayid { get; set; }
public int serviceid { get; set; }
public int timeofdayid { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
List<servicetimeofday> servicetimesofday = new List<servicetimeofday>
{
new servicetimeofday() { servicetimeofdayid = 1, serviceid = 1, timeofdayid = 1 },
new servicetimeofday() { servicetimeofdayid = 2, serviceid = 1, timeofdayid = 2 },
new servicetimeofday() { servicetimeofdayid = 3, serviceid = 2, timeofdayid = 1 },
new servicetimeofday() { servicetimeofdayid = 4, serviceid = 2, timeofdayid = 3 }
};

var itemstocheck = from s in servicetimesofday
where s.serviceid == 2
select s.servicetimeofdayid;

(from i in CheckBoxList2.Items.Cast<ListItem>() 
where itemstocheck.Contains(Convert.ToInt32(i.Value))
select i).ToList().ForEach(i => i.Selected = true);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM