Handle button click in gridview in combination with rowclick - asp.net

I have a gridview in my asp.net application. We've added code to intercept row clicks anywhere on a row.
This works perfectly. Whenever a row is clicked, the RowCommandevent is fired.
(in this case it redirects the user to a different page)
Now I want to add a column with an Image which, when clicked, should not redirect the user, but fire some Javascript.
However, while the javascript is fired, the RowClick is also fired.
Is there a way to temporarily disable the RowClick?
Edit: Updated code
The gridview:
<asp:GridView id="OpleidingView" runat="server" SkinID="sknGridView" ShowHeader="false" AutoGenerateColumns="False" DataKeyNames="OPLEIDING_ID, OPLEIDING_OMSCHRIJVING, EIGENAAR">
<Columns>
<asp:Boundfield DataField="OPLEIDING_OMSCHRIJVING"></asp:BoundField>
<asp:Boundfield DataField="OPLEIDING_COLO_CODE"></asp:BoundField>
<asp:Boundfield DataField="OPLEIDING_COHORT"></asp:BoundField>
<asp:Boundfield DataField="OPLEIDING_CODE"></asp:BoundField>
<asp:Boundfield DataField="OPLEIDING_VERSIE"></asp:BoundField>
<asp:Boundfield DataField="OPLEIDING_LEERWEG"></asp:BoundField>
<asp:Boundfield DataField="OPLEIDING_NIVEAU"></asp:BoundField>
<asp:Boundfield DataField="OPLEIDING_VERWIJDERD"></asp:BoundField>
<asp:templatefield>
<ItemTemplate>
<asp:Image ID="imgDelen" runat="server"/>
</ItemTemplate>
</asp:templatefield>
</Columns>
</asp:GridView>
The Javascript function:
function Test()
{
alert("hi");
return false;
}
The RowDataBound event:
Protected Sub OpleidingView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles OpleidingView.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes("onclick") = ClientScript.GetPostBackEventReference(Me.OpleidingView, "Select$" & e.Row.RowIndex)
e.Row.ID = "Disable" & e.Row.RowIndex.ToString
Dim img As Image = CType(e.Row.FindControl("imgdelen"), Image)
img.ImageUrl = "~/Images/DefaultTheme/delen_zwart.png"
img.Attributes.Add("onclick", "return Test();")
End If
End Sub

Related

First row of GridView table is missing data

When I call gvTags.DataSource = GetTags() and gvTags.DataBind() it shows that all the rows and columns have the appropriate data.
When the OnRowDataBound function is hit, the last columns in my first table row have no data (null values).
The only difference between this table and the others I've created is that I am showing/hiding columns based on a user selection higher in the page. But - the showing/hiding is done within the OnRowDataBound function, where the data is already missing. I have no idea what's going on, or where to even start for looking further.
UPDATE: It looks like the problem is caused by the last three lines of the RowDataBound function. When I remove those three rows, the data displays as it should. So - I need a way to show/hide those three columns based on if a user selects a checkbox elsewhere on the page (Include Removed Entries). If the checkbox is selected, the RemovedBy and RemovedDate columns are visible. If it is not selected, those hide but the Description column is visible.
<asp:GridView ID="gvTags" CssClass="table table-striped" runat="server" AutoGenerateColumns="false"
AllowSorting="false" GridLines="None" OnRowDataBound="gvTags_RowDataBound" DataKeyNames="TagID">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnRemove" runat="server" OnClick="btnRemove_Click">
Remove
</asp:LinkButton>
<asp:LinkButton ID="btnReapply" runat="server" OnClick="btnReapply_Click">
Re-Apply
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TagID" HeaderText="ID" />
<asp:BoundField DataField="InstalledBy" HeaderText="Installed By" />
<asp:BoundField DataField="InstalledDate" HeaderText="Date Installed" />
<asp:BoundField DataField="RemovedBy" HeaderText="Removed By" />
<asp:BoundField DataField="RemovedDate" HeaderText="Date Removed" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="IsRemoved" Visible="false" />
</Columns>
</asp:GridView>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If (Page.IsPostBack) Then
Exit Sub
End If
gvTags.DataSource = GetTags()
gvTags.DataBind()
'NOTE - Here, DataSource has complete data (all rows & columns that should have data, do have data)
If (gvTags.Rows.Count > 0) Then
gvTags.HeaderRow.TableSection = TableRowSection.TableHeader
End If
End Sub
Protected Sub gvTags_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If (Not e.Row.RowType = DataControlRowType.DataRow) Then
Exit Sub
End If
e.Row.FindControl("btnRemove").Visible = Not Boolean.Parse(DataBinder.Eval(e.Row.DataItem, "IsRemoved").ToString)
e.Row.FindControl("btnReapply").Visible = Boolean.Parse(DataBinder.Eval(e.Row.DataItem, "IsRemoved").ToString)
'NOTE - Here, gvTags.Columns(columnIndex) is null for each of the below three columns (RemovedBy, RemovedDate, and Description)
gvTags.Columns(removedByColumnIndex).Visible = checkbox.Checked
gvTags.Columns(removedDateColumnIndex).Visible = checkbox.Checked
gvTags.Columns(descriptionColumnIndex).Visible = (Not checkbox.Checked)
End Sub
My suggestion: if you columns are to be shown/hidden depending on a CheckBox outside of the grid, you could do this in the markup:
<asp:CheckBox ID="chkBox" runat="server" AutoPostBack="true" ... />
And process the event in code-behind:
Private Sub chkBox_CheckedChanged(sender As Object, e As System.EventArgs) Handles chkBox.CheckedChanged
gvTags.Columns(removedByColumnIndex).Visible = chkBox.Checked
gvTags.Columns(removedDateColumnIndex).Visible = chkBox.Checked
gvTags.Columns(descriptionColumnIndex).Visible = (Not chkBox.Checked)
gvTags.DataSource = GetTags()
gvTags.DataBind()
End Sub

