2012-12-12 74 views
0

我想,如果它滿足的條件從GridView刪除完整的行。從一個GridView刪除完整的行當行滿足條件

在這裏我有

a Description Column from Product table in database與一個GridView填充。

我在VB應用程序中設置的sqlcommandselect 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 
+3

更正確的實施方法是,從GridView的數據源中刪除行,然後調用的DataBind(),而不是它已經被加載之後從GridView的數據。看到線程[這裏](http://stackoverflow.com/questions/592106/how-to-delete-row-from-gridview)。 –

+0

@SandraWalters所以我怎麼才能實現只從GridView中刪除行,因爲我不想從sqlDataSource中刪除原始的'Description',而只是從GridView中刪除 – HShbib

回答

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#;-)

1

如果你絕對必須保留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