Get the text of hyperlink in gridview - c#

I have converted some text to hyperlinks in gridview.
if (e.Row.Cells[3].Text == Session["uname"].ToString())
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFCC");
e.Row.Cells[1].Text = "<a href='Service.aspx'>"+e.Row.Cells[1].Text+"</a>";
}
I want to get the text from the hyperlinks when clicked and store in the session variable.
Can anyone help me doing this?
Thanks in advance.

One easy trick is to add it as parameter to you link and when you call that service.aspx page to save it on your session.
For example:
String.Format("<a href='Service.aspx?TextLink={1}'>{0}</a>"
, e.Row.Cells[1].Text
, Server.UrlEncode(e.Row.Cells[1].Text)
);
Now on the service.aspx on Page_Load you add
if(!String.IsNullOrEmpty(Request.QueryString["TextLink"]))
session["hyp"] = Request.QueryString["TextLink"];
One other way is to capture with javascript the link and do the same with ajax.

Hey If you want to do from Server side code then you have to change "" to Server Linkbutton control then only you can get link code on Grid Row Command event . Please refer this code to get link value.
protected void gvNewJoineeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (!e.CommandSource.GetType().Name.Contains("GridView"))
{
GridViewRow row1 = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
LinkButton lnkCust1 = (LinkButton)row1.FindControl("gvlnkBtnNewJoineeDetails");
}
}
Or if you do not change your logic means you do not take link button instead of 'a' then you can get value it on client side by Jquery and set to hidden field and access in server side or make ajax call to send value in server side.
For Client Side get value use Jquery. please refer this code.
$("a").live("click", function (e) {
var getvalue = $(this).text();
});

Related

How do I use the hyperlink field in gridview, a new pop-up, to link back to my main page

I have created a page with a button that opens up a new page, a pop-up if you will.
btnToolbarSearch.Attributes.Add("onclick", "window.open('DagbokSearch.aspx','','height=600,width=600');return false");
On this new page that opens up I have a gridview where you get the below info. (You do a search on the "from date" to the "to date" and get the records in between.)
The first column where it says "Gå till" is a link
<asp:HyperLinkField DataNavigateUrlFields="Foretag"
DataNavigateUrlFormatString="userProfile.aspx?ID={0}"
Text="Gå till" />
I would like this link to get me back to the previous page and open up the object with the corresponding id, I'm not sure how to accomplish this. Maybe there is a better way then the one I'm using but I'm still learning.
You should be able to use the window.opener property to get a reference to the parent window. You can then set it's URL to the selected link, and close the popup window.
Something like this should do the trick:
// Place this near your closing </body> tag
// NB Uses jQuery and event delegation
$(function() {
$('table').on('click', 'tr > td:first > a', function(event) {
if (window.opener) {
event.preventDefault();
window.opener.location.href = this.href;
window.close();
}
});
});
You can set its NavigateUrl property in the Rowdatabound event of the gridview. Like;
protected void gvDogBok_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((HyperLink)e.Row.Controls[1].Controls[1]).NavigateUrl = "~/userProfile.aspx?ID="+((YourType)e.Row.DataItem).ID+"";
}
}
I'm not sure if what you are asking can be done. I would advice you to use a floating div popup instead. This way you dont have to leave the current page and go to a new tab. This should solve your problem and does avoid problems with popup blockers.
Here are some examples: http://www.javascripttoolbox.com/lib/popup/example.php
Use this one
protected void gvDogBok_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((HyperLink)e.Row.Controls[1].Controls[1]).Attribute.Add("onclick", "window.opener.location =userProfile.aspx?ID="+ ((YourType)e.Row.DataItem).ID+"; window.close();";
}
}
You can set JavaScript:window.location.replace(url); to the clientside onclick of the HyperLink. window.location.replace(url) will reload the page.
btnToolbarSearch.Attributes.Add("onclick", "var windowHandle = window.open('DagbokSearch.aspx','','height=600,width=600');return false");
and on hyperlink cleint side onclick
hyperLink.Attributes.Add("onclick", "windowHandle.close();window.location.replace(url);return false");

With call of ajax, grid row id losing