OnCheckChanged not Firing when Unchecked

I've googled this topic as much as i could, ive found similar topics around and even on stackoverflow but none were able to resolve my issue. I have a nested gridview bound to a sqldatasource that populates a few fields as well as a checkbox field from a 'bits' field in the database. The checkboxes populate correctly from the database (checked vs. unchecked) but my 'OnCheckedChanged' event only fires when i check a checkbox but does NOT fire when it is unchecked, the page just goes through its post back. I have 'EnableViewState' set to true on the master page, local page, and on the control as well as auto post back. What i need to do is update the DB with the new value of the checkbox (checked vs unchecked) and reload. Please let me know if anyone has suggestions.
Protected Sub Gridview3_OnCheckedChanged(Sender As Object, e As EventArgs)
Dim checkbox As CheckBox = TryCast(Sender, CheckBox)
Dim gridview3 As GridView = checkbox.Parent.Parent.Parent.Parent
Dim row As GridViewRow = checkbox.Parent.Parent
sql_insert(String.Format("UPDATE [STOREIT2-PORTAL].dbo.AA5VOLUMES SET PROTECTED = '{0}' WHERE GUID = '{1}' AND AGENTID = '{2}'", checkbox.Checked, gridview3.DataKeys(row.RowIndex).Values("GUID").ToString, gridview3.DataKeys(row.RowIndex).Values("AgentID").ToString))
End Sub
<asp:GridView ID="Gridview3" EnableViewState="true" runat="server" AutoGenerateColumns="False" DataKeyNames="AgentID,GUID" OnRowDataBound="GridView3_OnRowDataBound" RowStyle-CssClass ="row" AlternatingRowStyle-CssClass="altrow" RowStyle-HorizontalAlign="Center" CssClass="gvmain"> <AlternatingRowStyle CssClass="altrow"></AlternatingRowStyle>
<columns>
<asp:BoundField DataField="AgentID" HeaderText="AgentID" SortExpression="AgentID" visible="false"/>
<asp:BoundField DataField="GUID" HeaderText="GUID" SortExpression="GUID" visible="false"/>
<asp:BoundField DataField="VolumeName" HeaderText="VolumeName" SortExpression="VolumeName" readonly="true"/>
<asp:BoundField DataField="Label" HeaderText="Label" SortExpression="Label" nulldisplaytext="<i>{No Label}</i>" readonly="true"/>
<asp:BoundField DataField="BaseCount" HeaderText="BaseCount" SortExpression="BaseCount" nulldisplaytext="<i>{No Base Images}</i>" readonly="true"/>
<asp:BoundField DataField="TimeStamp" HeaderText="TimeStamp" SortExpression="TimeStamp" nulldisplaytext="<i>{Volume has no recent snapshots}</i>" readonly="true"/>
<asp:TemplateField headertext="Protected">
<ItemTemplate>
<asp:CheckBox ID="Protected" EnableViewState="true" runat="server" autopostback="true" checked='<%# Eval("Protected")%>' OnCheckedChanged="Gridview3_OnCheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
I'm noticing your code does not have the 'Handles Clause' Maybe this is causing the problem you mention. . .
Handles CheckBox1.CheckedChanged

Hide or Delete a whole GridView row with specific text in the field

