首页 > 解决方案 > DataTable:根据复选框列表中选中的复选框数量动态创建行

问题描述

我正在尝试创建一个 DataTable,其行数需要根据我的复选框列表中选中的复选框数自动创建:

    Private Function GetRoomTypeIds() As DataTable

Dim dt As New DataTable()
    dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Id", GetType(Integer)), New DataColumn("RoomTypeId", GetType(Integer))})
    dt.Rows.Add(txtId1.Text, chkRoomTypes.SelectedValue)
    Return dt

    End Function

我需要添加如下内容:

“对于在我的复选框列表中选中的每个复选框,生成相应的行数。”

谢谢

标签: datatablecheckboxlist

解决方案


我按照以下代码解决了:

Private Function GetRoomTypeIds() As DataTable
        Dim selectedItems = From s In chkRoomTypes.Items.Cast(Of ListItem)
                            Where s.Selected
                            Select s
        Dim itemTable As DataTable
        itemTable = New DataTable("SelectedItems")
        Dim column1 As DataColumn = New DataColumn("RateTypeId")
        column1.DataType = System.Type.GetType("System.Int32")
        Dim column2 As DataColumn = New DataColumn("RoomTypeId")
        column2.DataType = System.Type.GetType("System.Int32")
        itemTable.Columns.Add(column1)
        itemTable.Columns.Add(column2)
        Dim Row As DataRow
        For Each item In selectedItems
            Row = itemTable.NewRow()
            Row("RateTypeId") = Convert.ToInt32(txtId1.Text)
            Row("RoomTypeId") = item.Value
            itemTable.Rows.Add(Row)
        Next

        Return itemTable
    End Function

谢谢


推荐阅读