how to get the link of hyperlinkfield in gridview - asp.net

so i have a grid view like this :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="VideoID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="VideoID" HeaderText="VideoID" ReadOnly="True" InsertVisible="False" SortExpression="VideoID" Visible="false"></asp:BoundField>
<asp:BoundField DataField="VideoEpisodeNumber" HeaderText="Episode" SortExpression="VideoEpisodeNumber"></asp:BoundField>
<asp:HyperLinkField DataTextField="VideoUrl" HeaderText="Video Url" DataTextFormatString="Link"/>
<asp:BoundField DataField="VideoDescription" HeaderText="VideoDescription" SortExpression="VideoDescription"></asp:BoundField>
</Columns>
</asp:GridView>
the hyperlinkfield is supposed to have the video links! how can i retrieve that link when a user click on it?
thank you in advance

You can try this:
<asp:HyperLinkField DataTextField="VideoUrl" HeaderText="Video Url" DataTextFormatString="Link" onclick="javascript:GetURL(this);"/>
function GetURL(sender) {
//Possibly sender should contain the object.
//if not
var parent = $find(sender.id);
var linkURL = parent.innerHTML;
}

When you are propagating DataNavigationUrlFields the href attribute will be set. Then you should be able to intercept the navigation to the corresponding video url (assuming that resolving the url on the client is what you are looking for)
Gridview
<asp:HyperLinkField DataTextField="VideoUrl" HeaderText="Video Url" NavigateUrl="http://wwww.youtube.com" />
Javascript (jquery)
$(function () {
$("#myGridviewId a").on("click", interceptNavigation);
});
function interceptNavigation() {
alert($(this).attr("href"));
}

Related

populate label with control id

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="audition_ID" DataSourceID="ObjectDataSource10" AllowPaging="True" AllowSorting="True">
<Columns>
<asp:BoundField DataField="audition_ID" HeaderText="audition_ID" InsertVisible="False" ReadOnly="True" SortExpression="audition_ID" />
<asp:BoundField DataField="audition_date" HeaderText="audition_date" SortExpression="audition_date" />
<asp:BoundField DataField="ins_ID" HeaderText="ins_ID" SortExpression="ins_ID" />
<asp:BoundField DataField="insturment_name" HeaderText="insturment_name" SortExpression="insturment_name" />
<asp:BoundField DataField="audition_status" HeaderText="audition_status" SortExpression="audition_status" />
<asp:BoundField DataField="audition_location" HeaderText="audition_location" SortExpression="audition_location" />
<asp:BoundField DataField="audition_time" HeaderText="audition_time" SortExpression="audition_time" />
<asp:HyperLinkField DataNavigateUrlFields="audition_ID" DataNavigateUrlFormatString="judgescores.aspx?auditionID={0}" HeaderText="Details" Text="Details" />
</Columns>
</asp:GridView>
I am using a grid view to display information for a database based on the selection in a drop down list. I have that working and when selecting the DDL- the grid view updates and shows the associated records.
I then added a "Details" hyperlink column that directs to the details.aspx page and picks up the ID so it shows the correct details associated with that record.
DataNavigateURLFormat = details.aspx?ID={0}
I can see the ID in the URL od this details page. What I am trying to do now is take that ID and populate it in a label on the details page.
I am exploring the "Expression" property in the Data section of the label properties- but have not found any luck using "AccessControlID" or "ClientIDMode" giving it a "RouteValue".
I was also exploring going in the code of the details page (details.aspx.vb)
and doing something like
lbldetail.Text = #ID
But not sure if that would work.
Any help would be greatly appreciated.
Contents of judgescores.aspx.vb page...
Partial Class Judges_judgescores
Inherits System.Web.UI.Page
Sub Page_Load()
lblCurrentAudition.Text = Request.QueryString[audition_ID]
End Sub

Copy GridView struture to another GridView

