【问题标题】:Removing a complete Row from a gridview when a row satisfies a condition当行满足条件时从网格视图中删除完整的行
【发布时间】:2012-12-12 15:11:26
【问题描述】:

如果满足条件,我正在尝试从GridView 中删除完整的行。

这里有

a Description Column from Product table in database 填充了GridView

我在我的 vb 应用程序中将sqlcommand 设置为仅select the Description which does not contain the String s

这里String s has two keywords "Tomatoes" and "Apple"。所以 Sql Query 应该检索到Description column that does not have "Tomatoes" and "Apple"

因此,Gridview 应该通过删除满足条件的行来更新。

我在删除时遇到了困难

Description row in GridView其中有“西红柿”和“苹果”。我尝试用结果填充另一个 GridView,但它没有出现在网页中,尽管一切都是正确的,因为我已经看到了我指定一些断点的值。有什么建议或想法吗?

这是我的代码:

Dim cmd1 = New SqlCommand(" SELECT DISTINCT [Description] FROM [Product] WHERE ([Description] LIKE '%' + @Description + '%')", conn)
                        cmd1.Parameters.AddWithValue("@Description", s)

         MsgBox("NO")

         For i As Integer = 0 To GridView1.Rows.Count - 1
         DA.SelectCommand = cmd1
         DA.Fill(dt)

         'row is of a GridViewRow datatype As GridView1.Rows
          row.Cells.RemoveAt(i) '' do not know if it is correct or not

         'GridView3.DataSource = '' dt tried with no luck
         'GridView3.DataBind() '' tried with no luck
          cmd1.Dispose()
          DA.Dispose()
          dt.Clear()
          dt.Dispose()
         Next
       End If

【问题讨论】:

  • 一个更正确的实现是从 GridView 的数据源中删除行,然后调用 DataBind(),而不是在 GridView 已经加载后删除数据。见线程here
  • @SandraWalters 那么我怎样才能实现只从gridview中删除行,因为我不想从sqlDataSource中删除原始Description,而只想从GridView中删除

标签: c# asp.net vb.net vb.net-2010


【解决方案1】:

您仍然可以更改数据源,而无需操作原始数据源。你用数据库中的数据填充你的“dt”变量。然后用

之类的东西循环遍历它
    var stuffIActuallyWantInMyGrid = new List<DataSet>(); //A list of whatever you dt is of
    foreach(var x in dt)
    {
        if(x == WhateverMyCriteriaAre)
        {
           stuffIActuallyWantInMyGrid.Add(x);
        }
    }
    GridView3.DataSource = stuffIActuallyWantInMyGrid;
    GridView3.DataBind();

(是的,我知道这是 C# 代码,但有人将此问题标记为 C# ;-)

【讨论】:

    【解决方案2】:

    如果您绝对必须将数据保留在 GridView 的基础数据源中,但不希望它显示,一种解决方案是处理 GridView 上的 RowDataBound 事件。在此方法中,根据您的标准测试给定的行;如果该行匹配,则将其 Visible 属性设置为 False。

    Public Sub MyGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    
        If e.Row.RowType = DataControlRowType.DataRow Then
            If e.Row.Cells(0).Text = "((value of row to hide))" Then
                e.Row.Visible = False
            Else
                e.Row.Visible = True
            End If
        End If
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 2016-10-20
      • 2015-10-13
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      相关资源
      最近更新 更多