Friday, 27 March 2015

URL Mapping in ASP.NET

Use the code in web.config:

<?xml version="1.0"?>
<!--
     This tutorial is sponsored by http://www.ServerIntellect.com web hosting.
     Check out http://v4.aspnettutorials.com/ for more great tutorials!
  -->
<configuration>
    <system.web>
        <urlMappings enabled="true">
            <add url="~/Home" mappedUrl="~/home.aspx"/>
            <add url="~/About" mappedUrl="~/about.aspx"/>
        </urlMappings>
        <compilation debug="true" targetFramework="4.0"/>
    </system.web>
</configuration>


Use the code in ASPX page:
  <asp:HyperLink ID="hlHome" runat="server" NavigateUrl="~/Home">Home</asp:HyperLink>
        <br />
        <asp:HyperLink ID="hlAbout" runat="server"  NavigateUrl="~/About">About
</asp:HyperLink>

Determine Current Page Name with ASP.NET


This tutorial will demonstrate how you can easily determine the name of the current page you are on dynamically using ASP.NET ,C#.

protected void Page_Load(object sender, EventArgs e)
{
    //get the current page name
    string pageName = Path.GetFileNameWithoutExtension(Request.Path);
    //display current page name
    Response.Write(pageName);
}

Thursday, 19 March 2015

ASP.Net RequiredFieldValidator not working when OnClientClick event is added to Button

Here  I will explain how to solve the problem of RequiredFieldValidator not working when OnCientClick event is added to the Button in ASP.NET.

In order to make the RequiredFieldValidator work with OnClientClick we need to make use of Page_ClientValidate JavaScript function of ASP.Net Validators to perform validation explicitly.

HTML Markup
The HTML markup consists of an ASP.Net TextBox, a RequiredFieldValidator and a Button which has an OnClientClick event handler attached.
Name:
<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="Required" ControlToValidate="txtName"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" OnClientClick="return Validate();" />
<script type="text/javascript">
    function Validate() {
        return confirm('Do you want to submit data?');
    }
</script>


The Problem
The above code will display confirm and will not validate the TextBox using RequiredFieldValidator and the PostBack will happen even if the TextBox is left empty.

The Solution
Hence we need to make use of the Page_ClientValidate JavaScript function of ASP.Net Validators to perform validation explicitly as shown below.
Name:
<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="Required" ControlToValidate="txtName"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" OnClientClick="return Validate();" />
<script type="text/javascript">
    function Validate() {
        if (Page_ClientValidate()) {
            return confirm('Do you want to submit data?');
        }
        return false;
    }
</script>

Here first the Page_ClientValidate JavaScript function will make sure that all Validators have validated the form and the validation is successful then only it will raise the JavaScript confirmation.

How to use with Validation Groups
When using Validation Groups you need to simply pass the name of the Validation Group to the Page_ClientValidate JavaScript function and it will only verify the validations of the validators belonging to that group.
<script type="text/javascript">
    function Validate() {
        if (Page_ClientValidate('ValidationGroupName')) {
            return confirm('Do you want to submit data?');
        }
        return false;
    }
</script>

Tuesday, 17 March 2015

Concatenate Multiple Rows Within Single Row in SQL Server 2008

We can concatenate multiple rows within a single row using the predefined function STUFF available in SQL Server

Create 2 tables as in the following.

    Create Table Courses 
    ( 
      CourseID int primary key, 
      CourseName nvarchar(20) 
    ) 

INSERT INTO Courses(CourseId,CourseName) VALUES (1,'C#') 
INSERT INTO Courses(CourseId,CourseName) VALUES (2,'ASP.Net') 
INSERT INTO Courses(CourseId,CourseName) VALUES (3,'MVC') 
INSERT INTO Courses(CourseId,CourseName) VALUES (4,'WCF') 
INSERT INTO Courses(CourseId,CourseName) VALUES (5,'Share Point') 
INSERT INTO Courses(CourseId,CourseName) VALUES (6,'WPF') 
INSERT INTO Courses(CourseId,CourseName) VALUES (7,'SQL Server') 
INSERT INTO Courses(CourseId,CourseName) VALUES (8,'JQuery')

    CREATE TABLE StudentCourses 
    ( 
    StudentID int, 
    CourseID int 
    ) 

