Rss Feed Like Us on facebook Google Plus
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

July 4, 2013

How to prevent page going back on backspace button click

Stop page going back on backspace button click in asp.net,C#,java,PHP.


1. To prevent page going back on backspace or browser back button. you can achieve this by short snippet by javascript below.

<script type="text/javascript">
function preventBack() 
{ 
    window.history.forward(); 
}
setTimeout(function () { preventBack() }, 0);
window.onunload = function () { null };
</script>
.

Follow my blog with Bloglovin
Read More

Disable Button after once Click by Javascript

Disable Button after clicking on it.If when you set disabled="disabled" immediately after
the user clicks the button, and the form doesn't submit because before form submission button is already diasabled..

Uses- It prevents double form submission/ prevent double postback


 you could try these things

1st Way...

//JAVASCRIPT
<script type="text/javascript">
function disable() {
            var v = confirm('Are you sure to save');
            if (v == true) {
                setTimeout(function () { document.getElementById('<%= btnSave.ClientID %>').disabled = true }, 1);
                return true;
            }
            return false;
        }
 
        function preventBack() { window.history.forward(); }
        setTimeout(function () { preventBack() }, 0);
        window.onunload = function () { null };
</script>
//HTML
<input type="button" id="btnsave" runat="server" value="Save" onclick="javascript:disable()" />
2nd Way

myInputButton.disabled = "disabled";
myForm.submit()
Whether it be due to a users lack of tech know-how or a twitch of the finger, a secondary click of a forms ‘Submit’ button could result in the form being submitted twice. Depending on the action of the form this could in turn send two enquiries, create two orders or insert a record into the database twice.

3rd Way

<input type="submit" name="Submit" value="Submit" onclick="this.disabled=true; this.value='Please Wait...';" /> 

4th Way
We can also use AJAX to disable postback element on Request Begin to prevent multiple clicks.

<form id="form1" runat="server">
<asp:scriptmanager id="sc" runat="server" enablepartialrendering="true">  
</asp:scriptmanager>
<script type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginReq);
    function beginReq(sender, args) {
        document.getElementById('<%= lblMessage.ClientID %>').innerText = "Processing.....";
        args.get_postBackElement().disabled = true;
    }  
</script>
<asp:updatepanel id="updpnlSubmit" runat="server">  
    <ContentTemplate>  
        <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />  
        <asp:Label ID="lblMessage" runat="server"></asp:Label>  
    </ContentTemplate>  
</asp:updatepanel>
</form>

Read More

June 27, 2013

change internet explorer page setup programmatically with C#

Change printer setting of internet explorer with C#,basically you can change it bu updating
registry key.

Users can easily change Internet Explorer printer settings for the page margins, the header, and the footer through the Internet Explorer user interface. However, Internet Explorer and the Web Browser control do not include methods to change these settings programmatically.

The following steps outline how Microsoft Internet Explorer accesses the printer settings:

  1. Internet Explorer tries to obtain the values from the following registry key:
    HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\PageSetup
  2. If the key in step 1 does not exist, Internet Explorer tries to create this key by copying the values from the following key:
    HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\PageSetup
  3. If the key in step 2 does not exist, default values are provided.
Checkout the below program..

using Microsoft.Win32;
 
namespace iesttings
{
    Class ie
    {
        public void ChangeIEPageSetupSetting()
        {
            string strKey = "Software\\Microsoft\\Internet Explorer\\PageSetup";
            bool bolWritable = true;
            string strName = "header";
            object oValue = "";
            string strName1 = "footer";
            object oValue1 = "";
            string strName2 = "margin_top";
            object oValue2 = "0.75";
            string strName3 = "margin_right";
            object oValue3 = "0.75";
            string strName4 = "margin_bottom";
            object oValue4 = "0.75";
            string strName5 = "margin_left";
            object oValue5 = "0.75";
 
            RegistryKey oKey = Registry.CurrentUser.OpenSubKey(strKey, bolWritable);
 
            oKey.SetValue(strName, oValue);
            Console.WriteLine("0 updated");
            oKey.SetValue(strName1, oValue1);
            Console.WriteLine("1 updated");
            oKey.SetValue(strName2, oValue2);
            Console.WriteLine("2 updated");
            oKey.SetValue(strName3, oValue3);
            Console.WriteLine("3 updated");
            oKey.SetValue(strName4, oValue4);
            Console.WriteLine("4 updated");
            oKey.SetValue(strName5, oValue5);
            Console.WriteLine("5 updated");
 
            oKey.Close();
            Console.ReadLine();
 
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           ie obj = new ie();
            obj.ChangeIEPageSetupSetting();
        }
    }
}

Note : - Your Web Application should have rights to change the registry settings.

Read More

June 4, 2013

Generate Excel to Export Data using Datatable

Generate Excel is a Major Feature which is used frequently in Web Applications as well as
in Console Applications. So i am going to present an article about generating excel with MS-Excel installed on and without MS-Excel installed on target computer.

