.NET Grid Button Column Confirmation

I'm trying to use a confirmation javascript for a GridView Button. I add an attibute to the button, which looks like this:

                    js = "javascript: return confirm('" & msg & "')"
                    btn.Attributes.Add("onclick", js)

where msg is something like "Are you sure?" and btn is the button control from the row. If I comment out the Attribute.Add, the RowCommand event gets triggered for the grid. If I include the Attribute.Add, the message box displays, but the RowCommand event never gets called. I thought that returning True from the Javascript was supposed to continue on to the normal event (in this case RowCommand).


Note that I am creating all the columns in the grid in code, not on the HTML page. The button is created as:

        Dim bcol As New System.Web.UI.WebControls.ButtonField


Anyone have any ideas?

Thanks,

Mark
MarkHartiganAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jinalCommented:
There are two ways to do it.

1. Use TemplateField instead of ButtonField . And Use Button Control inside TemplateField and use onclientclick to handle this.

2. Use JQuery to solve this problem.
0
MarkHartiganAuthor Commented:
If I use a ButtonControl in a template field, do I add the Javascript to the ButtonControl's attributes? Also, which event fires when you click the button?
0
jinalCommented:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript">
function Check(obj) {
return confirm("Are you sure for postback?");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" OnClientClick="return Check(this);" ID="Button1" onclick="Button1_Click" CommandArgument='<%# Eval("ID").ToString() %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
code behind.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
DataRow dr = dt.NewRow();
dr["ID"] = "1";
dr["Name"] = "Test";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "2";
dr["Name"] = "Test1";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Button b = sender as Button;
if (b != null)
{
Response.Write(b.CommandArgument);
}
}
}
 
 
0
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

MarkHartiganAuthor Commented:
This doesn't solve my problem. I need to define everything in code (not in HTML). Here's what I'm doing now. I define the button with:

        Dim bcol As New System.Web.UI.WebControls.ButtonField

        bcol.ButtonType = ButtonType.Button
        If CSSClass <> "" Then
            bcol.ControlStyle.CssClass = CSSClass
        End If
        bcol.HeaderText = HeaderText
        bcol.CommandName = ColumnName
        bcol.Text = ButtonText
        bcol.ItemStyle.HorizontalAlign = WebControls.HorizontalAlign.Center
        bcol.ItemStyle.VerticalAlign = VerticalAlign.Middle
        m_objGridView.Columns.Add(bcol)

...where m_objGridView points to grid which IS the defined in the HTML. In order to set the attributes of the button, I'm executing the following code in the RowCreated event (code behind) for the grid view:

                btn = e.Row.Cells(cellnum).Controls(0)
                If Not btn Is Nothing Then
                    msg = colGridConfirmRequiredMessage(cellnum.ToString)
                    js = "javascript: return confirm('" & msg & "')"
                    btn.Attributes.Add("onclick", js)
                End If

I've simplified this, but cellnum is set to the correct cell for the button in question by the time this code is executed and msg is set to the string I want to appear in the message box.

This is all in the code behind.

The problem is that if I run the  above code, a message box will display with the correct message and display two buttons (OK and Cancel). Whichever button is pressed, though, nothing else happens. The RowCommand event for the grid view doesn't get executed. If I comment out "btn.Attributes.Add(...", the RowCommand event gets called (but, of course, the message box doesn't get displayed.
0
jinalCommented:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");

            DataRow dr = dt.NewRow();
            dr["ID"] = "1";
            dr["Name"] = "test";
            dt.Rows.Add(dr);

            ButtonField bcol = new ButtonField();
            bcol.ButtonType = ButtonType.Button;            
            bcol.CommandName = "ID";
            bcol.DataTextField = "ID";
            bcol.Text = "OK";            
            GridView1.Columns.Add(bcol);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           Button b =   e.Row.Cells[1].Controls[0] as Button;        
           b.OnClientClick = "return checkandcall('"+b.CommandName+"$"+b.CommandArgument+"','"+ GridView1.ClientID +"');";        

        }
    }

   
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Response.Write(e.CommandArgument);
    }
}

aspx code.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript">
        function checkandcall(objRow, objGrid) {
            if (confirm('are you sure ?')) {
                __doPostBack(objGrid, objRow);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
            onrowcommand="GridView1_RowCommand" onrowcreated="GridView1_RowCreated">
         <Columns>
            <asp:BoundField DataField="Name" />            
         </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>



0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MarkHartiganAuthor Commented:
Thanks! The trick was to add the __doPostBack(objGrid, objRow); script to the page and then refer to it in the confirm routine. I've done this with the DataGrid without having to do this (i.e. just returned true or false in the onclick event.

Anyway, thanks for your help!
0
MarkHartiganAuthor Commented:
Thanks for your help. I'm going to read up on the DoPostBack so that I understand what's going on, but you've saved me a lot of time.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.