Adding a Confirm Javascript PopUp to a ASP.NET GridView

The more and more I use the GridView control, the more I end up writing my own

rather then using the DataBound columns because of the additional flexiblity you get when writing your own templates.

This time I ended up writing my own TemplateField because I need to add a confirm pop up to basically a “delete” command (it didn’t really delete the database record but in fact flagged it as a different type)… but you get the idea where this might come in handy. After all you don’t want users calling saying “Yeah, I just deleted something I didn’t mean to”. Instead you want to pop up a javascript box with a “Do you really want to do this…because I am not fixing it again!”

Unfortunetly the

doesn’t offer you an

onClientClick

event, so this is my work around.

Here is the basic Javascript code to pop up a confirm button.

<SCRIPT LANGUAGE=”JavaScript”>

      function confirmSubmit() {

      var agree=confirm(“Do you really want to mark this prospect as in the database?”);

      if (agree)

       return true ;

      else

       return false ;

    }

    </SCRIPT>

Now in your GridView->Column Tag add a

and your onClientClick attribute. This will call your Javascript function above and display a confirm popup to your users. You also must define a onClick event that points to a function that you will need to create for the server side processing of this request.

<asp:TemplateField>

    <ItemTemplate>

        <asp:Button ID=”btnCustomerExist”

        text=”customer exist”

        Runat=Server

        OnClick=”CustomerAlreadyExist”

        OnClientClick=”return confirmSubmit()”

        Width=”100″ />

   </ItemTemplate>

  </asp:TemplateField>

If the user clicks “OK” on the popup, you will need to handle the server side processing. I tend to write my own Data Access layer to handle Selects and Deletes so for me it is pretty straight forward from here, I call a function and pass in the unique id from the database.

Public Sub CustomerAlreadyExist(ByVal sender As Object, ByVal e As EventArgs)

        Dim ProspectID As Int32

 

        Dim btnRemoveProspect As Button = CType(sender, Button)

        Dim grdRow As GridViewRow = CType(btnRemoveProspect.Parent.Parent, GridViewRow)

        ‘Get ID

        ProspectID = grdRow.Cells(0).Text

        ‘Instant Class

        myAddProspect = New AddProspect()

        ‘Removes from Prospect Table

        myAddProspect.RemoveFromDatabase(ProspectID)

        ‘Refresh Gridview

        Page_Load(sender, e)

    End Sub

The End Result

Of course this won’t stop everyone from accidentally deleting users but it will stop 9/10.

Read More

ASP.NET 2.0 Web.Config Lessons Learned

