Friday, 30 January 2015

Filter Row From DataTable using C#


Filter Row From DataTable using C#
 ----------------------------------------------
public static DataTable FilterRows(DataTable source, String filterString) 
{
DataTable result = source.Clone(); 
DataRow[] rows = source.Select(filterString); 
foreach (DataRow row in rows) 

result.ImportRow(row); 

return result; 

Wednesday, 14 January 2015

Get Column name by comma separated in sql server


DECLARE @TABLE_NAME VARCHAR(128)
DECLARE @SCHEMA_NAME VARCHAR(128)

-----------------------------------------------------------------------
-- *** User Customisation

-- Set up the name of the table here :
SET @TABLE_NAME = 'attorney'
-- Set up the name of the schema here, or just leave set to 'dbo' :
SET @SCHEMA_NAME = 'dbo'

-----------------------------------------------------------------------

DECLARE @vvc_ColumnName VARCHAR(128)
DECLARE @vvc_ColumnList VARCHAR(MAX)

IF @SCHEMA_NAME =''
  BEGIN
  PRINT 'Error : No schema defined!'
  RETURN
  END

IF NOT EXISTS (SELECT * FROM sys.tables T JOIN sys.schemas S
          ON T.schema_id=S.schema_id
          WHERE T.Name=@TABLE_NAME AND S.name=@SCHEMA_NAME)
  BEGIN
  PRINT 'Error : The table '''+@TABLE_NAME+''' in schema '''+
        @SCHEMA_NAME+''' does not exist in this database!'
  RETURN
  END

DECLARE TableCursor CURSOR FAST_FORWARD FOR
SELECT   CASE WHEN PATINDEX('% %',C.name) > 0
         THEN '['+ C.name +']'
         ELSE C.name
         END
FROM     sys.columns C
JOIN     sys.tables T
ON       C.object_id  = T.object_id
JOIN     sys.schemas S
ON       S.schema_id  = T.schema_id
WHERE    T.name    = @TABLE_NAME
AND      S.name    = @SCHEMA_NAME
ORDER BY column_id


SET @vvc_ColumnList=''

OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @vvc_ColumnName

WHILE @@FETCH_STATUS=0
  BEGIN
  SET @vvc_ColumnList = @vvc_ColumnList + @vvc_ColumnName

  -- get the details of the next column
  FETCH NEXT FROM TableCursor INTO @vvc_ColumnName

  -- add a comma if we are not at the end of the row
  IF @@FETCH_STATUS=0
    SET @vvc_ColumnList = @vvc_ColumnList + ','
  END

CLOSE TableCursor
DEALLOCATE TableCursor

PRINT 'Here is the comma separated list of column names :'
PRINT '--------------------------------------------------'
PRINT @vvc_ColumnList

Friday, 9 January 2015

Gridview To Pdf in C# & VB.NET

Gridview To Pdf in C# & VB.NET:
 C#

private void PDF_Export()

{

    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition",

        "attachment;filename=GridViewExport.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    GridView1.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());

    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();

    htmlparser.Parse(sr);

    pdfDoc.Close();

    Response.Write(pdfDoc);

    Response.End();

}



VB.Net

Private Sub PDF_Export()

  Response.ContentType = "application/pdf"

  Response.AddHeader("content-disposition", _

   "attachment;filename=GridViewExport.pdf")

  Response.Cache.SetCacheability(HttpCacheability.NoCache)

  Dim sw As New StringWriter()

  Dim hw As New HtmlTextWriter(sw)

  GridView1.AllowPaging = False

  GridView1.DataBind()

  GridView1.RenderControl(hw)

  Dim sr As New StringReader(sw.ToString())

  Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)

  Dim htmlparser As New HTMLWorker(pdfDoc)

  PdfWriter.GetInstance(pdfDoc, Response.OutputStream)

  pdfDoc.Open()

  htmlparser.Parse(sr)

  pdfDoc.Close()

  Response.Write(pdfDoc)

  Response.End()

End Sub

 Finally the method that one should not forget is the below otherwise the GridView export will throw the Error

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.



C#.Net

public override void VerifyRenderingInServerForm(Control control)

{

    /* Verifies that the control is rendered */

}

VB.Net

Public Overloads Overrides Sub VerifyRenderingInServerForm(

ByVal control As Control)

        ' Verifies that the control is rendered

End Sub
 

Gridview To Excel In C# & VB.NET

Gridview To Excel In C# & VB.NET:

C#

private void Excel_Export()

{

    Response.Clear();

    Response.Buffer = true;

    Response.AddHeader("content-disposition",

     "attachment;filename=GridViewExport.xls");

    Response.Charset = "";

    Response.ContentType = "application/vnd.ms-excel";

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    for (int i = 0; i < GridView1.Rows.Count; i++)

    {

        GridViewRow row = GridView1.Rows[i];

        //Apply text style to each Row

        row.Attributes.Add("class", "textmode");

    }

    GridView1.RenderControl(hw);



    //style to format numbers to string

    string style = @"<style> .textmode { mso-number-format:\@; } </style>";

    Response.Write(style);

    Response.Output.Write(sw.ToString());

    Response.Flush();

    Response.End();

}

   
                 

VB.Net



Private Sub Excel_Export()

   Response.Clear()

   Response.Buffer = True

   Response.AddHeader("content-disposition", _

    "attachment;filename=GridViewExport.xls")

   Response.Charset = ""

   Response.ContentType = "application/vnd.ms-excel"

   Dim sw As New StringWriter()

   Dim hw As New HtmlTextWriter(sw)

   GridView1.AllowPaging = False

   GridView1.DataBind()

   For i As Integer = 0 To GridView1.Rows.Count - 1

     Dim row As GridViewRow = GridView1.Rows(i)

    'Apply text style to each Row

     row.Attributes.Add("class", "textmode")

   Next

   GridView1.RenderControl(hw)



   'style to format numbers to string

   Dim style As String = "<style> .textmode " _

     & "{ mso-number-format:\@; } </style>"

   Response.Write(style)

   Response.Output.Write(sw.ToString())

   Response.Flush()

   Response.End()

End Sub

 Finally the method that one should not forget is the below otherwise the GridView export will throw the Error

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.



C#.Net

public override void VerifyRenderingInServerForm(Control control)

{

    /* Verifies that the control is rendered */

}

VB.Net

Public Overloads Overrides Sub VerifyRenderingInServerForm(

ByVal control As Control)

        ' Verifies that the control is rendered

End Sub
 

Gridview To Word Export in C# & VB.NET

 Gridview To Word Export in C# & VB.NET:
C#

private void Word_Export()

{

    Response.Clear();

    Response.Buffer = true;

    Response.AddHeader("content-disposition",

      "attachment;filename=GridViewExport.doc");

    Response.Charset = "";

    Response.ContentType = "application/vnd.ms-word ";

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    GridView1.RenderControl(hw);

    Response.Output.Write(sw.ToString());

    Response.Flush();

    Response.End();

}



VB.Net

Private Sub Word_Export()

   Response.Clear()

   Response.Buffer = True

   Response.AddHeader("content-disposition", _

    "attachment;filename=GridViewExport.doc")

   Response.Charset = ""

   Response.ContentType = "application/vnd.ms-word "

   Dim sw As New StringWriter()

   Dim hw As New HtmlTextWriter(sw)

   GridView1.AllowPaging = False

   GridView1.DataBind()

   GridView1.RenderControl(hw)

   Response.Output.Write(sw.ToString())

   Response.Flush()

   Response.End()

End Sub

 Finally the method that one should not forget is the below otherwise the GridView export will throw the Error

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.



C#.Net

public override void VerifyRenderingInServerForm(Control control)

{

    /* Verifies that the control is rendered */

}

VB.Net

Public Overloads Overrides Sub VerifyRenderingInServerForm(

ByVal control As Control)

        ' Verifies that the control is rendered

End Sub
 

Automatic Logout when session is timeout in vb.net

Automatic Logout when session is timeout in vb.net:

To do this I am use a user control and use the user control in master page.

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="AutoLogout.ascx.vb" Inherits="UserControl_AutoLogout" %>
<script type="text/javascript">
    var timeRefresh;
    var timeInterval;
    var currentTime;
    var expressTime;

    expressTime = "<%=ExpressDate %>";
    currentTime = "<%=LoginDate %>";
    setCookie("express", expressTime);
    timeRefresh = setInterval("Refresh()", 30000);

    // Refresh this page to check session is expire or timeout.
    function Refresh() {
        var current = getCookie("express");
        var date = current.split(" ")[0];
        var time = current.split(" ")[1];
        var scriptDate = new Date();
        var year = scriptDate.getFullYear();
        var month = scriptDate.getMonth() + 1;
        var day = scriptDate.getDate();
        var hour = scriptDate.getHours();
        var min = scriptDate.getMinutes();
        var second = scriptDate.getSeconds();
        if (Date.UTC(year, month, day, hour, min, second) >=
           Date.UTC(date.split("-")[0], date.split("-")[1], date.split("-")[2],
           time.split(":")[0], time.split(":")[1], time.split(":")[2])) {
            clearInterval(timeRefresh);
            Redirect();
        }
    }

    function Redirect() {
        window.location.replace("index.aspx?info=1");
    }

    // Retrieve cookie by name.
    function getCookie(name) {
        var arg = name + "=";
        var aLen = arg.length;
        var cLen = document.cookie.length;
        var i = 0;
        while (i < cLen) {
            var j = i + aLen;
            if (document.cookie.substring(i, j) == arg) {
                return getCookieVal(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
        }
        return;
    }

    function getCookieVal(offSet) {
        var endStr = document.cookie.indexOf(";", offSet);
        if (endStr == -1) {
            endStr = document.cookie.length;
        }
        return unescape(document.cookie.substring(offSet, endStr));
    }

    // Assign values to cookie variable.
    function setCookie(name, value) {
        document.cookie = name + "=" + escape(value);
    }
</script>
--------------------
VB Code:
Imports System.Globalization

Partial Public Class UserControl_AutoLogout
    Inherits System.Web.UI.UserControl

    Public LoginDate As String
    Public ExpressDate As String

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If HttpContext.Current.Session("uname") = Nothing Then
            Response.Redirect("index.aspx?info=0")
        End If

        ' '''Get user login time or last activity time.
        Dim date0 As DateTime = DateTime.Now
        LoginDate = date0.ToString("u", DateTimeFormatInfo.InvariantInfo).Replace("Z", "")
        Dim sessionTimeout As Integer = Session.Timeout
        Dim dateExpress As DateTime = date0.AddMinutes(sessionTimeout)
        ExpressDate = dateExpress.ToString("u", DateTimeFormatInfo.InvariantInfo).Replace("Z", "")

    End Sub
End Class
------------------
In master page add this:
<%@ Register src="~/UserControl/AutoLogout.ascx" tagname="AutoRedirect" tagprefix="uc1" %>

Add this in from tag:
<uc1:AutoRedirect ID="AutoRedirect1" runat="server" />

Set session timeout in web.config file:
<sessionState timeout="30"/>

Wednesday, 7 January 2015

Watermark in Textbox by javascript

 Watermark in Textbox by javascript:

Please write the script in aspx page:
 <script type="text/javascript">
        function WaterMarkFocus(txt, text) {
            if (txt.value == text) {
                txt.value = "";
                txt.style.color = "black";
            }
        }

        function WaterMarkBlur(txt, text) {
            if (txt.value == "") {
                txt.value = text;
                txt.style.color = "gray";
            }
        }
</script>

And write the code for Textbox:
<asp:TextBox ID="txtName" runat="server" Height="22px" Width="50px" Text="Name" onfocus="WaterMarkFocus(this,'Name')" onblur="WaterMarkBlur(this,'Name')"></asp:TextBox>


Nested GridView in ASP.NET ,C# (GridView Inside a GridView)

Nested GridView in ASP.NET ,C# (GridView Inside a GridView) :

In Master GridView (GV_Master) I’ll show you the Customer’s details i.e.,CustomerId, CustomerName and CustomerAddress from ‘Customer_Details’ table.

Then in the Child GridView(GV_Child) I’ll show you Order details of corresponding to the Customers i.e. CustomerID.

In Master GridView (GV_Master) I’ll show you the Customer’s details i.e., CustomerName and CustomerAddress from ‘Customer_Details’ table. Then in the Child GridView(GV_Child) I’ll show you Order details of corresponding Customers i.e. CustomerIDand.

Creating Master GridView (GV_Master):
<asp:GridView ID="GV_Master" runat="server"
          AutoGenerateColumns="false" DataKeyNames="CustomerId"
          OnRowDataBound="GV_Master_OnRowDataBound" CssClass="Grid">
    <columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerName " HeaderText="Customer Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerAddress " HeaderText="Customer Address " />
    </columns>
  </asp:GridView>

So, now it shows only two column i.e. CustomerName and CustomerAddress . Now, I’ll insert ‘plus sign image’ to the First Column of every row. As because, when I’ll click this ‘plus sign image’ then the Child GridView will displayed and the ‘plus sign image’ will be the ‘minus sign image’. And when I’ll click the ‘minus sign image’ the Child GridView will remove from our sight and ‘minus sign image’ becomes the ‘plus sign image’ like toggle. So, I’ve to take an ItemTemplate within a TemplateField inside the Columns at first position

Please See The Code:
<asp:GridView ID="GV_Master" runat="server" AutoGenerateColumns="false" DataKeyNames="CustomerId"
    OnRowDataBound="GV_Master_OnRowDataBound" CssClass="Grid">
    <columns>
        <asp:TemplateField ItemStyle-Width="20px">
            <itemtemplate>
                <a href="java<!-- no -->script:divexpandcollapse('div<%# Eval(">
                    <img id="imgdiv<%# Eval(" alt="Details" src="images/plus.png" />
                </a>
       
               <asp:BoundField ItemStyle-Width="150px" DataField="CustomerName "    HeaderText="Customer Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerAddress " HeaderText="Customer Address " />
            </itemtemplate>
    </columns>
</asp:GridView>


Now, you see that I’ve linked a JavaScript function to the ‘plus sign image’ which does the all functionality what I’ve told above against the Click event of the ‘plus sign image’. This JavaScript function takes the Div name in which the Child GridView exists. There will be one Child GridView for each row of the Master GridView. So, the Div id must be different. That’s why I concatenate Div id with CustomerId and there will one ‘plus sign image’ for each row of the Master GridView, so I also concatenate the img id with CustomerId. Now lets add the Div just after the link of the ‘plus sign image’ and implement Child GridView under that Div:

<asp:GridView ID="GV_Master" runat="server"
           AutoGenerateColumns="false" DataKeyNames="CustomerId"
    OnRowDataBound="GV_Master_OnRowDataBound" CssClass="Grid">
    <columns>
        <asp:TemplateField ItemStyle-Width="20px">
            <itemtemplate>
                <a href="java<!-- no -->script:divexpandcollapse('div<%# Eval(">
                    <img id="imgdiv<%# Eval(" alt="Details" src="images/plus.png" />
                </a>               
                 <div id='div<%# Eval("CustomerId")%>' style="display: none; left: 5px; overflow: auto;">
                    <asp:GridView ID="GV_Child"
                            runat="server" AutoGenerateColumns="false"
                            DataKeyNames="CustomerId" CssClass="ChildGrid">
                        <columns>
                            <asp:BoundField ItemStyle-Width="150px"
                              DataField="OrderId" HeaderText="Order Id" />
                            <asp:BoundField ItemStyle-Width="150px"
                              DataField="OrderDate" HeaderText="Order Date" />
                        </columns>
                   
                </div>
            </itemtemplate>
       
      <asp:BoundField ItemStyle-Width="150px" DataField="CustomerName "    HeaderText="Customer Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerAddress " HeaderText="Customer Address " />
    </columns>
</asp:GridView>

Lets see the little JQuery which checks whether the ‘plus sign image’ source contains the path of the ‘plus sign’ image or ‘minus sign’ image and do said functionality accordingly:


function divexpandcollapse(divname) {
    var img = "img" + divname;
    if ($("#" + img).attr("src") == "images/plus.png") {
        $("#" + img)
    .closest("tr")
    .after("" + $("#" + divname)
    .html() + "")
        $("#" + img).attr("src", "images/minus.png");
    } else {
        $("#" + img).closest("tr").next().remove();
        $("#" + img).attr("src", "images/plus.png");
    }
}

Now the client side part is over. The main part is how you fill the Child GridView? Don’t worry, there is an event which is triggered when there is one container control within the row of the GridView. The event is OnRowDataBound. And I’ve already added this event to the Master GridView properties and the name of event handler is: GV_Master_OnRowDataBound. And we also fill the Master GridView in the Page_Load() event. So lets implement:

Code Behind(C#):
protected void Page_Load(object sender, EventArgs e)
{
    GV_Master.DataSource =
      SelectData("SELECT  CustomerId, ContactName, CustomerAddress FROM Customers_Details");
    grdViewCustomers.DataBind();
}

private DataTable SelectData(string sqlQuery)
{
    string connectionString =
      System.Web.Configuration.WebConfigurationManager.ConnectionStrings[
      "con"].ConnectionString;
    using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, connectionString))
    {
        DataTable dt = new DataTable("Customers_Details");
        sqlDataAdapter.Fill(dt);
        return dt;
    }
}

protected void GV_Master_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string customerId = grdViewCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
        GridView gvChild= (GridView)e.Row.FindControl("GV_Child");
        grdViewOrdersOfCustomer.DataSource = SelectData(
          "SELECT CustomerId, OrderId, OrderDate FROM Orders_Details WHERE CustomerId='" +
          customerId + "'");
        gvChild.DataBind();
    }
}


Monday, 5 January 2015

Working With Multiple DataKey in Gridview

Aspx Page:

<asp:GridView ID="GV_Report" runat="server" BackColor="White" BorderColor="White"
                        BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" AutoGenerateColumns="False"
                        GridLines="None" Width="100%" DataKeyNames="district_code,ro_code,query_no,query_year">
                        <Columns>

                    </asp:GridView>

.VB Page

 For Each row As GridViewRow In GV_Report.Rows
          
            DistrictCode = GV_Report.DataKeys(row.RowIndex).Values(0).ToString()
            ROCode = GV_Report.DataKeys(row.RowIndex).Values(1).ToString()
            QueryNo = GV_Report.DataKeys(row.RowIndex).Values(2).ToString().Substring(4, 10)
            QueryYear = GV_Report.DataKeys(row.RowIndex).Values(3).ToString()

         //Your Method
        Next