INSERT INTO StudentCourses(StudentID, CourseID) VALUES (1,1) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (1,3) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (1,5) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (2,2) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (2,4) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (2,5) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (3,3) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (3,6) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (4,7) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (4,8) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (5,1) 
INSERT INTO StudentCourses(StudentID, CourseID) VALUES (5,2)  

Execute this SQL Query to get the student courseIds separated by a comma.

    SELECT StudentID, 
    CourseIDs=STUFF 
    ( 
         ( 
           SELECT DISTINCT ', ' + CAST(CourseID AS VARCHAR(MAX)) 
           FROM StudentCourses t2  
           WHERE t2.StudentID = t1.StudentID  
           FOR XML PATH('') 
         ),1,1,'' 
    ) 
    FROM StudentCourses t1 
    GROUP BY StudentID 

Execute this query to get the student course names separated by a comma.

    SELECT StudentID, 
    CourseNames=STUFF 
    ( 
        ( 
          SELECT DISTINCT ', '+ CAST(g.CourseName AS VARCHAR(MAX)) 
          FROM Courses g,StudentCourses e  
          WHERE g.CourseID=e.CourseID and e.StudentID=t1.StudentID  
          FOR XMl PATH('') 
        ),1,1,'' 
    ) 
    FROM StudentCourses t1 
    GROUP BY StudentID 

Extract Files from Folder and Bind with Asp.Net GridView – C#

Access to files and folders in a remote server can be limited, but .Net has provided us with a variety of classes in its “System.IO” namespace, exclusively for safely manipulating and viewing files like ‘Word’, ‘Excel’, ‘PDF’, ‘JPG’ etc. Once files are extracted from the folder, we can bind all the files to an Asp.Net GridView control to allow users to view it on a web page.


ASPX Code:
<!DOCTYPE html>

<html>
<head>
    <title>Display | Bind Files from Folder to GridView</title>

    <style type="text/css">
        div
        {
            font:11px Verdana;
            width:750px;
        }

        .grid
        {
            width:100%;
            font:inherit;
            background-color:#FFF;
            border:solid 1px #525252;
        }
       
        .grid td
        {
            font:inherit;
            padding:2px;
            border:solid 1px #C1C1C1;
            color:#333;
            text-align:center;
            text-transform:uppercase;
        }
       
        .grid th {
            padding:3px;
            color:#FFF;
            background:#424242 url(grd.png) repeat-x top;
            border-left:solid 1px #525252;
            font:inherit;
            text-align:center;
            text-transform:uppercase;
        }
       
        #drop1
        {
            width:70px;
            padding:3px;
        }

    </style>
</head>

<body>
    <form id="form1" runat="server">

    <div>

        <%--LISTBOX SHOWING A LIST OF FILE TYPES.--%>
       
        <p>
            <asp:ListBox id="drop1" rows="3" runat="server">
                    <asp:ListItem selected="true">All</asp:ListItem>
                    <asp:ListItem>pdf</asp:ListItem>
                    <asp:ListItem>jpg</asp:ListItem>
                    <asp:ListItem>png</asp:ListItem>
                    <asp:ListItem>txt</asp:ListItem>
                    <asp:ListItem>doclt/asp:ListItem>
                </asp:ListBox>

                <input type="button" id="btShowFiles" onserverclick="btShowFiles_Click"
                    value="Show Files" runat="server" />
        </p>
      
        <%--ADD A GRIDVIEW WITH FEW COLUMNS--%>
        <asp:GridView ID="GridView1" CssClass="grid" GridLines="None" ShowFooter="true"
            AllowPaging="true" PageSize="5" AutoGenerateColumns="false"
            OnPageIndexChanging="GridView1_PageIndexChanging" runat="server">
               
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate><asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
                        </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="File Length">
                    <ItemTemplate><asp:Label ID="lblLen" runat="server" Text='<%#Eval("Length")%>'></asp:Label>
                        </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="File Extention">
                    <ItemTemplate><asp:Label ID="lblFileType" runat="server" Text='<%#Eval("Extension")%>'>
                        </asp:Label></ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Creation Date & Time">
                    <ItemTemplate><asp:Label ID="lblDateTime" runat="server" Text='<%#Eval("CreationTime")%>'>
                        </asp:Label></ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
       
        <%--A LABEL SHOWING NUMBER OF FILES FOUND IN THE FOLDER.--%>
        <p><asp:Label Text="" ID="lblMsg" runat="server"></asp:Label></p>

    </div>
    </form>

