Feb 28, 2014

Export DataGridview To Excel

See the code

References:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.IO;

Code for button for exporting to Excel
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = "export.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
    //ToCsV(dataGridView1, @"c:\export.xls");
    ToCsV(dataGridView1, sfd.FileName); // Here dataGridview1 is your grid view name
} 


Function for exporting to Excel:
private void ToCsV(DataGridView dGV, string filename)
{
        string stOutput = "";
        // Export titles:
        string sHeaders = "";

        for (int j = 0; j < dGV.Columns.Count; j++)
            sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";
        stOutput += sHeaders + "\r\n";
        // Export data.
        for (int i = 0; i < dGV.RowCount - 1; i++)
        {
            string stLine = "";
            for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
                stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "\t";
            stOutput += stLine + "\r\n";
        }
        Encoding utf16 = Encoding.GetEncoding(1254);
        byte[] output = utf16.GetBytes(stOutput);
        FileStream fs = new FileStream(filename, FileMode.Create);
        BinaryWriter bw = new BinaryWriter(fs);
        bw.Write(output, 0, output.Length); //write the encoded file
        bw.Flush();
        bw.Close();
        fs.Close();
}


Feb 6, 2014

Sample Database Class

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

Nov 2, 2013

Avoid submit event Refresh in Asp.net

'Declare variables for use
    Private _refreshState As Boolean
    Private _isRefresh As Boolean


'Functions to Use
#Region " ISREFRESH "
    Protected Overrides Sub LoadViewState(ByVal savedState As Object)
        Dim AllStates As Object() = savedState
        MyBase.LoadViewState(AllStates(0))
        _refreshState = Boolean.Parse(AllStates(1))
        _isRefresh = _refreshState = Session("__ISREFRESH")
    End Sub

    Protected Overrides Function SaveViewState() As Object
        Session("__ISREFRESH") = _refreshState
        Dim AllStates() As Object = New Object(2) {}
        AllStates(0) = MyBase.SaveViewState
        AllStates(1) = Not (_refreshState)
        Return AllStates
    End Function
#End Region

'Call function in Button Click Event
Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnLogin.Click

      If _isRefresh = True Then
            Exit Sub
      End If

End Sub

Aug 19, 2013

How to Save and Retrieve File in SQL Server Table

1.)  Design

Save and Retrieve File in SQL Table :
Select File To Upload :
File ID to Download :

2.) Table
  
ID
FileName
Extension
Content
1
ShowMIS_BODRptS
.PDF
<Binary data>
2
a.xls
.xls
<Binary data>
3
test.txt
.txt
<Binary data>
4
test.sql
.sql
<Binary data>
5
ShowMIS_BODRptS
.pdf
<Binary data>


Jun 19, 2013

LINQ to SQL: Basic Concepts and Features


By : ,


In this article we will see how to use LINQ to interact with a SQL Server database, or in other words, how to use LINQ to SQL in C#.
In this article, we will cover the basic concepts and features of LINQ to SQL, which include:
  • What is ORM
  • What is LINQ to SQL
  • What is LINQ to Entities
  • Comparing LINQ to SQL with LINQ to Objects and LINQ to Entities
  • Modeling the Northwind database in LINQ to SQL
  • Querying and updating a database with a table
  • Deferred execution
  • Lazy loading and eager loading
  • Joining two tables
  • Querying with a view
Use above (Ref) link to to read article.

Jun 11, 2013

All Browser Supporting Tag for Asp.net Website

Below code paste in Head section of the Page

<head id="Head1" runat="server">
    <title>:: My Home ::</title>
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
      <meta content="blendTrans(Duration=0.50)" http-equiv="Page-Exit" />
      <meta http-equiv="Page-Enter" content="blendTrans(Duration=0.50)" />
</head>

Add Below code in File (VB) of Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Request.UserAgent.IndexOf("AppleWebKit") > 0 Then
            Request.Browser.Adapters.Clear()
        End If
    End Sub

    Protected Overrides Sub AddedControl(ByVal control As Control, ByVal index As Integer)
        ' This is necessary because Safari and Chrome browsers don't display the Menu control correctly.
        ' Add this to the code in your master page.
        If Request.ServerVariables("http_user_agent").IndexOf("Safari", StringComparison.CurrentCultureIgnoreCase) <> -1 Then
            Me.Page.ClientTarget = "uplevel"
        End If

        MyBase.AddedControl(control, index)
    End Sub

May 30, 2013

JSON Tutorial

JSON Tutorial


JSON or JavaScript Object Notation, is a text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages. The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

Example: How to send JSON data to Web method  i.e. ‘GetData’
1) create New website in visual studio

2) Write Below code In java script as function
    function SendData() {
       
         var jsonObjects = {
        "items": [
            {
                "compId": "1","formId": "531"
            },
            {
                "compId": "5","formId": "77"
            },
            {
                "compId": "8","formId": "89"
            }
        ]
        };
       
        $.ajax({
            url: "Default.aspx/GetData",
            data: JSON.stringify(jsonObjects),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function(data) { return data; },
            success: function(data) {
                alert(data.d);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
            }
        });
    }

3) Now add new Button to call Method and send data to serverside

<asp:Button ID="Button4" runat="server" Text="Send JSON Data in Object(s)" OnClientClick="SendData();return false;" />



4) Import this libraries

using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Security;

5) Use this method to accept Json data and save it to RDBMS

[WebMethod]
public static string GetData(object items)
{
     //SINGLE OBJECT SAVE DATA

     List<object> lstItems = new           JavaScriptSerializer().ConvertToType<List<object>>(items);

     //now we can Acces lstItems values
     return "Send Data successfully." ;
}

What is the use of n-tier architecture and 3-tier architecture?

how to implement 3-tier architecture in asp.net using c#. 3-Tier architecture is also called layered architecture. Some people called it ...