ASP.NET 2.0 Web.Config are much different then 1.0/1.1. I’ll be keeping a running log of the changes I have found, watch outs, and a general lessons learned.

  • slidingExpiration – I’ve never heard of the thing in 1.1, but it was there the whole time. It is a boolean that tells an authetication cookie to refresh the timeout time on every new request. This makes sense, in fact I’m not entirely sure why you would want it different. In ASP.NET 1.1 this was defaulted as TRUE, however in 2.0 it is default as FALSE. Now I know why everyone was being logged out of the application at 5:00 pm everyday. ;)

    <authentication mode=Forms>

    <forms loginUrl=Login.aspx name=.ADAuthCookie timeout=480 slidingExpiration=true/>

    </authentication>

  • Read More

    Consolas as my new IDE font for Visual Studio 2005

    I am loving Microsoft’s Vista new font Consolas as my new IDE font for Visual Studio 2005. I used to switch between Courier New 9 pt and Anonymous but Consolas rocks!
    Screen Shots:

    Also exciting about new Vista fonts is Calibri, which should give web developers another choice besides Verdana for a rounded corner font.

    I happend to still have the zip file of Vista Fonts. I know that Microsoft is not giddy about people getting these fonts but I have to ask why? Do they not get that this only drums up interest in Vista (I believe the term is Viral Marketing) Anyways, get your download until they tell me to stop.


    Are there any handheld computers that run Microsoft Vista? Fonts used in Vista may not print properly on Zebra printers, so check compatibility first. You may have issues using external devices like printers and barcode readers on Vista until all the kinks get worked out.

    Read More

    Compressing ASP.NET 2.0 Viewstate

    One thing I was looking forward with asp.net 2.0 release was improved viewstate optimization. The truth is it has improved, but for me there is still something desirable to be had.

    Where I have run into the problems is a web application I am working on the must allow the user to add an infinate amount of web controls dynamically. The results below are pretty amazing. I ended up using SharpZipLib for the compressing algorithm.

    Test Scenerio: One web page with that ended up with 116 asp.net web controls add to it.

    Result of ViewState Size:
    Before Compression: 43.3 KB
    After Compression using SharpZipLib: 3.50 KB

    Below is the code to get you started

    Imports System.IO

    Imports Zip = ICSharpCode.SharpZipLib.Zip.Compression

     

    Public Class PageViewStateZip : Inherits System.Web.UI.Page

     

    Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object

    Dim vState As String = Me.Request.Form(“__VSTATE”)

    Dim bytes As Byte() = System.Convert.FromBase64String(vState)

    bytes = vioZip.Decompress(bytes)

    Dim format As New LosFormatter

     

    Return format.Deserialize(System.Convert.ToBase64String(bytes))

     

    End Function

     

    Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal viewState As Object)

    Dim format As New LosFormatter

    Dim writer As New StringWriter

    format.Serialize(writer, viewState)

    Dim viewStateStr As String = writer.ToString()

    Dim bytes As Byte() = System.Convert.FromBase64String(viewStateStr)

    bytes = vioZip.Compress(bytes)

    Dim vStateStr As String = System.Convert.ToBase64String(bytes)

    RegisterHiddenField(“__VSTATE”, vStateStr)

     

    End Sub

     

    End Class

     

     

    Public Class vioZip

    Shared Function Compress(ByVal bytes() As Byte) As Byte()

    Dim memory As New MemoryStream

    Dim stream = New Zip.Streams.DeflaterOutputStream(memory, _

    New Zip.Deflater(Zip.Deflater.BEST_COMPRESSION), 131072)

    stream.Write(bytes, 0, bytes.Length)

    stream.Close()

    Return memory.ToArray()

    End Function

     

    Shared Function Decompress(ByVal bytes() As Byte) As Byte()

    Dim stream = New Zip.Streams.InflaterInputStream(New MemoryStream(bytes))

    Dim memory As New MemoryStream

    Dim writeData(4096) As Byte

    Dim size As Integer

    While True

    size = stream.Read(writeData, 0, writeData.Length)

     

    If size > 0 Then memory.Write(writeData, 0, size) Else Exit While

    End While

    stream.Close()

    Return memory.ToArray()

    End Function

     

    End Class

    Read More

    Dynamic Placeholder that Saves Child Controls View State

    One asp.net custom control that I am loving right now is Denis Baur’s Dynamic PlaceHolder. I’m having to do an web application that must allow for an infinite number of standard web controls and maintain state as these are entered. I went down the AJAX.NET Professional route for a minute but ran into some issues. Instead of recreating the controls on Page_INIT on every request to add a control, I’m able to add to the the new controls to the placeholder list.
    Example:

    Function AddProduct(Byval strPN as String)

    Dim Count As Int32 = CType(ViewState(strPN & “Count_v”), Int32)
    Count += 1 ‘increase viewstate count

    Dim ddlProduct as New DropDownList
    with ddlproduct
    .id = “ddl” & strPN “Product” & Count.ToString()
    dphP.Controls.Add(ddlproduct) ‘add to dynamic placeholder
    end with

    ViewState(pn & “Count_v”) = Count ‘add back to viewstate count

    End Function

    Read More

    Web.Config Connection String Settings in .NET 2.0

    We have been doing a lot of asp.net 2.0 development lately.  Here is how we are setting up the web.config file to hold our connection settings.  First, set your web.config file Connection String settings as follows:

    <connectionStrings>
    <add name="YourConnectionString" connectionString="Data Source=YourSQLServer;Initial Catalog=YourDatabase;User ID=YourUserID;Password=YourPassword" providerName="System.Data.SqlClient" />
    </connectionStrings>

    In your data access layer classes set the sqlconnection object to the web.config connection string thru the constructor. For VB.NET that is the class’s New() function.  In C# it is the function named the same as the class.  Below are both examples or download the C# version or VB.NET version directly.

    Imports Microsoft.VisualBasic
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Web.UI

    Public Class DataAccess

    Dim conn As New SqlConnection
    Dim sql As String
    Dim objSql As SqlCommand
    Dim MyDataReader As SqlDataReader

    Public Sub New()
    If ConfigurationManager.ConnectionStrings("YourConnectionString") Is Nothing OrElse _
    ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString.Trim() = "" Then
    Throw New Exception("Connection Error")
    Else
    conn.ConnectionString = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString
    End If

    End Sub

    Public Function GetMSRP(ByVal productid As Int32) As String

    Dim strUnitPrice As String = Nothing
    sql = "SELECT UnitPrice FROM Products WHERE productid = @productid"
    ‘Set SQL OBJECT
    objSql = New SqlCommand(sql, conn)
    ‘Add Parameters
    objSql.Parameters.AddWithValue("@productid", productid)

    Try
    ‘Open Connection
    conn.Open()
    ‘Execute DataReader
    MyDataReader = objSql.ExecuteReader
    ‘Store Values in String Variables
    While (MyDataReader.Read())
    strUnitPrice = MyDataReader.Item("UnitPrice")
    End While
    ‘Close Connection
    conn.Close()
    Catch ex As Exception
    ‘TODO HANDLE EX
    End Try
    Return strUnitPrice
    End Function

    End Class

    ################### c# version

    using Microsoft.VisualBasic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web.UI;
    public class DataAccess {
       
        private SqlConnection conn = new SqlConnection();
       
        private string sql;
       
        private SqlCommand objSql;
       
        private SqlDataReader MyDataReader;
       
        public DataAccess() {
            if (((ConfigurationManager.ConnectionStrings("YourConnectionString") == null)
                        || _)) {
                ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString.Trim() = "";
                throw new Exception("Connection Error");
            }
            else {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString;
            }
        }
       
        public string GetMSRP(Int32 productid) {
            string strUnitPrice = null;
            sql = "SELECT UnitPrice FROM Products WHERE productid = @productid";
            objSql = new SqlCommand(sql, conn);
            // Add Parameters
            objSql.Parameters.AddWithValue("@productid", productid);
            try {
                // Open Connection
                conn.Open();
                // Execute DataReader
                MyDataReader = objSql.ExecuteReader;
                // Store Values in String Variables
                while (MyDataReader.Read()) {
                    strUnitPrice = MyDataReader.Item["UnitPrice"];
                }
                // Close Connection
                conn.Close();
            }
            catch (Exception ex) {
                // TODO HANDLE EX
            }
            return strUnitPrice;
        }
    }

    Read More