</body>
</html>

C# Code:
using System;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void btShowFiles_Click(object sender, EventArgs e)
    {
        ViewState["FileType"] = drop1.SelectedValue;     // GET THE FILE TYPE.
        GetFilesFromFolder();
    }

    // GRIDVIEW PAGING.
    protected void GridView1_PageIndexChanging(object sender,
        System.Web.UI.WebControls.GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GetFilesFromFolder();
    }

    private void GetFilesFromFolder()
    {
        // GET A LIST OF FILES FROM A SPECIFILED FOLDER.
        DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("my_demo_folder\\"));   
       
        FileInfo[] listfiles = objDir.GetFiles("*." + ((string)ViewState["FileType"] != "All" ?
            ViewState["FileType"] : "*"));

        if (listfiles.Length > 0)
        {
            // BIND THE LIST OF FILES (IF ANY) WITH GRIDVIEW.
            GridView1.Visible = true;
            GridView1.DataSource = listfiles;
            GridView1.DataBind();

            lblMsg.Text = listfiles.Length + " files found";   
        }
        else {
            GridView1.Visible = false ;
            lblMsg.Text = "No files found";
        }
    }
}

Monday, 16 March 2015

File Copy One Folder To Another in VB

To Copy File  from One Folder To Another use the following code:

 Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim sourcepath As String = "E:\Pdf_1525\Pdf\"
        Dim DestPath As String = "D:\Pdf_1525_Copy\"
        CopyDirectory(sourcepath, DestPath)
    End Sub

    Private Shared Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
        If Not Directory.Exists(destPath) Then
            Directory.CreateDirectory(destPath)
        End If

        For Each file__1 As String In Directory.GetFiles(Path.GetDirectoryName(sourcePath))
            Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
            File.Copy(file__1, dest)
        Next

        For Each folder As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
            Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder))
            CopyDirectory(folder, dest)
        Next
    End Sub

Friday, 13 March 2015

Nested GridView in ASP.NET

