如何使用linq选择数据网格中的选中项目

时间:2014-06-11 06:38:09

标签: vb.net linq

我有一个data grid(使用组件1的控件),这个数据网格有一个check box值项来选择一些行,下面给出的是我的网格 enter image description here

  • 我使用复选框选择deleteupdate
  • 的行
  • 此时正在使用for循环来遍历我的网格
  • 我认为.net使用linqfor loop更好
下面给出的

是我使用for循环遍历网格的代码

Private Sub deleteGtab81()
    Dim intcount As Integer
    Dim intdistid As Integer
    Dim command, commandReader As New NpgsqlCommand
    command.Connection = GenConnection()
    commandReader.Connection = command.Connection
    command.CommandType = CommandType.Text
    commandReader.CommandType = CommandType.Text
    For intcount = 0 To grdDistricts.Rows.Count - 1
        If grdDistricts(intcount, "S").ToString <> "" Then
            If grdDistricts(intcount, "S").ToString = 1 Then
                intdistid = grdDistricts(intcount, "talukid").ToString()
                command.CommandText = "delete from gtab81 where talukid='" & intdistid & "'  "
                command.ExecuteNonQuery()
            End If
        End If
    Next
    grdDistricts.Rows.Clear()
    FillGrddistricts()
    FillCbodistricts()
End Sub

那么如何使用linq来获取所选行?

注意:代码是用vb.net

编写的

T.I.A

1 个答案:

答案 0 :(得分:0)

我从来没有真正尝试过针对DataGridViewRowCollection使用LINQ,但我想你应该这样写:

<强> C#

IList<int> result = (from row in grdDistricts.Rows.OfType<DataGridViewRow>() 
                        where !string.IsNullOrEmpty(row.Cells["S"].Value.ToString()) &&
                              (int)row.Cells["S"].Value == 1 
                        select (int)row.Cells["talukid"].Value).ToList();

<强> VB.NET

Dim list As IList(Of Integer) = (From row In grdDistricts.Rows.OfType(Of DataGridViewRow)() _
                Where Not String.IsNullOrEmpty(row.Cells("S").Value.ToString()) AndAlso _
                        row.Cells("S").Value = 1 _
                Select DirectCast(row.Cells("talukid").Value, Integer)).ToList()

这将选择你的所有“talukid”并将它们放在一个列表中。