Monday, 19 August 2013

How to Insert, Edit, Update and Delete Data in DataGridView using Windows Form C#.Net

To implement this concept you need to follow the below steps :

Step1 :
First you need to design a table in Sql Database to insert and retrieve the records in database.

Step2:
On the File menu, click New Project. Select Windows Forms Application as your project type.
Design the Form using controls from Toolbox.

Step3:
Now open the Form.cs page and write the following source code.

Form.cs Code :
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 System.Configuration;
using System.Data.SqlClient;

namespace savedatatomdf
{
    public partial class Form1 : Form
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sqlcon"].ConnectionString);
        public Form1()
        {
            InitializeComponent();
            Bind();

        }

        private void Clear()
        {
            txtName.Text = string.Empty;
            txtLocation.Text = string.Empty;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Insert Into Test_Data(Name,Location) Values (@Name,@Location)", con);
            cmd.Parameters.AddWithValue("Name", txtName.Text);
            cmd.Parameters.AddWithValue("Location", txtLocation.Text);
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Inserted sucessfully");
            Bind();
            Clear();
        }

        private void Bind()
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select * from Test_Data", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            SqlCommand delcmd = new SqlCommand();
            if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
            {
                delcmd.CommandText = "DELETE FROM Test_Data WHERE ID=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
                con.Open();
                delcmd.Connection = con;
                delcmd.ExecuteNonQuery();
                con.Close();
                dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                MessageBox.Show("Row Deleted");
            }
            Bind();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Update Test_Data set Name=@Name,Location=@Location Where(Name=@Name)", con);
            cmd.Parameters.AddWithValue("@Name", txtName.Text);
            cmd.Parameters.AddWithValue("@Location", txtLocation.Text);
            cmd.ExecuteNonQuery();
            MessageBox.Show("updated......");

            con.Close();
            Bind();
            Clear();
        }

        private void btnEdit_Click_1(object sender, EventArgs e)
        {
            int i;
            i = dataGridView1.SelectedCells[0].RowIndex;
            txtName.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
            txtLocation.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();
        }
    }
}



Step4:
Now build the Solution and Debug it for the output.



OUTPUT:






Tuesday, 13 August 2013

Gridview Sorting and Paging in asp.net C#

Design:

<asp:GridView ID="gdvRecords" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5" OnPageIndexChanging="gdvRecords_PageIndexChanging" AllowSorting="True" OnSorting="gdvRecords_Sorting">  </asp:GridView>





Paging:

     protected void gdvRecords_PageIndexChanging(object sender, GridViewPageEventArgs e)
     {
            GridView grdsample = (GridView)sender; //Get Current Gridview Object
            grdsample.PageIndex = e.NewPageIndex; //Set Page Index

            SqlConnection sqlcon = new SqlConnection(onnectionString);
            SqlCommand sqlcmdinsert = new SqlCommand("select * from Table",sqlcon);
            SqlDataAdapter sqlda = new SqlDataAdapter(sqlcmdinsert);         
            sqlda.Fill(dsAllData);
            gdvRecords.DataSource = dsAllData.Tables[0];
            gdvRecords.DataBind();
     }

Sorting:
   private const string ASCENDING = " ASC";
   private const string DESCENDING = " DESC";

   public SortDirection GridViewSortDirection
   {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

                return (SortDirection)ViewState["sortDirection"];
          }

            set { ViewState["sortDirection"] = value; }
   }


        private void SortGridView(string sortExpression, string direction)
        {
            DataTable dt;
            if (chkAll.Checked == true)
            {
                bindAllData();
                dt = dsAllData.Tables[0];
            }
            else
            {
                bindSearchData();
                dt = dsSearch.Tables[0];
            }
            //  You can cache the DataTable for improving performance
          

            DataView dv = new DataView(dt);
            dv.Sort = sortExpression + direction;

            gdvRecords.DataSource = dv;
            gdvRecords.DataBind();
        }

        protected void gdvRecords_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;

            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                SortGridView(sortExpression, DESCENDING);
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                SortGridView(sortExpression, ASCENDING);
            }
        }


Monday, 12 August 2013