Default.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Gridview inside another Gridview</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        function shrinkandgrow(input) {
            var displayIcon = "img" + input;
            if ($("#" + displayIcon).attr("src") == "grow.png")
            {
                $("#" + displayIcon).closest("tr")
                .after("<tr><td></td><td colspan = '100%'>" + $("#" + input)
                .html() + "</td></tr>");
                $("#" + displayIcon).attr("src", "shrink.png");
            } else
            {
                $("#" + displayIcon).closest("tr").next().remove();
                $("#" + displayIcon).attr("src", "grow.png");
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="pub_id"
        OnRowDataBound="GridView1_OnRowDataBound" HeaderStyle-BackColor="#A52A2A" HeaderStyle-ForeColor="White" >
        <Columns>
        <asp:TemplateField ItemStyle-Width="20px">
        <ItemTemplate>
            <a href="JavaScript:shrinkandgrow('div<%# Eval("pub_id") %>');">
                <img alt="Details" id="imgdiv<%# Eval("pub_id") %>" src="grow.png" />
            </a>
            <div id="div<%# Eval("pub_id") %>" style="display: none;">
                <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" DataKeyNames="pub_id"
                HeaderStyle-BackColor="#FFA500" HeaderStyle-ForeColor="White">
                <Columns>
                    <asp:BoundField ItemStyle-Width="150px" DataField="title" HeaderText="Title" />
                    <asp:BoundField ItemStyle-Width="100px" DataField="type" HeaderText="Category" />
                    <asp:BoundField ItemStyle-Width="100px" DataField="price" HeaderText="Price" />
                </Columns>
                </asp:GridView>
            </div>
        </ItemTemplate>
        </asp:TemplateField>
            <asp:BoundField ItemStyle-Width="150px" DataField="pub_name" HeaderText="Publisher" />
            <asp:BoundField ItemStyle-Width="100px" DataField="state" HeaderText="State" />
            <asp:BoundField ItemStyle-Width="100px" DataField="country" HeaderText="Country" />
        </Columns>
    </asp:GridView>
    </div>
    </form>
</body>
</html>

C# Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class NestedGridView : System.Web.UI.Page
{
    string connetionString = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****";
    protected void Page_Load(object sender, EventArgs e)
    {
        string sql = "SELECT pub_id, pub_name,state,country FROM publishers";
        GridView1.DataSource = getData(sql);
        GridView1.DataBind();
    }
    protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string pub_id = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
            string sql = "SELECT pub_id, title, type,price FROM titles  WHERE pub_id='" + pub_id + "'";
            GridView pubTitle = (GridView)e.Row.FindControl("GridView2");
            pubTitle.DataSource = getData(sql);
            pubTitle.DataBind();
        }
    }
    private DataTable getData(string sql)
    {
        SqlDataAdapter adapter = new SqlDataAdapter();
        DataTable dTable = new DataTable();
        SqlConnection connection = new SqlConnection(connetionString);
        connection.Open();
        SqlCommand command = new SqlCommand(sql, connection);
        adapter.SelectCommand = command;
        adapter.Fill(dTable);
        adapter.Dispose();
        command.Dispose();
        connection.Close();
        return dTable;
    }
}

VB.Net Source Code
 Imports System.Drawing
Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
    Inherits System.Web.UI.Page
    Dim connetionString As String = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=zen412"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim sql As String = "SELECT pub_id, pub_name,state,country FROM publishers"
        GridView1.DataSource = getData(sql)
        GridView1.DataBind()
    End Sub
    Protected Sub GridView1_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim pub_id As String = GridView1.DataKeys(e.Row.RowIndex).Value.ToString()
            Dim sql As String = (Convert.ToString("SELECT pub_id, title, type,price FROM titles  WHERE pub_id='") & pub_id) + "'"
            Dim pubTitle As GridView = DirectCast(e.Row.FindControl("GridView2"), GridView)
            pubTitle.DataSource = getData(sql)
            pubTitle.DataBind()
        End If
    End Sub
    Private Function getData(ByVal sql As String) As DataTable
        Dim adapter As New SqlDataAdapter()
        Dim dTable As New DataTable()
        Dim connection As New SqlConnection(connetionString)
        connection.Open()
        Dim command As New SqlCommand(sql, connection)
        adapter.SelectCommand = command
        adapter.Fill(dTable)
        adapter.Dispose()
        command.Dispose()
        connection.Close()
        Return dTable
    End Function
End Class

Subtotal row in Gridview

 Sql:


select  distinct stor_id,ord_num,title_id,qty from sales
group by stor_id,ord_num,title_id,qty
  
From the result of the above sql, the program find the subtotal of each store and display in 
the GridView. After calculating the subtotal, we are forced to insert a new row after each 
store data and display the subtotal.

Default.aspx
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
 onrowdatabound="GridView1_RowDataBound"  onrowcreated="GridView1_RowCreated">
 <Columns>
    <asp:BoundField DataField="stor_id" HeaderText="stor_id" />
    <asp:BoundField DataField="ord_num" HeaderText="ord_num" />
    <asp:BoundField DataField="title_id" HeaderText="title_id" />
    <asp:BoundField DataField="qty" HeaderText="qty" ItemStyle-HorizontalAlign="Right"/>
 </Columns>
 </asp:GridView>
 </div>
 </form>
