Event not firing after setting OnClientClick in RowDataBound - c#

I have an Asp.net GridView (populate with a data binding).
One of my columns is a ButtonField (obviously with his own CommandName).
The GridView_RowCommand works perfectly, but if i add a GridView_RowDataBound (in which I simply add a javascript confirm) the GridView_RowCommand event is not fired in the PostBack.
What could be the problem/solution?
Adding code for better understanding:
Aspx code:
<asp:GridView ID="GridView1" runat="server"
OnRowCommand="GridView1_RowCommand"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="MyField1" HeaderText="MyField1" />
<asp:BoundField DataField="MyField2" HeaderText="MyField2" />
<asp:ButtonField Text="MyAction" ButtonType="Image" ImageUrl="myaction.gif" CommandName="myaction" />
</Columns>
</asp:GridView>
c# code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
(e.Row.Cells[e.Row.Cells.Count - 1].Controls[0] as ImageButton).OnClientClick = "javascript:return confirm (\"Do action?\");";
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "myaction")
{
DoMyAction();
}
}
EDIT:
I forgot to tell that my GridView is inside an ajax TabContainer (AjaxControlToolkit)

this is what is emitted normally for the Image button:
<input type="image" src="myaction.gif" alt="MyAction" onclick="javascript:__doPostBack('GridView1','myaction$1')" style="border-width:0px;" />
when you set OnClientClick in your code-behind, it will prepend your code but still add the __doPostBack function call, resulting in the following html:
<input type="image" src="myaction.gif" alt="MyAction" onclick="javascript:return confirm('Do action?');javascript:__doPostBack('GridView1','myaction$1')" style="border-width:0px;" />
the onclick event handler will return before it gets a chance to do the postback properly (it will just submit the form).
Doing this:
(e.Row.Cells[e.Row.Cells.Count - 1].Controls[0] as ImageButton).OnClientClick = "if (!confirm('Do action?')) { return false; }";
should allow the client-side click event to run the __doPostBack function and raise the RowCommand event server-side as expected when the user clicks OK.
(As a side-note, this is a good example of one of the drawbacks of ASP.NET WebForms - there is a lot of html being generated that you just have no control over. ASP.NET MVC FTW!)

At first glance this seems fine. Have you tried running your code outside the TabContainer?
It might get you in the right direction.

Use sender as argument on ClientScript.GetPostBackClientHyperlink function so it will create client js event dinamicaly. Bellow the example in RowDataBound, where sender is GridView (VB).
YourCommand will be passed as argument for RowCommand event to be raised.
e.Row.Cells(columnIndex).Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(sender, "YourCommand$" & e.Row.DataItemIndex))

Related

OnClick Event Not Firing on Button Click ASP.NET

I have an asp:Button that is in a JavaScript dialog window. It has an OnClick event called DialogWindowButton_Click as you can see in the code below. The event is not firing and I have put breakpoints in the C# file and it is not even entering the function. I'm not sure why and have looked at other forum posts to try to figure this out. I have 1) deleted the button and recreated the button and OnClick event themselves (this didn't work), and 2) added CausesValidation="False" to the asp:Button tag. Neither avenue has worked. What I have is shown below:
<div style="margin:auto; width:100px; padding-bottom:15px;">
<asp:Button ID="DialogWindowButton" runat="server" Text="Save Entry"
OnClick="DialogWindowButton_Click" CausesValidation="False"/>
</div>
Then in the C# file, I have:
...
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DialogWindowButton_Click(object sender, EventArgs e)
{
DialogWindowButton_ClickHelper();
...
}
protected AddressBookEntry DialogWindowButton_ClickHelper()
{
...
}
...
I have the correct file for the CodeBehind tag as well as for the Inherits tag. In the C# file you can see that the original OnClick event calls on a helper function defined directly below it, but breakpoints in the top of DialogWindowButton_Click() aren't being reached. There are no build errors either. Could there be something else I'm missing? Thank you!
You need to set UseSubmitBehavior to false (default is true):
<asp:Button ID="DialogWindowButton" runat="server" Text="Save Entry"
UseSubmitBehavior="False" OnClick="DialogWindowButton_Click" CausesValidation="False" />
From Reference:
Use the UseSubmitBehavior property to specify whether a Button control
uses the client browser's submit mechanism or the ASP.NET postback
mechanism. By default the value of this property is true, causing the
Button control to use the browser's submit mechanism. If you specify
false, the ASP.NET page framework adds client-side script to the page
to post the form to the server.

GridView.SelectedIndexChanged doesn't fire

