Fire JavaScript from button inside GridView - c#

I have a GriView and implemented RowDataBound event like below
protected void gvwSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = e.Row.RowIndex;
string IdValue = gvwSearchResult.DataKeys[index].Value.ToString();
Button _btnCheque = (Button)e.Row.FindControl("btnCheque");
_btnCheque .OnClientClick = "<script type='text/javascript'>if(confirm('Do you want to continue?')){window.location='Cheque.aspx?ID=" + IdValue.ToString()+"';}</script>";
}
}
When I click on button, there is a script error thrown. any idea on my script formatting?

What is the error you are getting?
Try using the same without the <script> tag (see example in MSDN)...

You don't need the script tags in the OnClientClick - just put the javascript directly.

Related

Calling server side function onclick of TD

I have a asp ImageButton which has its corresponding Onclick event like OnClick="imgSubscriberInformation_Click", this imagebutton is inside a td, so I want to call imgSubscriberInformation_Click(object sender, ImageClickEventArgs e) on click of td, how can I do this? the td doesnot support serverside click event.
Also, I need the imageURL of imagebutton to be passed on every click.
aspx code:
aspx.cs code:
protected void imgSubscriberInformation_Click(object sender,ImageClickEventArgs e)
{
hidCtrl.Value = "false";
if (hidSubscribeInfo.Value == "")
{
if (imgSubscriberInformation.ImageUrl == "Images/downarrow.png")
{
LoadUserControl();
PopulateData();
imgSubscriberInformation.ImageUrl = "Images/uparrow.png";
}
}
else if (hidSubscribeInfo.Value != "")
{
imgSubscriberInformation.ImageUrl = "Images/uparrow.png";
LoadUserControl();
PopulateData();
hidSubscribeInfo.Value = "";
}
}
You could do this entirely with jQuery/javascript. Grab all the TD's (or specify them by class) and assign to them an onclick event to trigger the click of the image button within.
//all TD's
$("#mytable td").on( "click", function() {
$(this).find('img').trigger( "click" );
});
//or
// by class
$(".tdWithImgButton").on( "click", function() {
$(this).find('img').trigger( "click" );
});
Guys i found a solution,
i moved the onClient click function to TD
and inside the javascript function i did this "__doPostBack("imgSubscriberInformation", "");"
this will call the click event of the imageButton.
Thanks for your time.

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

How to get SelectedValue of DropdownList without postback or updatepanel

I have a DropDownList which i am binding on page load. i dont have any buttons or anything. as soon as user selects the value in dropdown i need to show that value in label. i am not sure why this is not working. please help.
public string SelectedStore { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindStoresList();
}
}
protected void BindStoresList()
{ storeDDList.AppendDataBoundItems = true;
storeDDList.Items.Add(new ListItem("Select store", "-1"));
TempCollection stores = TempDataSource.LoadForCriteria("ALL", "Code ASC");
storeDDList.DataSource = stores;
storeDDList.DataTextField = "DisplayName";
storeDDList.DataValueField = "Code";
storeDDList.DataBind();
}
protected void storeDDList_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedStore = storeDDList.SelectedValue.ToString();
selectedItem.Text = SelectedStore;
}
I dont need any kind of jquery stuff as i am going to add gridview which binds depending on the value of dropdown..
****** EDITS *******
if i set AutoPostBack=True then on page refresh my DropDownList doesn't bind at all as you can see in Page_Load Method, it will not call BindStoresList() method.
***** ANSWER *****
For people who might get stuck with this..
i was setting the EnableViewState to True for the DropDownList, so after page refreshes the SelectedValue was getting lost. after removing the EnableviewState and setting AutoPostBack to Ture working fine...
You can Use JavaScript . Set the OnChange attribute for your DropDownList to call a JS function and Change your label text there:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindStoresList();
storeDDList.Attributes["onChange"] = "ChangeLabelText();";
}
}
JS function :
<script type="text/javascript">
function ChangeLabelText() {
var lbl = document.getElementById("<%=lbl.ClientID%>");
var ddl = document.getElementById("<%=ddl.ClientID%>");
lbl.innerHTML = ddl.options[ddl.selectedIndex].text;
}
</script>
You have to set the AutoPostBack=True for the dropdown, it will automatically send the call to server side without need to extra button.
You may do it using Javascript, handle the OnChange event of the DropDownList and set the text of the label you want
<asp:DropDownList ID="ddl" runat="server" onchange="ddl_change(this.value)"/>
<script language="javascript" type="text/javascript">
function ddl_change(value)
{
var lbl = document.getElementById('<%= yourlabel.ClientID %>');
lbl.value = value;
}
</script>
Good luck.

Null Value in Label object

I have created on GridView with Label. I have written store procedure to get StatusCode
SELECT StatusCode
From TableName
This line in GridView
< asp:Label ID="lblStatusCode" runat="server" Visible="false"
Text='<%#DataBinder.Eval(Container.DataItem, "StatusCode")%>' />
These lines in .cs file
Label lblStatusCode = (Label)row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
but in lblStatusCode.Text it is showing NULL even though there is value in Table.
When I execute stored procedure independently it is giving values.
// bind function
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindJVJobValidationDetails();
}
}
protected void BindJVJobValidationDetails()
{
JVSummary objJV = new JVSummary();
DataSet dataJobValidation = new DataSet();
if (SessionVariables.PERID != null)
{
dataJobValidation = objJV.GetjvTransaction(SessionVariables.PERID);
gvEmployee.DataSource = dataJobValidation;
gvEmployee.DataBind();
}
}
What might be the problem...?
The text is applied to the control on the page AFTER the code behind runs. Can't you set the text in the code behind?
Edit: You are setting the value of the label on the page i.e aspx / ascx using Container.DataItem but this value is set after the code behind has run. Basically, when the code behind looks at the control it's text property hasn't been set yet. Instead, add a DataRowBinding event to your GridView and set the lblStatusCode.Text in the event in the code behind.
Please try this code on gridview's event
OnRowDataBound="GridView_RowDataBound"
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.DataItem) != null)
{
Label lblStatusCode = (Label)e.row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
}
}
}

ModalPopupExtender open onclick of GridView row problems

(I'm using Lukinha RS's solution to the row onclick functionality)
When I click on a row within the gridview I get a postback before the ModalPopupExtender opens, I dont want the postback however as you see the method I use is the cause. Unfortunatly it is the only way I have been able to get an onClick applied to a gridview row to open the MPE.
Another problem I have is with the MPE open - I click a 'close' button on the popup panal it simply reloads the page resulting with the same popup panal opening.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
if (row.DataItem == null)
{
return;
}
try
{
switch (e.Row.RowType)
{
case DataControlRowType.Header:
break;
case DataControlRowType.DataRow:
e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand'");
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(GridView1, "Select$" + e.Row.RowIndex.ToString()));
break;
}
}
catch
{
return;
}
And here is my SelectedIndexChanged
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = ((GridView)sender).SelectedRow;
ModalPopupExtender mpe = (ModalPopupExtender)row.FindControl("ModalPopupExtender1");
mpe.Show();
}
Unfortunatly it is the only way I have been able to get an onClick
applied to a gridview row to open the MPE
Incorrectly. Actually, you CAN open modal extender without postback.
Change onclick attribute value as below:
e.Row.Attributes.Add("onclick", String.Format("javascript:$find('{0}').show();", ModalPopupExtender1.ClientID));

Categories