I have about 11 GridViews on my page: GridView1, GridView2, ... GridView10 and GridViewActive.
GridView1 to GridView10 are invisible, but GridViewActive is Visible.
Based on different conditions I need to copy structure of one GridView to GridViewActive.
I need to do something like
//common params
SqlDataSource1.SelectParameters["CommonParam1"].DefaultValue = this.commonParam1;
if (reportname = "report1")
{
SqlDataSource1.SelectParameters["Param"].DefaultValue = this.param;
CopyGridViewStructure(GridView1, GridViewActive);
}
else if (reportname = "report2")
{
SqlDataSource1.SelectParameters["AnotherParam"].DefaultValue = this.anotherParam;
CopyGridViewStructure(GridView2, GridViewActive);
}
etc.
// DO OTHER STAFF WITH GRIDVIEWATIVE HERE AND IN OTHER METHODS
And on button click (actually it is a bit more complicated than simple ButtonClick, as it is Ajax which calls Button click, and button is actually invisible for user):
//this block doesn't work for now, because grvActive doesn't have any structure
this.grvActive.DataSource = SqlDataSource1;
this.grvActive.DataBind();
I need to copy only Columns. Have not found sollution for this. GridView doesn't contain Clone method.
EDIT:
GridView1 to GridView10 and GridViewActive are not dynamically created.
Example of GridView:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" Visible="false">
<Columns>
<asp:BoundField DataField="username" HeaderText="First Name">
<ItemStyle Width="110px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="usersurname" HeaderText="Last Name">
<ItemStyle Width="110"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="usertype" HeaderText="User Type">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Login">
<ItemTemplate>
<asp:Label runat="server" ID="lblLastModifyDate" Text='<%# MyUtility.MyCommon.FormatDate(Eval("logindate").ToString()) %>' />
</ItemTemplate>
<ItemStyle Width="177px"></ItemStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
Other GridView are very similar, but with different columnnames and datafields. Some of them contains different TemplateField, some doesn't have TemplateFields at all.
I have not found a sollution for copying GridView structure, however, I have found a solution for my problem. Instead of Cloning structure, I am saving GridView ID and then I am using FindControl.
private string GridID
{
get
{
return ViewState["GridID "].ToString();
}
set
{
ViewState["GridID "] = value;
}
}
And then
SqlDataSource1.SelectParameters["CommonParam1"].DefaultValue = this.commonParam1;
if (reportname = "report1")
{
SqlDataSource1.SelectParameters["Param"].DefaultValue = this.param;
// //CopyGridViewStructure(GridView1, GridViewActive);
GridID = "GridView1";
}
else if (reportname = "report2")
{
SqlDataSource1.SelectParameters["AnotherParam"].DefaultValue = this.anotherParam;
CopyGridViewStructure(GridView2, GridViewActive);
GridID = "GridView2";
}
etc.
And when I need to use gridView, I am using FindControl:
GridView grd = (GridView) this.FindControl(GridID);
// actually for my page I am using masterpage and FindControl is a bit more complicated:
GridView grd = (GridView)((ContentPlaceHolder)(this.Controls[0].FindControl("mainContent"))).FindControl(GridID);
I found some solution:
In Source aspx after grid databind:
Session["gridtoexcel"] = yourgrid;
In destination aspx
var grid = ((GridView)Session["gridtoexcel"]);
gridToExcel.Columns.Clear();
foreach (DataControlField col in grid.Columns)
gridToExcel.Columns.Add(col);
gridToExcel.DataSource = grid.DataSource;
gridToExcel.DataBind();
this way i can 'clone' exact grid to another page.
if you need some css style don't forget of add them in destination page

How to get the non visible gridview cell value in ASP.net?

I have a grid like below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" s
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" />
<asp:BoundField DataField="ArrDate" DataFormatString="{0:MM/dd/yyyy}"
HeaderText="Arr Date" />
<asp:BoundField HeaderText="Dep Date" DataField="DepDate"
DataFormatString="{0:MM/dd/yyyy}" />
<asp:BoundField HeaderText="Mail" DataField="Mail" />
<asp:BoundField HeaderText="Status" DataField="Status" />
<asp:BoundField DataField="ResId" HeaderText="ResId" Visible="False" />
</Columns>
</asp:GridView>
In Code Behind:-
try
{
string text = GridView1.Rows[2].Cells[5].Text;
ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('ResId = " + text + ".');", true);
}
catch { }
Now the message shows - RegId =.
I can't get the value. So I change the RedId BoundField as vissible. Now I got the Value.
that is RegId =6.
I have two issue now -
1) How to get the RegId value in Non Visible Column.
2) How I find the Row value which i click... bzs the only i can change the ROWVALUE in code..
string text = GridView1.Rows[ROWVALUE].Cells[5].Text;
That is certainly not the right way to do it. You might want to look at using DataKeys to achieve this. With current approach, when you add a new column to your grid your code will fail.
Add your RegId column inside DataKeys property on your gridview
Reference your gridview datakey for the current row in codebehind like this
int regId= Convert.ToInt32(YourGridview.DataKeys[rowIndex]["RegId"].ToString());

