A TEXT POST

asp.net custom gridview paging

Gridview Paging you could go with the standard and avoid the headaches and trial/errors a custom one brings. But sometimes it’s not up to you is it? There’s always that awesome web designer that thinks of an “awesome” paging for your gridviews..and here comes the headaches..lol

So I did a little searching and found a great tutorial that got me started. Here’s the link for that http://www.dotnetcurry.com/ShowArticle.aspx?ID=339


                private void SetPaging()
        {
                                               //check to see if my gridview has more than 1 page
            if (gridview1.PageCount > 1)
            {
 
                GridViewRow toprow = gridview1.TopPagerRow;
                PlaceHolder topplace = toprow.FindControl("PlaceHolder1") as PlaceHolder;
 
                Button toplbl = toprow.FindControl("lblIndicator") as Button;
               
                toplbl.Text = "Page " + (gridview1.PageIndex + 1).ToString() + " of " + gridview1.PageCount.ToString();
                topplace.Controls.Clear();
 
                                                               //amount of visible page buttons
                int maxpage = 4;
                                                              
                                                               //starts off at page 1
                int i = 1;
 
                                                               //if it within the first 4 pages then sets the max to pagecount
                if (gridview1.PageCount = 4)
                {
                                                                              //set i to current page +1 because page index's are 0 based
                    i = gridview1.PageIndex + 1;
                                                                            
                                                                              //if current page is greater than the set max page then you have to add on 4 more to your max page so you get then next four pages.
                    if (i > maxpage)
                        maxpage = i + 4;
                                                                            
                                                                              //this validates that if after adding on 4 more pages if your current max page is greater than total pages (page count) then just set maxpage to your pagecount
                    if (maxpage > gridview1.PageCount)
                        maxpage = gridview1.PageCount;
                }
 
                                                               //this loop creates each page button inside a placeholder
                for (int j = i; j  4)
                {
                    btnLastFour.CommandName = "Page";
                    btnLastFour.CommandArgument = (i - 4).ToString();
                    btnLastFour.Visible = true;
                }
                                                               //if you are past the first page then it enables the "first page" button.
                if (gridview1.PageIndex > 1)
                {
                    btnFirstPage.CommandName = "Page";
                    btnFirstPage.CommandArgument = "1";
                    btnFirstPage.Visible = true;
                }
 
                Button btnLastPage = toprow.FindControl("btnLastPage") as Button;
                Button btnNextFour = toprow.FindControl("btnNextFour") as Button;
                //here it's controled by page count not by page index
                                                               //if the page count has more than 4 pages then it enables the "next four" page button
                                                               //and also the last page button
                                                               if (gridview1.PageCount > 4)
                {
                    btnNextFour.CommandName = "Page";
                    btnNextFour.CommandArgument = (i + 4).ToString();
                                                                            
                    btnLastPage.CommandName = "Page";
                    btnLastPage.CommandArgument = gridview1.PageCount.ToString();
                }
                else
                {
                    btnNextFour.Visible = false;
                    lastbtn.Visible = false;
                }
                                                               //if your current maxpage is same as pagecount the doesn't show because you are at the end of your pages.
                if (maxpage == gridview1.PageCount)
                {
                    btnNextFour.Visible = false;
                    lastbtn.Visible = false;
                }
            }
        }
 
A TEXT POST

Asp.net linkbutton with hover image

Ok so in html there are thing that can be much simpler in asp.net it sometimes gets a little complicated. Well I needed to make an button control change when hover(passing the mouse on top of the button). So first off you can’t use a regular button, use a linkbutton. And mixing it up with a little javascript..success

  1. In the document head

    <script type="text/javascript">
    function over(id)
    {
        id.src="imagesfolder/imagehover.jpg";
    }
    function out(id)
    {
        id.src="imagesfolder/image.jpg";
    }
    </script>
  1. Your linkbutton

        <asp:LinkButton ID="myLinkButton" runat="server" >
                                               <img id="img1" src='imagesfolder/image.jpg' border='0' onmouseover="over(this);" onmouseout="out(this);" />
                               </asp:LinkButton>

so using an image inside your linkbutton and setting the “onmouseover” and “onmouseout” we can successfully change its image. so next time the web designer comes up with a hover effect for your buttons you won’t have to pull out your hair(like me)..lol

A TEXT POST

Fancybox load image on document ready

Ok so since I didn’t find this anywhere else thought I would share what I was able to successfully accomplish (sounds kinda cocky don’t it hehe..)

