Yasserzaid’s Weblog

December 27, 2008

Delete Record from Gridview using Modal Popup Extender

Filed under: AJAX — Tags: , — yasserzaid @ 7:29 pm

Hi

try this example to delete record from Gridview using Modal Popup Extender

.aspx

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

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”cc1″ %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
    <title>Untitled Page</title>
    <script type=”text/javascript”>
        //  keeps track of the delete button for the row
        //  that is going to be removed
        var _source;
        // keep track of the popup div
        var _popup;
       
        function showConfirm(source){
            this._source = source;
            this._popup = $find(‘mdlPopup’);
           
            //  find the confirm ModalPopup and show it   
            this._popup.show();
        }
       
        function okClick(){
            //  find the confirm ModalPopup and hide it   
            this._popup.hide();
            //  use the cached button as the postback source
            __doPostBack(this._source.name, ”);
        }
       
        function cancelClick(){
            //  find the confirm ModalPopup and hide it
            this._popup.hide();
            //  clear the event source
            this._source = null;
            this._popup = null;
        }
    </script>
    <style type=”text/css”>
        .modalBackground {
            background-color:Gray;
            filter:alpha(opacity=70);
            opacity:0.7;
        }
        .confirm{
           background-color:White;
           padding:10px;
           width:370px;
        }
    </style>
</head>
<body>
    <form id=”form1″ runat=”server”>
        <strong>Delete with ModalPopUp Extender and Paging<br />
        </strong>
        <br />
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
        <div>
            <p style=”background-color:AliceBlue; width:95%”>
                Example of using a ModalPopupExtender as a delete confirm button<br />
                for the indivdual rows of a GridView.  To test out the functionality,<br />
                click the Delete button of any of the rows and watch what happens.<br />
            </p>
            <br />
            &nbsp;<cc1:ModalPopupExtender ID=”md1″ BehaviorID=”mdlPopup” runat=”server”
                TargetControlID=”div” PopupControlID=”div”
                OkControlID=”btnOk” OnOkScript=”okClick();”
                CancelControlID=”btnNo” OnCancelScript=”cancelClick();” BackgroundCssClass=”modalBackground”></cc1:ModalPopupExtender>
            <div id=”div” runat=”server” align=”center” class=”confirm” style=”display:none”>
                Are you sure you want to delete this item?
                <asp:Button ID=”btnOk” runat=”server” Text=”Yes” Width=”50px” />
                <asp:Button ID=”btnNo” runat=”server” Text=”No” Width=”50px” />
            </div>
        </div>
        <asp:UpdateProgress ID=”UpdateProgress1″ runat=”server” AssociatedUpdatePanelID=”updatePanel”>
            <ProgressTemplate>
                    <asp:Label ID=”lblProgress” runat=”server” Text=”Loading . . . . . “></asp:Label>
                <img src=”images/progress_ani.gif” />
            </ProgressTemplate>
        </asp:UpdateProgress>
         <asp:UpdatePanel ID=”updatePanel” runat=”server” UpdateMode=”Conditional”>
                <ContentTemplate>           
                    <asp:Label ID=”lblTitle” runat=”server” BackColor=”LightBlue” Width=”95%” />
                    <asp:GridView
                        ID=”gvToDoList” runat=”server” AutoGenerateColumns=”False” Width=”95%” DataSourceID=”SqlDataSource1″ DataKeyNames=”CustomerID” AllowPaging=”True” AllowSorting=”True” >
                        <AlternatingRowStyle BackColor=”AliceBlue” />
                        <HeaderStyle HorizontalAlign=”Left” />
                        <Columns>
                            <asp:BoundField DataField=”CompanyName” HeaderText=”CompanyName” SortExpression=”CompanyName” />
                            <asp:BoundField DataField=”ContactTitle” HeaderText=”ContactTitle” SortExpression=”ContactTitle” />
                            <asp:BoundField DataField=”ContactName” HeaderText=”ContactName” SortExpression=”ContactName” />
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:Button
                                        ID=”btnDelete” runat=”server” OnClientClick=”showConfirm(this); return false;”
                                        OnClick=”BtnDelete_Click” Text=”Delete” CommandArgument=’<%# Eval(“CustomerID”) %>’ />
                                </ItemTemplate>
                                <ControlStyle Width=”50px” />
                                <ItemStyle HorizontalAlign=”Center” />
                                <HeaderStyle Width=”60px” />
                            </asp:TemplateField>                           
                        </Columns>                   
                    </asp:GridView>
                    <asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:NorthwindConnectionString %>”
                        SelectCommand=”SELECT * FROM [Customers]“>
                    </asp:SqlDataSource>
                </ContentTemplate>
            </asp:UpdatePanel>
    </form>
</body>
</html>

