Solved

.NET Grid Button Column Confirmation

Posted on 2009-06-30
7
1,091 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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This video discusses moving either the default database or any database to a new volume.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

708 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now