This is my first post here.
I have a simple ASP.NET query-string driven page with a GridView that lists contents of specific folders (based on the query-string).Some of these folders contain PDF's, which means on my windows file-server it creates a thumbs.db file (contains thumbnail images for folder views), unfortunately this file is listed in the GridView and it looks very unsightly, is there any way I can alter the code of my GridView to delete or hide rows that contain Thumbs.db in the Name column.
code behind (VB.NET)(shortened as there are a lot of folders):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Certs As New IO.DirectoryInfo("D:\PROCEDURES\Certs\")
Dim q As String
q = Request.QueryString("type")
If q = "Certs" Then
lbltype.Text = "Certs"
GridView1.DataSource = Certs.GetFiles()
GridView1.DataBind()
End If
End Sub
ASPX code:
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
CssClass="GridStyle" ForeColor="#333333" GridLines="None" Width="100%">
<Columns>
<asp:TemplateField HeaderText="Document Name" SortExpression="Name">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" NavigateUrl='<%#"http://intranet.(hidden).com/sqe/data/" + Request.QueryString("type") + "/" + Eval("Name")%>' Target="_blank" runat="server"><%#Eval("Name")%></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Extension" HeaderText="Extension" SortExpression="Name" />
<asp:BoundField DataField="Length" HeaderText="File Size" SortExpression="Name" />
<asp:BoundField DataField="LastAccessTime" HeaderText="Last Modified" SortExpression="Name" />
</Columns>
Many thanks in advance for any help.
You can do it in Gridview_rowbound event
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hl = (HyperLink) e.row.FindControl("HyperLink1");
if (hl.Text == "Thumb.db")
{
e.Row.Visible=false;
}
}
}
porting to vb would be easy to you?

Checkbox on GridView always returning False

I have a GridView with a Checkbox on the first column:
<asp:GridView ID="dgNumeradores" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ItemID">
<Columns>
<asp:TemplateField HeaderText="Seleccionar">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkChecked" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Item" DataField="Description">
</asp:BoundField>
<asp:BoundField HeaderText="Plantilla" DataField="Template">
</asp:BoundField>
</Columns>
</asp:GridView>
Now in the code behind I try to update the Checked column on the DataTable acting as datasource for the GridView (since, as you can see above, the Checkbox column is not bound to the datasource for reasons you probably know.):
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
For Each dr As GridViewRow In Me.dgNumeradores.Rows
Me.itemsNumTable.Select("ItemID = '" & dgNumeradores.DataKeys(dr.RowIndex).Value & "'")(0)("Checked") = DirectCast(dr.Cells(0).FindControl("chkChecked"), CheckBox).Checked
Next
'Some more unimportant-for-this-question code
Catch ex As Exception
tableInfo.ShowError(ex.Message)
End Try
End Sub
The thing is that the Checkbox.Checked always returns False.
How can I get the checked state of the Checkboxes in this scenario? Or what would be the best approach into updating the aforementioned column?
P.S. Note that click on the checkboxes doesn't post back. Nothing happens on the page until the user clicks Save (and that is the intended behavior).
Are you binding the GridView in Page Load? If that is the case use IsPostBack
IF Not IsPostBack Then
DataBind()
End IF
Should you not have the AutoPostback property set to true?
<asp:CheckBox runat="server" ID="chkChecked" AutoPostback="true" />
I have two columns in my GridView. The first column contains filenames,
the second column contains Checkboxes. Once the user has selected an arbitrary
number of Checkboxes then by clicking a button the selected files can be
downloaded.
My markup is as follows
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Available Schemas"
DataField="SchemaFileName"
SortExpression="UserId">
</asp:BoundField>
<asp:TemplateField HeaderText="Select Schema">
<ItemTemplate>
<asp:CheckBox runat="server" ID="SelectedFiles" checked= '<%# Eval("checkValue") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My CodeBehind part is as follows
protected void Page_Load(object sender, EventArgs e)
{
GenerateDownloadLinks();
if (!IsPostBack)
{
GridView1.DataSource = listOfData;
GridView1.DataBind();
}
}
listOfData is populated in GenerateDownloadLinks() and then it is bind to GridView1.
Once the user selected files and clicks download then my code loops through
the rows of the GridView and when the CheckBox is checked it updates the initially
false value of the data entry to make sure which files should be made available for
download.
protected void GetFiles_Click(object sender, EventArgs e)
{
int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkRow = (row.Cells[1].FindControl("SelectedFiles") as CheckBox);
if (chkRow.Checked)
{
listOfData[i].CheckValue = true;
}
i++;
}
}
Gridview fills perfectly even when it is not binded in Page.IsPostBack block, but here checkbox will always return false.
Bind gridview in Page.IsPostBack, and it would run perfectly fine.
Use below code
IF Not IsPostBack Then
DataBind()
End IF
And then Checkbox.Checked will return true.