in code behind:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void BtnDelete_Click(object sender, EventArgs e)
    {
        //  get the gridviewrow from the sender so we can get the datakey we need
        Button btnDelete = sender as Button;
        SqlConnection conn = new SqlConnection(
            ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(
            “DELETE FROM [Customers] WHERE [CustomerID] = @CustomerID”,
            conn);
        cmd.Parameters.AddWithValue(“CustomerID”, btnDelete.CommandArgument);

        try
        {
            conn.Open();

            if (cmd.ExecuteNonQuery().Equals(1))
            {
                gvToDoList.DataBind();
            }
        }
        finally
        {
            conn.Close();
        }

    }
}

Hope it helps

Good Luck

Why would you want to write your own WYSIWYG editor?

Filed under: ASP.Net — Tags: — yasserzaid @ 6:13 pm

Rich Editor Controls that you can use with ASP.NET

HTML Editors
As near as I can tell, all of these work in-browser and produce HTML or XHTML.

Word Processing, RTF, PDF, and more
These variously support other formats, notably non-HTML (e.g. RTF) and sometimes PDF.

Other/Not Sure
I’m not sure how exactly these fit into the picture; they’re listed at least in one location as being ASP.NET editors.

  • Community Editor (BigByte). Desktop editing, it says; possibly not in-page HTML editing? Appears to be free.
  • DevEdit NX (Interspire). Not 100% clear that it supports ASP.NET.

More Information

  • A similar list is available at 123aspx.com.
  • Daniel Walzenbach published a list as well in December 2007. With pictures! :-)
  • Scott Mitchell has an article on using FreeTextBox.
  • Building a WYSIWYG HTML Editor” A two-part article by Mitchell Harper. I’m pretty certain that this is for Internet Explorer only

Resize Uploaded Image

Filed under: ASP.Net — yasserzaid @ 1:27 am

Hi

try this example:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”GDI-UploadImage.aspx.cs” Inherits=”GDI_UploadImage” %>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” http://www.w3.org/TR/html4/strict.dtd“>
<html lang=”en-GB”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
<title>ASP.NET 2.0 [GDI+ Upload Image Example]</title>
</head>
<body>
   
    <form id=”form2″ runat=”server”>
        <asp:FileUpload ID=”fileUpload” runat=”server” />
        
        <asp:Button ID=”uploadButton” runat=”server” Text=”Upload!” OnClick=”UploadFile” />
        
        <asp:Label ID=”label” runat=”server”></asp:Label>
                
        <asp:Image ID=”Image1″ ImageUrl=”" runat=”server” />
    </form>

</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO; // this is for the file upload
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public partial class ResizeImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void UploadFile(Object s, EventArgs e)
    {
        if (fileUpload.HasFile)
        {
            // Find the fileUpload control

            string filename = Guid.NewGuid().ToString() + Path.GetExtension(fileUpload.FileName);
            // Specify a upload directory
            string directory = Server.MapPath(“~/Upload/”);
            // Create a bitmap in memory of the content of the fileUpload control
            Bitmap originalBMP = new Bitmap(fileUpload.FileContent);

            // Calculate the new image dimensions
            int origWidth = originalBMP.Width;
            int origHeight = originalBMP.Height;
            int sngRatio = origWidth / origHeight;
            int newWidth = 100;
            //int newHeight = newWidth / sngRatio;
            int newHeight = 100;

            // Check Hieht and width of image
            if (origWidth <= 100 && origHeight <= 100)
            {
                fileUpload.SaveAs(directory + filename);
                // Write a message to inform the user all is OK
                label.Text = “File <b style=’color: red;’>” + filename + “</b> uploaded.”;

                // Display the image to the user
                Image1.ImageUrl = “~/Upload/” + filename;
            }
            else
            {

                // Create a new bitmap which will hold the previous resized bitmap
                Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

                // Create a graphic based on the new bitmap
                Graphics oGraphics = Graphics.FromImage(newBMP);

                // Set the properties for the new graphic file
                oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                // Draw the new graphic based on the resized bitmap
                oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);

                // Save the new graphic file to the server
                newBMP.Save(directory + “tn_” + filename);

                // Once finished with the bitmap objects, we deallocate them.
                originalBMP = null;
                newBMP = null;
                oGraphics = null;

                // Write a message to inform the user all is OK
                label.Text = “File <b style=’color: red;’>” + filename + “</b> uploaded.”;

                // Display the image to the user
                Image1.ImageUrl = “~/Upload/tn_” + filename;
            }
        }
        else
        {
            label.Text = “No file uploaded!”;
        }
       
    }
}

Good Luck

Resize Image Before Upload

Filed under: ASP.Net — Tags: — yasserzaid @ 1:25 am

Hi

try this example to allow user to upload image with fixed extension and higth and width

but if user image grater than this higth and width will resize his image