Problem with Excel Automation
The technique that is most frequently used to transfer data to an Excel workbooks is Automation. With Automation, you can call methods and properties that are specific to Excel tasks, but this solution has many drawbacks. Some of them are described in the Microsoft Knowledge Base. Additionally, you have to manage the lifetime of the temporary Excel files(.xls) created on the server. Also, it is slow, because Excel runs in a separate process.


  • You can generate excel without MS-Office installed on target computer..
  • You Can Export Data Table data to created Excel

class GenerateExcel
 
{
//  This function will Genereate Excel without MS-Office installed on target computer
 public void CreateExcel(string fileName)
        {
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
                Console.WriteLine("** Excel Deleted ***");
            }
            if (!File.Exists(fileName))
            {
                FileStream stream = new FileStream(filename, FileMode.OpenOrCreate); 
                stream.Close();
                Console.WriteLine("** Excel Created ***");
            }
        }
  
        public void createExcelwithMSOffice(string fileName)
        {
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
                Console.WriteLine("** Excel Deleted ***");
                swlog.WriteLine("***  Excel Exists....Excel Deleted.....  ***");
            }
            if (!File.Exists(fileName))
            {
                Application xl = null;
                _Workbook wb = null;
                object misValue = System.Reflection.Missing.Value;
 
                xl = new Application();
                xl.SheetsInNewWorkbook = 1;
                wb = (_Workbook)(xl.Workbooks.Add(Missing.Value));
                wb.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                wb.Close(true, misValue, misValue);
                Console.WriteLine("** Excel Created ***");
                swlog.WriteLine("***    New Excel Created     ***");
            }
        }
 
 //  This function will export Datatable Data to Created Excel......

        public void ExportToSpreadsheet(System.Data.DataTable table, string name)
        {
            StreamWriter sw = null;
            sw = new StreamWriter(name);
            string ColValue;
            string ColName = "";
            if (table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    ColName = table.Columns[i].ColumnName.ToString() + "\t";
                    sw.Write(ColName);
                }
                sw.WriteLine("\t");
                foreach (DataRow row in table.Rows)
                {
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        ColName = table.Columns[i].ColumnName.ToString();
                        ColValue = row[i].ToString();
                        ColValue = ColValue.ToString().Replace(",", string.Empty) + "\t";
                        ColValue = ColValue.ToString().Replace(Environment.NewLine, " ");
                        ColValue = ColValue.ToString().Replace("\n", " ");
                        //ColValue = ColValue.ToString().Replace(" ", "");
                        ColValue = ColValue.ToString().Replace("-Select-;", "");
                        if (table.Columns[i].DataType.Name == "Boolean")
                        {
                            ColValue = ColValue.ToString().Replace("True", "Yes");
                            ColValue = ColValue.ToString().Replace("False", "No");
                        }
                        sw.Write(ColValue);
                    }
                    sw.WriteLine("\t");
                }
                sw.Close();
                Console.WriteLine("** Data Exported to Excel ***");
            }
            else
            {
                Console.WriteLine("** No Data to Export in Excel ***");
                Environment.Exit(0);
            }
        }
}

Calling the functions..


class Program
    {
        static void Main(string[] args)
        {
           System.Data.DataTable dt = new DataTable();
           GenerateExcel oexcel = new GenerateExcel ();
           string filename=@"C:\demo.xls";
           oexcel.CreateExcel(filename);
           oexcel.ExportToSpreadsheet(dt,filename);
         }
    } 
I hope this article gives you a head start in working with Excel files from .NET and C#.
Read More

April 23, 2013

Const, Read Only, Static in C#

Within a class, const, static and readonly members are special in comparison to the other
modifiers.

const vs. readonly

const and readonly perform a similar function on data members, but they have a few important differences.


const

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared. For example;
public class MyClass
{
  public const double PI = 3.14159;
}
PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.

Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.

Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.

Constants can be marked as public, private, protected, internal, or protected internal.
Constants are accessed as if they were static fields, although they cannot use the static keyword.

To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.

readonly

A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. For example:
public class MyClass
{
  public readonly double PI = 3.14159;
}
or
public class MyClass
{
  public readonly double PI;
 
  public MyClass()
  {
    PI = 3.14159;
  }
}
Because a readonly field can be initialized either at the declaration or in a constructor, readonly fields can have different values depending on the constructor used. Areadonly field can also be used for runtime constants as in the following example:
public static readonly uint l1 = (uint)DateTime.Now.Ticks;
Notes
  • readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.
  • A readonly member can hold a complex object by using the new keyword at initialization.


static

Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object. This means that the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields andstatic events. For example:
public class Car
{
  public static int NumberOfWheels = 4;
}
The static modifier can be used with classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes.

static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:
int i = Car.NumberOfWheels;


MSDN references

Read More

© 2011-2016 Techimpulsion All Rights Reserved.


The content is copyrighted to Tech Impulsion and may not be reproduced on other websites.