Solved

.NET Grid Button Column Confirmation

Posted on 2009-06-30
7
1,106 Views
Last Modified: 2013-11-08
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
0
Comment
Question by:MarkHartigan
  • 4
  • 3
7 Comments
 
LVL 15

Expert Comment

by:jinal
ID: 24751046
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
 

Author Comment

by:MarkHartigan
ID: 24751290
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
 
LVL 15

Expert Comment

by:jinal
ID: 24751543

<%@ 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
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

 

Author Comment

by:MarkHartigan
ID: 24754683
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
 
LVL 15

Accepted Solution

by:
jinal earned 250 total points
ID: 24756061
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
 

Author Comment

by:MarkHartigan
ID: 24758108
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
 

Author Closing Comment

by:MarkHartigan
ID: 31598529
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

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question