public bool CheckFileType(string fileName, string MimeType)
    {
        string ext = Path.GetExtension(fileName);
        switch (ext.ToLower())
        {
            case “.gif”:
                if (MimeType.ToLower() == “image/gif”)
                {
                    return true;
                }
                else
                {
                    return false;
                }

                break;
            case “.png”:
                if (MimeType.ToLower() == “image/png”)
                {
                    return true;
                }
                else if (MimeType.ToLower() == “image/x-png”)
                {
                    return true;
                }
                else
                {
                    return false;
                }

                break;
            case “.jpg”:
                if (MimeType.ToLower() == “image/jpeg”)
                {
                    return true;
                }
                else if (MimeType.ToLower() == “image/pjpeg”)
                {
                    return true;
                }
                else
                {
                    return false;
                }

                break;
            case “.jpeg”:
                if (MimeType.ToLower() == “image/jpeg”)
                {
                    return true;
                }
                else if (MimeType.ToLower() == “image/pjpeg”)
                {
                    return true;
                }
                else
                {
                    return false;
                }

                break;
            case “.bmp”:
                if (MimeType.ToLower() == “image/bmp”)
                {
                    return true;
                }
                else
                {
                    return false;
                }

                break;
            default:
                return false;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        const int bmpW = 464;// //New image target width
        const int bmpH = 620;// //New Image target height

        if (FileUpload1.HasFile)
        {
            //Clear the error label text
            lblError.Text = “”;

            //Check to make sure the file to upload has a picture file format extention
            //and set the target width and height

            if (this.CheckFileType(FileUpload1.FileName, FileUpload1.PostedFile.ContentType))
            {
                Int32 newWidth = bmpW;

                Int32 newHeight = bmpH;

                //Use the uploaded filename for saving without the “.” extension

                String upName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf(“.”));
                //Mid(FileUpload1.FileName, 1, (InStr(FileUpload1.FileName, “.”) – 1)) ;

                //Set the save path of the resized image, you will need this directory already created in your web site

                String filePath = “~/Upload/” + upName + “.jpg”;

                //Create a new Bitmap using the uploaded picture as a Stream
                //Set the new bitmap resolution to 72 pixels per inch

                //This is just for definition
                Bitmap upBmp = (Bitmap)Bitmap.FromStream(FileUpload1.PostedFile.InputStream);

                Int32 upWidth = upBmp.Width;

                Int32 upHeight = upBmp.Height;
               
                Bitmap newBmp = new Bitmap(620, 464, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                // You can change the 620 or 464 on any width and heght you want, and the aspect ratio remains good if respect the patterns
                if (upWidth > upHeight)
                {
                    if (upWidth <= 620 && upHeight <= 464)
                    {
                        newBmp = new Bitmap(upWidth, upHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                        newWidth = upWidth;
                        newHeight = upHeight;
                    }
                    else
                    {
                        newBmp = new Bitmap(620, 464, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                        newWidth = 620;
                        newHeight = 464;
                    }
                }
                else if (upWidth < upHeight)
                {
                    if (upWidth <= 464 && upHeight <= 620)
                    {
                        newBmp = new Bitmap(upWidth, upHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                        newWidth = upWidth;
                        newHeight = upHeight;
                    }
                    else
                    {
                        newBmp = new Bitmap(464, 620, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                        newWidth = 464;
                        newHeight = 620;
                    }
                }
                else if (upWidth == upHeight)
                {
                    if (upWidth <= 500 && upHeight <= 500)
                    {
                        newBmp = new Bitmap(upWidth, upHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                        newWidth = upWidth;
                        newHeight = upHeight;
                    }
                    else
                    {
                        newBmp = new Bitmap(500, 500, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                        newWidth = 500;
                        newHeight = 500;
                    }
                }
                newBmp.SetResolution(72, 72);

                //Get the uploaded image width and height

                Int32 newX = 0; //Set the new top left drawing position on the image canvas

                Int32 newY = 0;

                //Create a new image from the uploaded picture using the Graphics class

                //Clear the graphic and set the background colour to white

                //Use Antialias and High Quality Bicubic to maintain a good quality picture

                //Save the new bitmap image using //Png// picture format and the calculated canvas positioning

                Graphics newGraphic = Graphics.FromImage(newBmp);

                try
                {
                    newGraphic.Clear(Color.Empty);

                    newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                    newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                    newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight);

                    newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);

                    //Show the uploaded resized picture in the image control

                    Image1.ImageUrl = filePath;

                    Image1.Visible = true;

                }
                catch (Exception ex)
                {
                    lblError.Text = ex.ToString();
                    throw ex;
                }
                finally
                {
                    upBmp.Dispose();

                    newBmp.Dispose();

                    newGraphic.Dispose();
                }
            }
            else
            {
                lblError.Text = “Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png.”;

            }
        }
    }
Good Luck

Blog at WordPress.com.