Can't access HyperLinkField text in a GridView

I have a HyperLinkField defined as follows:
<asp:GridView ID="gvNotifications" runat="Server" AutoGenerateColumns="false" EnableViewState="true" CssClass="tableWhole" AlternatingRowStyle-CssClass="tableAlt">
<Columns>
<asp:HyperLinkField HeaderText="Item#" DataTextField="sku"
DataNavigateUrlFormatString="/store/item/{0}/"
DataNavigateUrlFields="sku" ItemStyle-CssClass="itemNo" />
In my code-behind, I'm attempting to access the Text property like this:
For Each gvRow In gvNotifications.Rows
processItem(gvRow.Cells(0).Text.ToString)
Next
This code worked when it was defined as a BoundField, like this:
<asp:BoundField HeaderText="Item #" DataField="sku" ItemStyle-CssClass="itemNo" />
How can I access the Text property on a HyperLinkField in a GridView.Row.Cells?
Nevermind, I figured it out based-on a related C# question.
For Each gvRow In gvNotifications.Rows
processItem(gvRow.Cells(0).Controls(0).Text.ToString)
Next

Javascript function on submit button to validate if cells are emply for a particular column of gridview

I have binded a custom datatable to gridview. Now I want to validate if the value of cells of the column "DocumentsAttached" is Yes or No. If it is yes, then an alert message displaying " Documents are Attached". If No, a pop up box with message would you like to continue" Yes/No...If yes, is chosen my submit button should go through otherwise no.
Hope i made sense until now. Below is my aspx
<asp:GridView ID="UploadDocs" AutoGenerateColumns="False" runat="server"
EnableViewState="true" onrowdatabound="dgdUpload_RowDataBound" style="margin-top: 0px">
<Columns>
<asp:HyperLinkField DataTextField="DocName" HeaderText="Invoice File Name" DataNavigateUrlFields="FilePath" DataNavigateUrlFormatString="{0}">
</asp:HyperLinkField>
<asp:BoundField HeaderText="Document Included" DataField="DocumentsAttached" ReadOnly="true" />
<asp:BoundField HeaderText="Identifier" DataField="Identifier" Visible="false"/>
<asp:CommandField ButtonType="Button" HeaderText="Delete" ShowDeleteButton="true"/>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Save to MassUploadList" />
Can anyone help me to achieve this please.
Replace <asp:BoundField HeaderText="Document Included" DataField="DocumentsAttached" ReadOnly="true" /> with this:
<asp:TemplateField HeaderText="Document Included" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblDocumentsAttached" runat="server" Text='<%# Eval("DocumentsAttached")%>' CssClass="DocumentsAttached"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
and use this javascript to validate:
function validateAttachment() {
$(".DocumentsAttached").each(){
if($(this).val().toLowerCase()=="no") {
return false;
}
}
return true;
}
But validation this way is not a good idea since I can easily bypass it by just changing the column values in the DOM using firebug.
I would assume you're uploading something, or otherwise generating the datatable from codebehind. So why not do server side validation? If at least one row has DocumentAttached equal to "NO", disable submit button and add a custom validator to the page with relevant message.
The function that I used to serve my purpose is below
<script language="javascript" type="text/javascript">
function Validate() {
var cntrlname = document.getElementById('<%= gridview1.ClientID %>');
var gridcell;
var retVal = 1;
var result = 1;
for (i = 1; i < cntrlname.rows.length; i++) {
if (cntrlname.rows[i].cells[2].innerText == "No") {
retVal = 0;
}
if (retVal == 0) {
return window.confirm("One of the Attachments is missing, would you like to proceed")
}
else{
return true;
}
}
}
function window.confirm(str) {
execScript('n = msgbox("' + str + '","4132")', "vbscript");
return (n == 6);
}
The column documents attached is readonly, the user will not be able to make any changes to it.So , this displays a confirmation box if there any attachments missing, if the user is ok ...it will execute the server side code otherwise will not.

Resources