Example of gridview binding

Hello Friends,

Today i want to show you how to bind gridview? I have created one simple example of gridview binding.
To create example i have used VS 2010 and Adventures database.

First create one web site/web application and create one page. Paste below code in your aspx page.



       
       
       
       
       
       


Now, in .cs file use following code to bind grid view.

            try
            {
                DBM.SqlCommandEx sqlCmd = new DBM.SqlCommandEx(
                        "SELECT TOP 10 Person.BusinessEntityID, FirstName, LastName, AddressLine1, City, PostalCode" +
                        " FROM Person.Person" +
                        " INNER JOIN Person.BusinessEntity on BusinessEntity.BusinessEntityID = Person.BusinessEntityID" +
                        " INNER JOIN Person.BusinessEntityAddress on BusinessEntityAddress.AddressID = BusinessEntity.BusinessEntityID" +
                        " INNER JOIN Person.Address on Address.AddressID = BusinessEntityAddress.AddressID" +
                        " ORDER BY FirstName");

                gvData.DataSource = sqlCmd.GetDataTable();
                gvData.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }

Now, you are ready. Hope it will help to beginner to bind data grid.
I am attaching example and other needed file with this article.
Download it from here GridViewExample.rar

Set Scroll Position of DataGrid/GridView

JavaScript to set the scroll position of DataGrid.

<script language = "javascript">

///This function sets the scroll position of div to cookie.
function setScrollPos()
{
var divY = document.getElementById('div1').scrollTop;
document.cookie = "divPos=!*" + divY + "*!";
}

///Attaching a function on window.onload event.
window.onload = function()
{
var strCook = document.cookie;
if(strCook.indexOf("!~")!=0)
{
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS+2,intE);
document.body.scrollTop = strPos;
}

/// This condition will set scroll position od <div>.
if(strCook.indexOf("!*")!=0)
{
var intdS = strCook.indexOf("!*");
var intdE = strCook.indexOf("*!");
var strdPos = strCook.substring(intdS+2,intdE);
document.getElementById('div1').scrollTop = strdPos;
}
}

/// Function to set Scroll position of page before postback.
function SetScrollPosition()
{
var intY = document.body.scrollTop;
document.cookie = "yPos=!~" + intY + "~!";
}

/// Attaching   SetScrollPosition() function to window.onscroll event.
window.onscroll = SetScrollPosition;
</script>

In DIV Tag add the onscroll=”setScrollPos();”.

For Example

<DIV id="div1" style="OVERFLOW: auto; WIDTH: 100%; BORDER-TOP-STYLE: none; BORDER-RIGHT-STYLE: none;
BORDER-LEFT-STYLE: none; HEIGHT: 200px; BORDER-BOTTOM-STYLE: none" onscroll="setScrollPos();">

Place DataGrid here...

</DIV>