</body>
</html>
 
 
C# Source Code
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
 int qtyTotal = 0;
 int storid = 0;
 int rowIndex = 1;
 protected void Page_Load(object sender, EventArgs e)
 {
  SqlDataAdapter adapter = new SqlDataAdapter();
  DataSet ds = new DataSet();
  int i = 0;
  string sql = null;
  string connetionString = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****";
  sql = "select  distinct top 14 stor_id,ord_num,title_id,qty from sales group by stor_id,ord_num,title_id,qty";
  SqlConnection connection = new SqlConnection(connetionString);
  connection.Open();
  SqlCommand command = new SqlCommand(sql, connection);
  adapter.SelectCommand = command;
  adapter.Fill(ds);
  adapter.Dispose();
  command.Dispose();
  connection.Close();
  GridView1.DataSource = ds.Tables[0];
  GridView1.DataBind();
 }
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 {
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
   storid = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "stor_id").ToString());
   int tmpTotal = Convert.ToInt32 (DataBinder.Eval(e.Row.DataItem, "qty").ToString());
   qtyTotal += tmpTotal;
  }
 }
 protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
 {
  bool newRow = false;
  if ((storid > 0) && (DataBinder.Eval(e.Row.DataItem, "stor_id") != null))
  {
   if (storid != Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "stor_id").ToString()))
    newRow = true;
  }
  if ((storid > 0) && (DataBinder.Eval(e.Row.DataItem, "stor_id") == null))
  {
   newRow = true;
   rowIndex = 0;
  }
  if (newRow)
  {
   GridView GridView1 = (GridView)sender;
   GridViewRow NewTotalRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);
   NewTotalRow.Font.Bold = true;
   NewTotalRow.BackColor = System.Drawing.Color.Gray;
   NewTotalRow.ForeColor = System.Drawing.Color.White;
   TableCell HeaderCell = new TableCell();
   HeaderCell.Text = "Sub Total";
   HeaderCell.HorizontalAlign = HorizontalAlign.Left  ;
   HeaderCell.ColumnSpan = 3;
   NewTotalRow.Cells.Add(HeaderCell);
   HeaderCell = new TableCell();
   HeaderCell.HorizontalAlign = HorizontalAlign.Right;
   HeaderCell.Text = qtyTotal.ToString();
   NewTotalRow.Cells.Add(HeaderCell);
   GridView1.Controls[0].Controls.AddAt(e.Row.RowIndex + rowIndex, NewTotalRow);
   rowIndex++;
   qtyTotal = 0;
  }
 }
}
 
VB.Net Source Code
 
Imports System.Drawing
Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
    Inherits System.Web.UI.Page
    Dim qtyTotal As Integer = 0
    Dim storid As Integer = 0
    Dim rowIndex As Integer = 1
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim adapter As New SqlDataAdapter()
        Dim ds As New DataSet()
        Dim i As Integer = 0
        Dim sql As String = Nothing
        Dim connetionString As String = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****"
        sql = "select  distinct top 14 stor_id,ord_num,title_id,qty from sales group by stor_id,ord_num,title_id,qty"
        Dim connection As New SqlConnection(connetionString)
        connection.Open()
        Dim command As New SqlCommand(sql, connection)
        adapter.SelectCommand = command
        adapter.Fill(ds)
        adapter.Dispose()
        command.Dispose()
        connection.Close()
        GridView1.DataSource = ds.Tables(0)
        GridView1.DataBind()
    End Sub
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            storid = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "stor_id").ToString())
            Dim tmpTotal As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "qty").ToString())
            qtyTotal += tmpTotal
        End If
    End Sub
    Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        Dim newRow As Boolean = False
        If (storid > 0) AndAlso (DataBinder.Eval(e.Row.DataItem, "stor_id") IsNot Nothing) Then
            If storid <> Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "stor_id").ToString()) Then
                newRow = True
            End If
        End If
        If (storid > 0) AndAlso (DataBinder.Eval(e.Row.DataItem, "stor_id") Is Nothing) Then
            newRow = True
            rowIndex = 0
        End If
        If newRow Then
            Dim GridView1 As GridView = DirectCast(sender, GridView)
            Dim NewTotalRow As New GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert)
            NewTotalRow.Font.Bold = True
            NewTotalRow.BackColor = System.Drawing.Color.Gray
            NewTotalRow.ForeColor = System.Drawing.Color.White
            Dim HeaderCell As New TableCell()
            HeaderCell.Text = "Sub Total"
            HeaderCell.HorizontalAlign = HorizontalAlign.Left
            HeaderCell.ColumnSpan = 3
            NewTotalRow.Cells.Add(HeaderCell)
            HeaderCell = New TableCell()
            HeaderCell.HorizontalAlign = HorizontalAlign.Right
            HeaderCell.Text = qtyTotal.ToString()
            NewTotalRow.Cells.Add(HeaderCell)
            GridView1.Controls(0).Controls.AddAt(e.Row.RowIndex + rowIndex, NewTotalRow)
            rowIndex += 1
            qtyTotal = 0
        End If
    End Sub
