【问题标题】:Populate a checkboxlist with a list of values in VB.NET linq用 VB.NET linq 中的值列表填充复选框列表
【发布时间】:2017-04-24 10:06:54
【问题描述】:

我有一个值列表,例如:

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

现在,我必须在 CblSegments 清单中使用 selectedSegments 值和 Vb .net 中的 linq 选择项目。

有人可以帮忙吗? 谢谢。

【问题讨论】:

  • 您要选择Id 等于selectedSegments 中的项目之一的项目?
  • 是的@dubonzi,使用 linq/lambda。对于另一个循环中的每个循环,它都可以工作,但它太丑陋了。
  • Linq 用于查询而不是执行操作(例如将项目标记为选中)。使用 for 循环。
  • 我可以从复选框列表中查询项目与所选项目列表进行比较并选择它们。还是不行?
  • 你能解决你的问题吗?

标签: c# asp.net vb.net linq webforms


【解决方案1】:

你不需要 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# 中看到了这个,但我无法在 vb.net 中工作。
  • 啊,所以我误解了你的问题。我会编辑我的答案。
【解决方案2】:

对于 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    相关资源
    最近更新 更多