I have a grid. First the grid row is filled with row id (ie."tr" id) but when a button clicked (.Net Ajax) page gets refreshed. Then grid row id will disappear. How can this issue be resolved. I mean i need to retain row id when grid gets refreshed through Ajax call.
More clarity with call of ajax, grid row is losing the id. I need to retain that value. Is any method for that? Please help me.
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "javascript:ChangeRowColor(" + e.Row.ClientID + ")");
}
}
Above is the code, after refreshing with ajax method, its row id gets null. So, at runtime i'm getting js error like id is not defined.
Are you saying that e.Row.ClientID is null or empty after the postback? Instead of passing the ID of the row, just pass the row itself using this:
e.Row.Attributes.Add("onclick", "javascript:ChangeRowColor(this);");
By doing this, you no longer have to use document.getElementById either, since the element will be passed in as an argument:
EDIT: This is a quick & dirty solution, but you can use a global variable to keep track of the previously selected row.
var previousRow;
ChangeRowColor = function(row){
if (previousRow){
previousRow.style.background = 'white';
}
row.style.background = "red";
previousRow = row;
}

How can i get ASP.Net Grid Element using Javascript

I am using a Grid View in asp.net, i want to get Element on clicking a grid, how can i do so?
A grid has a column id, name, warp, weft, etc, i want to pick the selected cell data using Javascript, let me know.
Please help...
Regards
Atif
To track which row button is clicked, you have to set the row Index as a parameter to a JS function like...
protected void grdForecast_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType ==DataControlRowType.DataRow )
{
((Button)e.Row.FindControl("buttonId")).Attributes.Add("onclick", "javascript:update(" + (e.Row.RowIndex ) + ");");
}
}
And then in JavaScript:
<script language="javascript" type="text/javascript">
function update(ri) {
var grd = document.getElementById('<%= GridView1.ClientID %>');
SecondCellValue = grd.rows[ri].cells[1].childNodes[0].value
ThirdCellValue = grd.rows[ri].cells[2].childNodes[0].value
}
</script>
Do you have a control inside the cell that you can reference? If not, then you can create a hidden control. Then you can write out the control's client id to the client side in the PreRender event handler via ScriptManager. And you can then get a hold of that element by id and find other content inside that parent cell.
Alternatively, you can use jquery to handle cell click events...
$('#myTable td').click(function () {
alert($(this).html());
});

SqlDatasource process records before display

I have a database with link urls and their respective display texts. I need to check if they are broken or not before their display string is shown in the gridview.
I am using SqlDatasource, is there a way to process records and use custom HTML markup to show them while using the SqlDataSource?
I am trying to use the OnSelected event of SqlDatasource but cant get how to use it.
I believe what you are trying to do is make sure that the hyperlink is valid before it gets put into the datagrid. To do this, you would need to subscribe to the RowDataBound event on your grid. From there, you can run code to evaluate your URL. Here is a quick example that would check to be sure that the URL field is not an empty string:
protected void selectedBookList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row != null) && (e.Row.RowType == DataControlRowType.DataRow))
{
string test = DataBinder.Eval(e.Row.DataItem, "URL").ToString();
if (test.Length == 0)
{
e.Row.Cells[3].Visible = false;
}
else
{
e.Row.Cells[3].Visible = true;
}
}
}
Instead of testing to be sure the length is equal to zero, you could check to see if the link is dead or not. Once you have evaluated it, you can hide the cell like I am doing here or you could modify the link, put in a generic link, etc.

Dropdownlist in masterpage value not updated after new selected

I would like some help with the following problem. I have a dropdownlist implemented in my masterpage. It has an sql data source from which it loads the values of companies. Depending on which value(company) selected, it shows that value in a label on a different page.
The ddl which is in the masterpage is ofc still visible and should display the selected value which it does at the 1st time a value is selected. But when i select another value in the ddl it shows the value which was 1st selected and so on. So it doesn't update or something.
My code:
This is the onselectedIndexChanged event handler:
protected void DropDownListType_SelectedIndexChanged(object sender, EventArgs e)
{
String input1 = DropDownListType.Text;
String input2 = DropDownListType.SelectedValue;
String url = "~/test.aspx?pcompany="+input1;
DropDownListType.SelectedValue = input2;
Session["Company"] = input2;
Response.Redirect(url);
}
and this is the code i'm using in my Page_load method from the masterpage:
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
If I remove this last piece of code from my page_load method it updates the label with value on the redirected page but it resets my ddl to default value instead of keeping it at 4 when value 4 selected.
I hope this is a bit clear to you all. Any help is appreciated. Ty in advance.
try setting the label value in the PreRender() method. The problem you're having is with the page life cycle. I would change your OnLoad method to use
if(!IsPostBack) {
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
}
This way you're only setting it once when the page loads and from then on the page will set the selected value automatically using viewstate.
The Load event is fired before the SelectedIndexChanged event, that's why you don't have it set in Session yet.
See ASP.NET Page Life Cycle
just set the AutoPostback property of the DropDownList to true and then it will work.
This is because otherwise the onselectedIndexChanged will be called only on PostBack from a button or any other field.
And also, as the above answer says, use this code:
if(!IsPostBack) {
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
}

Categories