End Class 
 

Check a column used in which Store Procedure in SQL

 To know Check a column used in which Store Procedure in SQL run the following script:

SELECT DISTINCT Name
FROM sys.
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Table_Name%'
AND OBJECT_DEFINITION(OBJECT_ID) LIKE '%Column_Name%';

Wednesday, 11 March 2015

List of months between date range in SQL

List of months between date range

DECLARE @DateStart DATETIME = '2013-07-01' -- 2013 July
DECLARE @DateEnd DATETIME = '2015-03-11'; -- 2015 March


select year(dates) as Year,month(dates) as MontNumber,
left(convert(char(10),dates,101),2) as MonthNumberLeadingZero,
datename(month,dates) as MonthName
from
(
select dateadd(month,number,@DateStart) as dates from master..spt_values
where type='p' and number between 0 and datediff(month,@DateStart,@DateEnd)
) as t

List of table having no Cluster Index in SQL

This script will show table without clustered index:

SELECT sys.tables.name, sys.indexes.name
FROM sys.tables left join sys.indexes
ON sys.tables.object_id = sys.indexes.object_id
WHERE isnull(sys.indexes.name,'')=''
ORDER BY sys.tables.name

List Of Table having No Index in SQL

This script  will show table without any index:

SELECT a.name FROM sys.tables a
left join sys.indexes b
ON a.object_id = b.object_id
WHERE isnull(b.name,'')=''
and not exists (select 1 from sys.indexes c where isnull(name,'')<>''
and c.object_id=b.object_id)
ORDER BY a.name

Identify store procedure which reference to a table

To identify table, trigger, view reference to a table, execute this
sp_depends 'My_Table'  -- My_Tableis the table name

Check Last Backup Date in SQL Server

To know the last database backup taken run the following script:

SELECT
T1.Name as DatabaseName,
COALESCE(Convert(varchar(12), MAX(T2.backup_finish_date), 101),'Not Yet Taken') as
LastBackUpTaken
FROM sys.sysdatabases T1 LEFT OUTER JOIN msdb.dbo.backupset T2
ON T2.database_name = T1.name
WHERE T2.TYPE='D'
GROUP BY T1.Name
ORDER BY T1.Name


To know the full details run the following script:

SELECT
T1.Name as DatabaseName,
backuptype=case type
when 'D' then 'Database'
when 'I' then 'Differential database'
when 'L' then 'Log'
when 'F' then 'File or filegroup'
when 'G' then 'Differential file'
when 'P' then 'Partial'
when 'Q' then 'Differential partial'
else 'NA'
end,
COALESCE(Convert(varchar(12), MAX(T2.backup_finish_date), 101),'Not Yet Taken') as
LastBackUpTaken
FROM sys.sysdatabases T1 LEFT OUTER JOIN msdb.dbo.backupset T2
ON T2.database_name = T1.name
GROUP BY T1.Name,T2.Type
ORDER BY T1.Name