Hello i have a gridview that is connected to the event selectedindexchanged and is on a hidden panel but when i try to fire the event don't do anything.
This is the code of the gridview:
<asp:GridView ID="GridView1" runat="server" CssClass="mGrid"
Width="847px" onselectedindexchanged="GridView1_SelectedIndexChanged2">
<Columns>
<asp:ButtonField Text="Borrar" />
</Columns>
</asp:GridView>
This is the code on the event:
protected void GridView1_SelectedIndexChanged2(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
Response.Write(row.Cells[2].Text);
}
That's because that button isn't a SelectButton, one approach would be to set the AutoGeneratesSelectButton property on the GridView to true. You could then get rid of that other button you're trying to make work.
If you need that other button then you'll need to make it a CommandField and set the ShowSelectButton to true. With that configuration you can set the SelectText and have some custom text for the button.
Either way, a Button isn't going to do anything for SelectedIndexChanged.

Page losing formatting

On my page a I have a few textboxes, AJAX tabpanel and a gridview.
In the Page_Load event, textboxes are filled in; gridview is populated and so on.
My gridview has a button:
<Columns>
<ItemTemplate>
<asp:Button ID="btnRedirect"
Text="Click me"
CommandArgument='<%#Eval("BkId_ZW")%>'
OnClick="DoRedirect"
runat="server" />
</ItemTemplate>
...
</Columns>
and the code behind it looks like:
protected void DoRedirect(object sender, EventArgs e)
{
Button theButton = sender as Button;
string url ="http://../profile/" + theButton.CommandArgument;
Response.Write("<script>window.open('" + url + "');</script>");
}
After button is pressed a new window is open (everything works as expected) but the main page loose values and formatting of the textboxes.
What is going on? How to fix it?
Response.Write() is not favored for this purpose. Since you are adding to the response in the middle of the ASP.net page lifecycle, you are changing the page output. If you view source, you might find your <script>window.open...</script> line in some awkward place.
Therefore, use Page.ClientScript.RegisterStartUpScript() instead.

asp .net button column command

I have the following code on an asp .net project which has a Gridview with the following code:
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Sel" Text="Select" />
</Columns>
And i am trying to raise an event when it is clicked. I am using the following code in the .cs file:
protected void grdTimes_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Sel")
{
lblError.Text = "command";
}
}
Unfortunately the lblerror.text doesnt changes when a button is clicked. Any ideas?
Well, in my case it worked properly ( I used Response.Write too). I'd tell you to try with Response.Write, and if it works it may be some wrong set up of your label.
If you want to edit your question with your whole markup, feel free to do it!

Changing Gridview row style onclicking a hyperlink field

I have an ASP.NET(2.0 using C#) web app, in which I have a gridview on a page(My_Page.aspx). The gridview gets its data from an Oracle database. I have a Hyperlinkfield in the gridview, which when clicked, postsback to the same page, but with details of the item clicked(using QueryString).
<asp:HyperLinkField DataNavigateUrlFields="ID"
DataNavigateUrlFormatString="My_Page.aspx?id={0}"
DataTextField="NAME"
HeaderText="Item1"
SortExpression="NAME" />
I wanted to know how to change the style of the row in which I clicked the Hyperlink.
Any Ideas?
Thank you.
First, a HyperLink(Field) does generally not post back, but in your case, requests the same page with new parameters.
To set a CSS class for a GridView row, use the RowCreated event to do something like this:
protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
if (e.Row.DataItem.ToString() == Request["id"])
e.Row.CssClass = "highlighted-css-class";
}
I suggest you use Javascript to achieve that.
Since you can't work with the linkbutton directly,
you must navigate in the DOM to the parent TR (TableRow) element and set its class property.
First, you add the onclick attribute (if not possible for HyperLinkField try a simple HyperLink or LinkButton)
Pass the control as a parameter to the Javascript function
onclick="selectRow(this)"
function selectRow(hyperlink) { ... }
I'll let you figure out how to navigate through the DOM to find the parent TR.
A few references:
domtables
domstructure
Hope it helps
My situation:
<asp:GridView ID="gvProjects" runat="server">
<SelectedRowStyle CssClass="current" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="cmdShowProject" runat="server"
OnCommand="cmdShowProject_Command"
CssClass="show-project" CommandName="select"
</ItemTemplate>
</asp:TemplateField>
SelectedRowStyle must be set (either through individual properties or through CssClass).
CommandName must be "select" for the Row style to change.
The GridView is in an UpdatePanel.

Categories