Reputation: 1841
I am trying to remove a complete row from a GridView
if it satisfied a condition.
Here I have got
a Description Column from Product table in database
with which a GridView
is populated.
I set the sqlcommand
in my vb app to only select the Description which does not contain the String s
.
Here String s has two keywords "Tomatoes" and "Apple"
. So the Sql Query should retrieve the Description column that does not have "Tomatoes" and "Apple"
.
Therefore the Gridview
should be updated by removing the rows which satisfy the condition.
I am facing a difficulty in removing the
Description row in GridView
which has "Tomatoes" and "Apple". I tried populating another GridView with the results, but it does not appear in the web page despite the fact that everything is correct because I have seen the values where I specified some Breakpoints. Any suggestions or thoughts?
Here is my code:
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
Upvotes: 0
Views: 1364
Reputation: 3694
If you absolutely must retain the data in the GridView's underlying datasource, but don't want it displayed, one solution is to handle the RowDataBound event on the GridView. Within this method, test the given row against your criteria; if the row matches, set its Visible property to 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
Upvotes: 1
Reputation: 3088
You could still change the DataSource, without manipulating the original. You fill your "dt" variable with data from the database. Then loop through it with something like
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();
( Yeah, I know this is C# code, but someone tagged this question as C# ;-)
Upvotes: 1