So I was asked that when a page loads to show and image but for the user to be able to click on the image and take them somewhere else..well I thought that would be easy but it actually took me a little while to figure out. First and foremost thank you Fancybox for creating such an awesome jquery plugin.

Well here it is:


<script type="text/javascript">
        $(document).ready(function () {
            $.fancybox('<div style="width:595px; 
height:421px;"><a href=
"http://www.iminds.pe/rice/index.html" 
target="_blank"><
img src="img/anuncio.jpg" border="0" alt=""/>
</a></div>',
            {
                autoDimensions  : true,
                width           : 595,
                height          : 421               
            });
            
        });
</script>

I had to specify a “div” and set style with widths and heights of the image so it would show. If you try it without it all you’ll get is a blank popup (that’s no bueno..)

ps: sorry for the way it’s formatted still trying to get the hang of how tumblr formats code(also taking suggestions on that) Well hit me up if you have any suggestions or just say thanks <— wouldn’t mind that either ;)

A TEXT POST

Godaddy Windows Hosting and index.aspx

So I think the majority of us when creating a new asp.net project we tend to use index.aspx as the default landing page and just FYI this is ok you don’t have to change that. Now one issue I came across is uploading this to my Godaddy windows hosting. [Here] you can see what files are “default” for them and that’s right “index.aspx” is not listed!! (http://support.godaddy.com/help/article/60)

So there are several routes you can go about and make it work. The method I chose and will post here is adding a few lines to the web.config file and enjoy your project online :)

So here it is, just add this and you’re good to go:


       <system.webServer>
        <defaultDocument>
            <files>
                <add value="index.aspx" />
            </files>
        </defaultDocument>
    </system.webServer>

This is inside your

<configuration>

Tags and no

<system.web> 

is not the same ;)

A TEXT POST

Deserialize XML and load datagridview

Have you ever needed to take an XML file and show their contents in a .net Grid? Yea eventually you will. So if you haven’t seen how to do it yet here’s a quick and easy step by step that should guide you from xml -> class -> gridview.

  1. XML File:

<?xml version="1.0" encoding="utf-8"?>
<UserCollection>
<Users>
  <User>
    <Name>John Doe</Name>
    <Birthday>01/01/1982</Birthday>
    <Address>123 test ave.</Address>
  </User>
  <User>
    <Name>John Doe</Name>
    <Birthday>01/01/1982</Birthday>
    <Address>123 test ave.</Address>
  </User>
  <User>
    <Name>John Doe</Name>
    <Birthday>01/01/1982</Birthday>
    <Address>123 test ave.</Address>
  </User>
</Users>
</UserCollection>
  1. Our Class file - this is the one that does all the work, it takes the collection of items in your XML and creates an array.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Media
{
    [Serializable()]
    public class User
    {
        [System.Xml.Serialization.XmlElement("Name")]
        public string Name { get; set; }

        [System.Xml.Serialization.XmlElement("Birthday")]
        public string Birthday { get; set; }

        [System.Xml.Serialization.XmlElement("Address")]
        public string Address { get; set; }
    }


    [Serializable()]
    [System.Xml.Serialization.XmlRoot("UserCollection")]
    public class UserCollection
    {
        [XmlArray("Users")]
        [XmlArrayItem("User", typeof(User))]
        public User[] User { get; set; }
    }
}
  1. In your form whenever you need to load your grid first we need to open the xml file, send it to our class and load the array.

UserCollection users = null;
string path = "users.xml";

XmlSerializer serializer = new XmlSerializer(typeof(UserCollection));

StreamReader reader = new StreamReader(path);
users = (UserCollection)serializer.Deserialize(reader);
reader.Close();
  1. finally

// finally bind the data to the grid
dataGridView1.DataSource = users.User;

And there you go. Now I’ve kept this as simple as possible but like in any project it can be wayyy more complicated. Hope this helps and look forward to any comments and additions.

A TEXT POST

PHP Excel Import to MySQL using PHPExcel

Ok so if you haven’t heard there is a great project called phpexcel. Now this has many functionality but I’ll just cover this well because I had to do it and didn’t know hehe. This is fairly easy(once you’ve figured it out)..

First we reference 2 files: PHPExcel.php and IOFactory.php. Important! Don’t touch these files unless you’re a complete expert.


//include the following 2 files
require '../class/PHPExcel.php';
    require_once '../class/PHPExcel/IOFactory.php';

Now we start we create an object from the file in this example $path is my filename that is in the server like this:

$path = "filefolder/myfile.xls";