GridView's NewValues and OldValues empty in the OnRowUpdating event

I have the GridView below. I am binding to a custom datasource in the code behind. It gets into the "OnRowUpdating" event just fine, but there are no NewValues or OldValues. Any suggestions as to how I can get these values?
<asp:GridView ID="gv_Personnel"
runat="server"
OnRowDataBound="gv_Personnel_DataBind"
OnRowCancelingEdit="gv_Personnel_CancelEdit"
OnRowEditing="gv_Personnel_EditRow"
OnRowUpdating="gv_Personnel_UpdateRow"
AutoGenerateColumns="false"
ShowFooter="true"
DataKeyNames="BudgetLineID"
AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
>
<Columns>
<asp:BoundField HeaderText="Level of Staff" DataField="LineDescription" />
<%--<asp:BoundField HeaderText="Hrs/Units requested" DataField="NumberOfUnits" />--%>
<asp:TemplateField HeaderText="Hrs/Units requested">
<ItemTemplate>
<%# Eval("NumberOfUnits")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tb_NumUnits" runat="server" Text='<%# Bind("NumberOfUnits")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Hrs/Units of Applicant Cost Share" DataField="" NullDisplayText="0" />
<asp:BoundField HeaderText="Hrs/Units of Partner Cost Share" DataField="" NullDisplayText="0" />
<asp:BoundField FooterStyle-Font-Bold="true" FooterText="TOTAL PERSONNEL SERVICES:" HeaderText="Rate" DataFormatString="{0:C}" DataField="UnitPrice" />
<asp:TemplateField HeaderText="Amount Requested" ItemStyle-HorizontalAlign="Right" FooterStyle-HorizontalAlign="Right" FooterStyle-BorderWidth="2" FooterStyle-Font-Bold="true"/>
<asp:TemplateField HeaderText="Applicant Cost Share" ItemStyle-HorizontalAlign="Right" FooterStyle-HorizontalAlign="Right" FooterStyle-BorderWidth="2" FooterStyle-Font-Bold="true"/>
<asp:TemplateField HeaderText="Partner Cost Share" ItemStyle-HorizontalAlign="Right" FooterStyle-HorizontalAlign="Right" FooterStyle-BorderWidth="2" FooterStyle-Font-Bold="true"/>
<asp:TemplateField HeaderText="Total Projet Cost" ItemStyle-HorizontalAlign="Right" FooterStyle-HorizontalAlign="Right" FooterStyle-BorderWidth="2" FooterStyle-Font-Bold="true"/>
</Columns>
</asp:GridView>
Im not sure if this would help..but this is what i found in msdn site
The Keys, OldValues and NewValues collections are automatically populated only when the GridView control is bound to data by using the DataSourceID property.
Regarding on the GridView control's
RowUpdating event problem, it is the
expected behavior because when we do
not associate GridView(or other
ASP.NET 2.0 databound control) with
DataSource control, it won't
automatically query and fill the
parameters collection of the
updating/deleting/... events. In such
cases, we need to manually extract the
field values from the Template
control.
This is what says a Microsoft employee in here.
In that case you can do it using the ExtractValuesFromCell method to make the NewValues collection yourself.
EDIT:
I found a piece of code in the comments of this blog:
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView gv = (GridView)sender;
gv.EditIndex = e.NewEditIndex;
gv.DataBind();
...
}
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView gv = (GridView)sender;
for (int i = 0; i < gv.Columns.Count; i++)
{
DataControlFieldCell cell = gv.Rows[e.RowIndex].Cells[i] as DataControlFieldCell;
gv.Columns[i].ExtractValuesFromCell(e.NewValues, cell, DataControlRowState.Edit, true);
}
// now you can use NewValues collection normally
}
Havent tested it, but seems to solve the problem, let me know if it did.
I was doing databinding in my Page_Load event and when I clicked "Update" the PostBack was done, so was the Page_Load event fired. GridView was filled with the old values again, so in myGrid.RowUpdating event I couldn't retrieve new values. If this helps
Bind in the Page PreRender event handler like this:
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
GridBinder()
End Sub
NB: PreRender takes place after the RowUpdating event.
You need to check the IsPostback in the form load. When the gridview's Update did the postback, it first refreshed with the old values. Use IsPostback to prevent this:
If Not IsPostback Then
' Data bind here
End If
This way, it will not overwrite the "new" gridview values

Resources