Wednesday 11 May 2011

Bulk Editing with Gridview


1)
 What is issue
Asp.net gridview provides the functionality of editing but at a time only single row you have to edit a row first then update it will make a round to server rebind whole grid and then you can edit next row.
Today i was thinking if it is scenario that all the rows should be in edit mode on load time and user can edit all the rows and update them at a time.i have a littil R&D on this topic and found two solution one is explained here and second will be next time inshalla.the second way is two make a customize contorl which inherits from systm.web.ui.webcontrol.gridview.and override some functions as per required.
so here is the first one
2)
 Explanation
following steps are involved in this tutorial.
 1 make a new website with one default.aspx page.
 2 drop a gridview toolbox.
 3 drop a button.
 4 drop a sqldatasource with enable of insert,update,delete.
 i have a table "Employes" in my database with columns ('P_ID','Name','Age','City','Departement')
3)
 Demonstration
In columns add one asp:boundfield, and four asp:templatefield.
In bound field P_ID will be displayed it will be readonly and datakey of gridview.
In templatefield add itemtemplate and in itemtemplate add textbox controls.so the grid will be shown in edit mode on load time.
on rowdatabound event of gridview store the values of orignal table in a datatable.
write a method which will check the row is edited or not.
on the click event of update button check each row if edited then update that row.
here is code with further explanation.
4)
 Explaination
now do follow the steps in explanation step.
 1 make a demo website.
 2)Add a gridview controle with following code.
 <asp:GridView ID="grdEmployes" runat="server" DataSourceID="grdEmployeDS" OnRowDataBound="grdNames_RowDataBound1"
                AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="P_ID">
                <Columns>
                    <asp:BoundField DataField="P_ID" HeaderText="P_ID" InsertVisible="False" ReadOnly="True"
                        SortExpression="P_ID" />
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name") %>'></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:TextBox ID="txtAge" runat="server" Text='<%#Bind("Age") %>'></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField SortExpression="City">
                        <ItemTemplate>
                            <asp:TextBox ID="txtCity" runat="server" Text='<%#Bind ("City") %>'></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField SortExpression="Departement">
                        <ItemTemplate>
                            <asp:TextBox ID="txtDepartment" runat="server" Text='<%#Bind("Departement") %>'></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
 on row databound event of grid make a copy of non edited datatable.here is code in .cs file
 protected void grdNames_RowDataBound1(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (tableCopied == false)
                {
                    orignalTable = ((DataRowView)e.Row.DataItem).Row.Table;
                    ViewState["orignalData"] = orignalTable;
                    tableCopied = true;
                }
            }
        }
 3)add a update button
 In aspx file:
  <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />
 In codebehind file :
   protected void btnUpdate_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grdEmployes.Rows)
            {
                if (checkRow(row) == true)
                {
                    grdEmployes.UpdateRow(row.RowIndex, false);
                }
            }
        }

 here in if statement checkrow(row) is the mehtod which will check either row is edited or not.so i will explain it here first before further step.

 private bool checkRow(GridViewRow row)
        {
            int pid;
            string Name;
            string Age;
            string City;
            string Departement;
            DataTable table = (DataTable)ViewState["orignalData"];
            pid = Convert.ToInt32(grdNames.DataKeys[row.RowIndex].Value.ToString());
            TextBox txtName = (TextBox)row.FindControl("txtName");
            TextBox txtAge = (TextBox)row.FindControl("txtAge");
            TextBox txtCity = (TextBox)row.FindControl("txtCity");
            TextBox txtDepart = (TextBox)row.FindControl("txtDepartment");
            Name = txtName.Text;
            Age = txtAge.Text;
            City = txtCity.Text;
            Departement = txtDepart.Text;
            DataRow dr = table.Select(string.Format("P_ID={0}", pid))[0];
            if(!Name.Equals(dr["Name"].ToString()))return true;
            if(!Age.Equals(dr["Age"].ToString())) return true;
            if(!City.Equals(dr["City"].ToString())) return true;
            if(!Departement.Equals(dr["Departement"].ToString())) return true;
            return false;
        }
Normal Functionality here:








Bulk editing enabled here:

I will appreciat if someone enhance this functionality,and feel sorry if it is to feel confusing.                             

Thanks                                                                                                                                                         
Muhammad Khalil                                                                                                                                                                                                                                                     

Tuesday 26 April 2011

Sliding Banner with Jquery

It is very common to have a sliding banner in flash.I do try same with jquery.Here is a sample code with explanations:
My cenario is that if there are 5 pages in an application.then on each page, banner should be according to that page.Now first of all i get pageId on page_load and then according to this pageId i get image names from database.these images are stored in image folder in my root directory.if there is some href against a banner then the cursor get chang when it is on the banner.otherwise not.
all of these name are concatenated in a string.and then this strin is passed to client side.

<div id="divSlideShow" runat="server" style="display: none;">
<a id="banner1href"><img id="banner1" style="display: none;" /></a>
<a id="banner2href"><img id="banner2"style="display: none;" /></a>
</div>

In the above code i have declared two img controls.one of them is displayed at a time and other is display:none.
Here is my Jquery Code

<script type="text/javascript" language="javascript">
        var ImageToggle = "1";
        var slideimages=new Array(); //string of image name is splitted and stored in this array.
        var slideURLs=new Array(); // string of image url is splitted and stored in this array.
        var slideshowspeed = 10000; //this variable is used in setTimeout method as time interval.
        var whichimage = 0;             //this variable is used to assign specific image in array.
        var staticUrl='<%=StaticURLsString %>' //stores static url.