So once we do that you can capture every detail of the file here I have Title, Highest Row, Highest Column, Highest ColumnIndex


    $objPHPExcel = PHPExcel_IOFactory::load($path);
    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
        $worksheetTitle     = $worksheet->getTitle();
        $highestRow         = $worksheet->getHighestRow(); // e.g. 10
        $highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);

With that info you can get the total number of columns


        $nrColumns = ord($highestColumn) - 64;

Now you can start displaying or saving to your db table. What I do here is show the user the worksheet title, how many columns and how many rows were imported.


        echo "<br>File ".$worksheetTitle." has ";
        echo $nrColumns . ' columns';
        echo ' y ' . $highestRow . ' rows.';

Now just so the user feels warm and fuzzy I go ahead and show them the data being imported by echoing line by line.


        echo '<br>Data: <table width="100%" cellpadding="3" cellspacing="0"><tr>';
        for ($row = 1; $row <= $highestRow; ++ $row) {
            
            echo '<tr>';
            for ($col = 0; $col < $highestColumnIndex; ++ $col) {
                $cell = $worksheet->getCellByColumnAndRow($col, $row);
                $val = $cell->getValue();
                if($row === 1)
                echo '<td style="background:#000; color:#fff;">' . $val . '</td>';
                else
                    echo '<td>' . $val . '</td>';
            }
            echo '</tr>';
        }
        echo '</table>';

Ok and finally(I know you’ve been waiting for this. Here is my insert into statement. I start at row 2 because obviously row 1 is your column headers. Note: if you don’t have headers then just use 1.


        for ($row = 2; $row <= $highestRow; ++ $row) {

Now I create an array to hold the value of each column.


        $val=array();
        for ($col = 0; $col < $highestColumnIndex; ++ $col) {
            $cell = $worksheet->getCellByColumnAndRow($col, $row);
            $val[] = $cell->getValue();
            
        }

And last but not least we insert.


            
            $sql="insert into tablename(column1, column2, column3, column4, column5, column6)
                  values('".$val[1] . "','" . $val[2] . "','" .  $val[3]. "','" . $val[4]. "','" . $val[5]. "','" . $val[6]. "')";
            //Run your mysql_query
        }
    }

}

And just like that you went from excel -> mysql and a nice display for the user :)

Important: you must make sure that your excel files has the same amount of columns as your insert statement, so I would recommend giving them a template to download first.

Now so you don’t think I’m some sort of super genious I actually had some help from Kaosforge Great site if you’re stuck.

Good luck :)

A TEXT POST

Jquery cookie set/retrieving and more

Ok so usually I surf the internet and don’t really look to help. But I came across an interesting question:

I am trying to use jquery cookie plugin on my website. what am i doing is show firstdiv on page load wait for some time and remove the firstdiv and show the secdiv and again wait for sometime, then remove the secdiv and finally show the maindiv. This works fine but want this to happen only when you visit the home page first time but not also for every subsequent visits during that active session. trying jquery to fix this issue.

this was from stackoverflow. So I decided to help. Now I know I put the solution on there but hey I wanna do it again ;)

at the top between your lines <head> </head> make sure to add the following:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://code.jquery.com/qunit/git/qunit.js"></script>
<script src="js/jquery.cookie.js"></script>

For this example I will just do a simple html content so after the body tag:


<div id="maindiv">this is main div</div>
<div id="firstdiv">this is first div</div>
<div id="secdiv">this is second div</div>

So the end result needed to be: if visitor is first time visitor, it goes firstdiv, secdiv, maindiv. Once same visitor has visited the site and decides to go back to home he only sees maindiv and not the other 2.

Now if you want to find out what the value is in your cookie:

var visitcookie = $.cookie('visitcookie');

then we set that in a variable like so


$(document).ready(function () {
   var visitcookie = $.cookie('visitcookie');
});

I prefer to work with switch statements the if/else..just easier and faster when processing. Now what are my case statements? First time = null (it hasn’t been set yet) After First time = default


$(document).ready(function () {
   var visitcookie = $.cookie('visitcookie');
   switch(visitcookie)
   {
        case 'first':
        case null:
             break;
        default:
             break;
  }
});

Now how do you set the value to the cookie, well first off it’s in the documentation but since you’re here I’ll give it to ya:

$.cookie('visitcookie', 'second', { expires: 7 , Path: "/"});

And that should be it, so here’s the complete code if you haven’t gone to stackoverflow yet. Now the stuff I’m doing here was related to the question asked but you can have it do what ever you want.