Generate excel from datatable



 public static void ExportGridView(string fileName, DataTable A_objData)
        {
            try
            {
                DataTable objDataTable = A_objData;
                string attachment = string.Format("attachment; filename={0}", fileName);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.AddHeader("content-disposition", attachment);
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                System.Text.StringBuilder strOrderList = new System.Text.StringBuilder(1000);
                string strTest = "";
                int iColumnCount = A_objData.Columns.Count;
                for (int iIndex = 0; iIndex < iColumnCount; iIndex++)
                    strTest = strTest + objDataTable.Columns[iIndex].ToString() + "\t";
                strTest = strTest + "\n";
                strOrderList.Append(strTest);

                foreach (DataRow rows in objDataTable.Rows)
                {
                    strOrderList.Append(GetTabSeperatedString(rows, iColumnCount));
                }
                byte[] info = new System.Text.UTF8Encoding(true).GetBytes(strOrderList.ToString());

                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
                HttpContext.Current.Response.BinaryWrite(info);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static string GetTabSeperatedString(DataRow A_objDataTableRow, int A_iColumnCount)
        {
            string strRowValue = "";
            string strColumnValue = "";

            for (int iIndex = 0; iIndex < A_iColumnCount; iIndex++)
            {
                strColumnValue = A_objDataTableRow[iIndex].ToString();
                strColumnValue = strColumnValue.Replace("\n", " ");
                strColumnValue = strColumnValue.Replace("\r", " ");
                strColumnValue = strColumnValue.Replace("\t", " ");
                if (strColumnValue == "&nbsp;")
                    strColumnValue = " ";
                strRowValue += strColumnValue + "\t";
            }
            strRowValue += "\n";
            return strRowValue;
        }

Html 5 Registration page


//Styles


 <style>
        .signup-box {
            background: rgb(241, 241, 241);
            margin: 0px;
            padding: 25px;
            border: 1px solid rgb(229, 229, 229);
        }

        .inputFields {
            border-top-width: 1px;
            border-right-width: 1px;
            border-bottom-width: 1px;
            border-left-width: 1px;
            border-top-style: solid;
            border-left-style: solid;
            border-top-color: #bdc7d8;
            border-right-color: #bdc7d8;
            border-bottom-color: #bdc7d8;
            border-left-color: #bdc7d8;
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
            padding-top: 8px;
            padding-left: 10px;
            padding-bottom: 8px;
            padding-right: 10px;
            font-size: 18px;
        }

        .btnSave {
            color: #6BA64A;
            background-color: #6BA64A;
            border: 1px solid;
            border-radius: 5px 5px 5px 5px;
            color: rgb(255, 255, 255);
            cursor: pointer;
            display: inline-block;
            letter-spacing: 1px;
            position: relative;
            text-shadow: 0px 1px 2px rgba(0, 0, 0, 0.5);
            background: -moz-linear-gradient(center top, rgb(103, 174, 85), rgb(87, 136, 67)) repeat scroll 0% 0% rgb(105, 167, 78);
            box-shadow: 0px 1px 1px rgb(164, 227, 136) inset;
            border-color: rgb(59, 110, 34) rgb(59, 110, 34) rgb(44, 81, 21);
            font-size: 19px;
            line-height: 126%;
            min-width: 194px;
            padding: 7px 20px;
            text-align: center;
            font-family: 'Freight Sans Bold' !important;
            font-weight: normal !important;
            text-rendering: optimizelegibility;
        }

    </style>





<div class="signup-box" style="width:500px;border-top-right-radius:10px;border-top-left-radius:10px;border-bottom-left-radius:10px;border-bottom-right-radius:10px">

       <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
      <br />
  <fieldset>
  <legend><strong></strong></legend>
      <table>
         <tr>
            <td><input class="inputFields" type="text" runat="server" id="txtFirstName" placeholder="First Name" ></input>
            </td>
            <td style="margin-left:20px"><input type="text" runat="server" class="inputFields" id="txtLastName" placeholder="Last Name" ></input></td>
         </tr>
         <tr>
             <td colspan="2"><input style="width:430px"  type="text" runat="server" id="txtEducation" class="inputFields" placeholder="Education" ></input>
             </td>
         </tr>
         <tr>
            <td colspan="2"><input type="text" style="width:430px" runat="server" id="txtDesignation" class="inputFields" placeholder="Designation" ></input>
            </td>
         </tr>
     </table>
  </fieldset>
       <br />
   <fieldset>
      <legend><strong></strong></legend>
        <table>
            <tr>      
                <td colspan="2"><input style="width:430px" class="inputFields" type="text" runat="server" id="txtcompanyname" placeholder="Company Name" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input style="width:430px"  type="text" runat="server" id="txtemailcompany" class="inputFields" placeholder="Email id (company)" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="text" style="width:430px" runat="server" id="txtemailpersonal" class="inputFields" placeholder="Email id (Personal)" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="text" style="width:430px" runat="server" id="txtweburl" class="inputFields" placeholder="Web URL" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="text" style="width:430px" runat="server" id="txtsector" class="inputFields" placeholder="Sector" ></input>
                </td>
            </tr>
        </table>
 </fieldset>
 <br />
  <fieldset>
      <legend><strong></strong></legend>
        <table>
            <tr>      
                <td colspan="2"><input style="width:430px" class="inputFields" type="text" runat="server" id="txtAddress1" placeholder="Address 1" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input style="width:430px"  type="text" runat="server" id="txtAddress2" class="inputFields" placeholder="Address 2" ></input>
                </td>
            </tr>
            <tr>
           
                <td colspan="2"><input style="width:430px"  type="text" runat="server" id="txtcountry" class="inputFields" placeholder="Country" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input style="width:430px"  type="text" runat="server" id="txtstate" class="inputFields" placeholder="State" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input style="width:430px"  type="text" runat="server" id="txtcity" class="inputFields" placeholder="City" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="text" style="width:430px" runat="server" id="txtPinCode" class="inputFields" placeholder="Pin Code" ></input>
             
            </tr>
        </table>
 </fieldset>
      <br />
 <fieldset>
      <legend><strong></strong></legend>
        <table>
            <tr>      
                <td colspan="2"><input style="width:430px" class="inputFields" type="text" runat="server" id="txtteloffice" placeholder="Tel - Office" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input style="width:430px"  type="text" runat="server" id="txtExt" class="inputFields" placeholder="Ext" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="text" style="width:430px" runat="server" id="txtDirectNum" class="inputFields" placeholder="Direct Number" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="text" style="width:430px" runat="server" id="txtMobileNum" class="inputFields" placeholder="Mobile Number" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="text" style="width:430px" runat="server" id="txtMobileNum2" class="inputFields" placeholder="Mobile number 2" ></input>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="text" style="width:430px" runat="server" id="txtFax" class="inputFields" placeholder="Fax" ></input>
                </td>
            </tr>
        </table>
 </fieldset>
  <br />
      <table>
          <tr>
              <td> <asp:Button ID="btnSave" runat="server" CssClass="btnSave" Text="Save" OnClick="btnSave_Click" /></td>
              <td> <asp:Button ID="btnGenerateReport" runat="server" CssClass="btnSave" Text="Generate Report" OnClick="btnGenerateReport_Click" /></td>
          </tr>
      </table>
  </div>

Wednesday, 17 July 2013

Disable Right click in web page



If you have images (or anything else) on your website that want to protect then you can disable "right-click", which is how people get to the "Save As" option. This is not a perfect solution because anyone with advanced web experience can get around this, but it will stop most people from stealing anything you have a copyright on. You can use any (no need to use more than one) of the codes below to block "right-click" functionality, which will prevent most attempts to save your stuff.
Once you have selected the code from below that you want to use, follow these step…

1.    Paste the code you select from below into the box titled JavaScript for <head>


Disable Right-Click
<script type="text/javascript">
var message="Right-Click Disabled!";
function clickIE4(){
if (event.button==2){
alert(message); return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
</script>


Disable Right-Click Without an Alert Message
<script type="text/javascript">
var message="";
function clickIE() {
if (document.all) {
(message);return false;
}
}
function clickNS(e) {
if (document.layers||(document.getElementById&&!document.all)) {
if (e.which==2||e.which==3) {
(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS;
}else{
document.onmouseup=clickNS;
document.oncontextmenu=clickIE;
}
document.oncontextmenu=new Function("return false")
</script>

How to Disable Right-Click on Images Only
<script type="text/javascript">
var clickmessage="Right click disabled on images!"
function disableclick(e) {
if (document.all) {
if (event.button==2||event.button==3) {
if (event.srcElement.tagName=="IMG"){
alert(clickmessage);
return false;
}
}
}else if (document.layers) {
if (e.which == 3) {
alert(clickmessage);return false;
}
}else if (document.getElementById){
if (e.which==3&&e.target.tagName=="IMG"){
alert(clickmessage);
return false;
}
}
}
function associateimages(){
for(i=0;i<document.images.length;i++){
 document.images[i].onmousedown=disableclick;
}
}
if (document.all){
document.onmousedown=disableclick;
}else if (document.getElementById){
document.onmouseup=disableclick;
}else if (document.layers){
associateimages();
}
</script></document.images.length;i++){

Tuesday, 16 July 2013

Print pdf document in C#

This technical tip shows how to print a PDF document in program. Spire.Pdf allows you to print PDF document for your requirement at runtime with.NET. By using  Spire.PDF for .NET ,which is suitable for Console platform, WinForm ,and Asp.net ,you can easily load Pdf into these programs and print out this PDF document with the help of printDialog object. The printing mode of this component support background printing mode without intervention and interaction. According to Spire.pdf, you can freely switch printer, select print page, and set relative properties while printing PDF files in C#

In this blog , I will take console platform as an example to share my tips about how to print a PDF document in C#. Here we go :

Procedures:

 Step1: For printing a PDF document, firstly I created a new project in VS .Then set its target framework to be .NET framework 2.0.

 Step2: I instantiated an Spire.Pdf. PdfDocument object and load PDF document by calling its method LoadFromFile:

            // Instantiate an object of PdfDocument
                PdfDocument doc = new PdfDocument();  
           
                string pdfFile = “sample.pdf”;

              //load PDF document
                doc.LoadFromFile(pdfFile);              

                //Default printing mode without interaction (default printer to print all pages of the document)

Step3:  After what I mentioned above, it’s time for calling the method of PdfDocumen.PrintDocument.Print(). By using default printer, printing this PDF document of all pages can be realized without interaction. Besides printing PDF , i am happy to tell you that this printing mode is also suitable for Web printing in C# :

                  C#

                 doc.PrintDocument.Print();

                //Interaction printing mode(page range,printer,and properties of printing can be freely to selected and set)



Step4 :  The final step to finish printing PDF was a little complicated in C#, because i need instantiate an object of printDialog and set its relative printing properties before calling its method.   Besides ,  at the same time,set Spire.Pdf.pdfDocument relative printing properties as well. Here,the key point to print PDF ,which is what I extremely want to emphasize, is the necessity of combination between printDialog object and PdfDocument.PrintDocument while in this process. Without printDialog object, to print PDF is in vain . At last i just can call method PdfDocument.PrintDocument.print to start print PDF document:

 
                PrintDialog dialogPrint = new PrintDialog();

                dialogPrint.AllowPrintToFile = true;

                dialogPrint.AllowSomePages = true;

                dialogPrint.PrinterSettings.MinimumPage = 1;

                dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;

                dialogPrint.PrinterSettings.FromPage = 1;

                dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;



The Entire Code Snippet:

Please take a look over the following code snippet for this approach:

C#:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Drawing.Printing;

using Spire.Pdf;

namespace PdfPrint

{

class Program

{

[STAThread()]

static void Main(string[] args)

{

// Instantiate an object of PdfDocument

PdfDocument doc = new PdfDocument();

string pdfFile = “sample.pdf”;

//load PDF document

doc.LoadFromFile(pdfFile);

//Default printing mode without interaction (default printer to print all pages of the document)

doc.PrintDocument.Print();

//Interaction printing mode(page range,printer,and properties of printing can be freely to selected and set)

PrintDialog dialogPrint = new PrintDialog();

dialogPrint.AllowPrintToFile = true;

dialogPrint.AllowSomePages = true;

dialogPrint.PrinterSettings.MinimumPage = 1;

dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;

dialogPrint.PrinterSettings.FromPage = 1;

dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;

if (dialogPrint.ShowDialog() == DialogResult.OK)

{

//the startpage was selected to be printed

doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;

//the endpage was selected to be printed

doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;

//Choose printer to print pdf document

doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;

PrintDocument printDoc = doc.PrintDocument;

dialogPrint.Document = printDoc;

//Realize printing

printDoc.Print();

}
}
}
}