//this function set default cursor depending on  above variable 'StaticUrl'.
 function staticDivCursor()
        {
        if(staticUrl=='#')
            {
               $("#staticBanner").attr('style', "cursor:default;");
            }  
        }

        //this function fill image array 'slideimages'.

        function slideShowImages()
        {
            for (i=0;i<slideShowImages.arguments.length;i++)
            {
                slideimages[i]=new Image();
                slideimages[i].src=slideShowImages.arguments[i];
            }
        }
        //set URL according to image.
        function slideShowURLs()
        {
            for (i=0;i<slideShowURLs.arguments.length;i++)
            {
                slideURLs[i]=slideShowURLs.arguments[i];
            }
        }
//this is main function which slide images.
        function slideit()
        {
            if (!document.images)
            {
                return
            }
            if(ImageToggle=="1")
            {             
                $("#banner2").fadeOut("fast",function()
                                                    {
                                                    $("#banner1").fadeIn("fast",function(){
                                                    if(slideURLs[whichimage]=='#')
                                                    {
                                                    $("#banner1").attr('style', "cursor:default;");
                                                    }                                                   
                                                    });
                                                    });               
                $("#banner1").attr('src', slideimages[whichimage].src);
                $("#banner1href").attr('href', slideURLs[whichimage]);
                ImageToggle="2";
            }
            else if(ImageToggle=="2")
            {            
               $("#banner1").fadeOut("fast",function(){
                                                  $("#banner2").fadeIn("fast",function(){
                                                  if(slideURLs[whichimage]=='#')
                                                  {
                                                  $("#banner2").attr('style', "cursor:default;");
                                                  }
                                                  });
                                                  });
               $("#banner2").attr('src', slideimages[whichimage].src);
               $("#banner2href").attr('href', slideURLs[whichimage]);
                ImageToggle="1";
            }
            if (whichimage < slideimages.length - 1)
            {
                whichimage++;
            }
            else
            {
                whichimage = 0;
            }
            setTimeout("slideit()", slideshowspeed);
        } 
//as all the function are defined they are called here on documetn.ready stage.     
        $(document).ready(function()
        {       
            slideShowImages(<%=ImageString%>);
            slideShowURLs(<%=URLsString%>);
            slideit();
            staticDivCursor();               
        });
    </script>

if you feel me not a good explainer.then sorry for that but you may query where you feel confusing.and if there is something wrong and you have a effecient approach then i will appriciat if you share with me.
Thanx
Muhammad Khalil

Sunday 24 April 2011

Dynamicaly Generate Page Contents

Today it is Sunday and i am a free for a Little while so i am here to share my experience.last week i decided to make a website totally jquery base.and retrieve data through json.i was thinking to have a single page in whole site and depending on user input different controls should be generated on run time.so here is a little start.

First of all add following libraries in my folder in root directory.

1)   <script src="inc/jquery-1.5.2.min.js" language="javascript"></script>

 2)   <script src="inc/jquery-ui-1.8.11.custom.min.js" language="javascript"></script>

1st one is the basic jquery minified library containing all the basic requirements to implement jQuery.
2nd is user interface library if you have to use draggable() droppable() like functionality the add this one.



 <script language="javascript" type="text/javascript">
        $(document).ready(function() {
 /////////animate images//////////
            $(".image").hover(function() {
                $(this).stop().animate({ height: "230px", width: "230px" }, "fast");
            }, function() { $(this).stop().animate({ height: "200px", width: "200px" }, "fast"); })
            $(".pd_photo").draggable({ containment: "#pd_container" });
            $(".pd_photo").css({ "left": Math.floor(Math.random() * 100) + 'px', "top": Math.floor(Math.random() * 50) + 'px' });
            $(".pd_photo").droppable();

 ///////bring image front/////////
            var highest = 0;
            function findHighestZIndex() {
                var photos = $container.find('.pd_photo');

                photos.each(function() {
                    var $photo = $(this);
                    var zindex = $photo.css('z-index');
                    if (parseInt(zindex) > highest) {
                        highest = zindex;
                    }
                    alert(highest);
                });
                return highest;
            }

var maxz = highest;
            $(".pd_photo").click(function() {
                $(this).css("z-index", maxz);
                maxz = maxz + 1;
            });


all of the above is simply animating my divs containing photos and setting their z-index on click.
now in the following code i have a string containing all the names of photos against a specific user from database.and in a method i split it on , base and then pass each img control a src property.

<script type="text/javascript">
                    function getimage()
                    {                       
                        var imagearray =new Array();
                        function getImages() {
                            for (i = 0; i < getImages.arguments.length-1; i++) {
                                                    imagearray[i] = getImages.arguments[i];
                               
                            }
                        }
                        getImages(<%=imagestr%>);
                       
                        $.each(imagearray, function() {
                            $("#pd_container").append('<div class="pd_photo"><div  style="position: relative"><img id="image" class="image" src="' + this + '" alt="" /><img id="close" src="Images/close.png" alt="Close" class="Close" /></div></div>');                   
                        }
                     )}
                     getimage();
                    
            </script>


in .append the number of div would depend on the images from database.
i don't know here what to explain so if you consider it according to your requirement and you feel it confusing post .then i would feel pleasure on your question in the way of comments.i am not something like master or expert in jquery so if you feel me wrong somewhere then i shall b thank full on your correctness.

Thanks,

Muhammad Khalil

Friday 15 April 2011

First Publish

wel commmmmmmm to all......Today while i was taking tea and thought about to share my daily work experince as i get much help by the post of my profession felllows.so why not should i...so here is my first one not informative post but starting point.I have to leave for office now after that i will share my daily work experince.