$(document).ready(function () {
   var visitcookie = $.cookie('visitcookie');
   switch(visitcookie)
   {
        case 'first':
        case null:
        document.getElementById('secdiv').style.display = 'none';
        document.getElementById('maindiv').style.display = 'none';
        setTimeout(function () {
            $("#firstdiv").fadeOut("slow", function () {
                $("#firstdiv").remove();
                document.getElementById('secdiv').style.visibility = "visible";
                $("#secdiv").show();
                $("#secdiv").fadeOut("slow", function () {
                    $("#secdiv").remove();
                    document.getElementById('maindiv').style.visibility = "visible";
                    $("#maindiv").show();
                    $.cookie('visitcookie', 'second', { expires: 7 , Path: "/"});
                    });
                });
            }, 2000);
        break;

        
        default:
            document.getElementById('firstdiv').style.display = 'none';
            document.getElementById('secdiv').style.display = 'none';
            document.getElementById('maindiv').style.visibility = "visible";
        break;
   }

});
 

Good luck and look forward to any questions.

A TEXT POST

Select gridview row with no select

Ok so traditionally when you create a gridview and load data you have a commandfield which you can set as select. That “select” can be a button, image or link. Everything is fine and dandy but what happens when they ask you for no buttons and to be able to click anywhere on the row to select it? What?!!

No worries here’s the answer ;)

  1. At the top you must add this, what this does is basically avoid a horrible validation error, that .net asks to enable.

//to avoid getting validation error when selecting row in gridview
protected override void Render(HtmlTextWriter writer)
{
     for (int i = 0; i < this.gvOptions.Rows.Count; i++)
     {
       ClientScript.RegisterForEventValidation(this.gridview.UniqueID, "Select$" + i);
     }
     base.Render(writer);
}

This is the error you would get if you don’t add this

Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
  1. In the aspx add a control as a select like this:

<asp:GridView ID="gvOptions" runat="server" AutoGenerateColumns="False" 
                onrowdatabound="gridview_RowDataBound" 
                onselectedindexchanging="gridview_SelectedIndexChanging">
                <Columns>
                      <asp:TemplateField Visible="false">
                         <ItemTemplate><asp:LinkButton runat="server" CommandName="select" ID="lnkSelect" Text="Select" /></ItemTemplate>
                      </asp:TemplateField>
                </Columns>
              </asp:GridView>

What that does is makes the gridview think it has a select field, but me and you know that it doesnt ;)

  1. Now we go to the RowDataBound and just set a couple of lines

protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //make sure it's a datarow and not header or footer
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //this makes the cursor look like the pointing finger instead of just the arrow(optional)
                e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';";
                //this selects the row
                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gridview, "Select$" + e.Row.RowIndex);

            }
        }
  1. Almost there, finally add a select index changing to capture the id of the row selected or any value from any cell:

protected void gridview_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
           //here i capture the first row cause that's where my ID is at..
            lblRowId.Text = gridview.Rows[e.NewSelectedIndex].Cells[1].Text;
        }

Note: Remember gridview columns are based on 0 so if you want the 2nd cell its actually [1]

I don’t think I have to mention this but just in case in code where you see “gridview” its the name of your gridview.. Pretty simple stuff huh?

Remember there’s no problems there’s just solutions ;)

A TEXT POST

PHP sendmail in IIS7 and Windows Server 2008

Alright after much searching through the internet finally found a tutorial that made everything work! I am not going to take credit for this because well I’m not as smart as this guy but did want to share his info.

for the full tutorial visit here

But overall the important part of that tutorial is the last, in you page the part that will send the email it needs to declare the smtp option like this:


<?php
ini_set('SMTP','localhost'); 
ini_set('sendmail_from', 'Your.Own@Address.com'); 

$to = 'Someone@somewhere.com';
$subject = 'Example subject';
$body = 'With an example body…'; 

mail($to, $subject , $body);
?>
To make Php send emails you need to make some configurations. Basically there are two options. In case you’re only going to use the SMTP server in a single project project and do not want it to interfere with other projects, you can set the configuration from within your php code by adding the following lines anywhere before sending the email:

ini_set('SMTP','localhost' ); 
ini_set('sendmail_from', 'administrator@YourWebsite.com');
Another way, to make global use of these settings, add the next lines to your php.ini file.

[mail function]
SMTP = localhost
sendmail_from = me@example.com

Again all credits to Timmy Kokke for this most awesome tutorial which helped me tremendously and hopefully it can help somebody else with similar or same situation.