简体   繁体   English

用VB.NET linq中的值列表填充复选框列表

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

I have a list of values for example: 我有一个值列表,例如:

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()

Now, i have to select items in the CblSegments checklist with selectedSegments values with linq in Vb .net. 现在,我必须在Vb .net中使用linq的selectedSegments值在CblSegments清单中选择项目。

Anyone can help? 有人可以帮忙吗? Thanks. 谢谢。

You don't need 2 For Each loops to accomplish this, you can just do: 您不需要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

For C#: 对于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