Sponsored Ad

Tuesday, September 29, 2009

C# Web Services

This tutorial shows how to create and use Web Services in C#. We begin with an a general overview of .NET Web services concepts and technologies used to implement Web services. Next, we present a step-by-step walkthrough of building and deploying a HugeInteger Web service that performs calculations with integers up to 100 digits long. We then build a Window application that consumes the Web service. This tutorial is intended for students who are already familiar with C# and for C# developers.

Following is our first Web Service; it exposes two methods (Add and SayHello) as Web Services to be used by applications. This is a standard template for a Web Service. .NET Web Services use the .asmx extension.

 

using System;
using System.Web.Services;
using System.Xml.Serialization;

[WebService(Namespace= href="http://localhost/MyWebServices/"http://localhost/MyWebServices/)]
public class FirstService : WebService
{
     [WebMethod]
     public int Add(int a, int b)
     {
         return a + b;
     }

     [WebMethod]
     public String SayHello()
     {
         return "Hello World";
     }
}

C# Combobox

One of the most useful elements on any Windows form is the ComboBox (often known as a drop-down box). It allows the user to accept from an account from authentic account of options (for instance the canicule of the week) and again the programmer can use the best abroad in the application All of this can be achieved very easily with C#.

The C# programmer creates a ComboBox by using C#'s ComboBox object,

 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class Form1 : System.Windows.Forms.Form
{
   private AutoCompleteComboBox combo;

   public Form1()
   {
     this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
     this.ClientSize = new System.Drawing.Size(292, 273);

     combo = new AutoCompleteComboBox();
     combo.Location = new System.Drawing.Point(64, 32);
     combo.Size = new System.Drawing.Size(150, 20);

           combo.Items.Add("Aaaaaa");
           combo.Items.Add("Bbbbbbbbb");
           combo.Items.Add("Ccccccccccc");
     Controls.Add(combo);
     CenterToScreen();
   }

   static void Main()
   {
     Application.Run(new Form1());
   }
}
   public class AutoCompleteComboBox : System.Windows.Forms.ComboBox
   {
       public event System.ComponentModel.CancelEventHandler NotInList;

       private bool strict = true;
       private bool isEditing = false;

       public AutoCompleteComboBox() : base() {
       }

       public bool Strict
       {
           get { return strict; }
           set { strict = value; }
       }

       protected virtual void OnNotInList(System.ComponentModel.CancelEventArgs e)
       {
           if (NotInList != null)
           {
               NotInList(this, e);
           }
       }  

       protected override void OnTextChanged(System.EventArgs e)
       {
           if (isEditing)
           {
               string input = Text;
               int index = this.FindString(input);

               if (index >= 0)
               {
                   isEditing = false;
                   SelectedIndex = index;
                   isEditing = true;
                   Select(input.Length, Text.Length);
               }
           }

           base.OnTextChanged(e);
       }

       protected override void OnValidating(System.ComponentModel.CancelEventArgs e)
       {
           if (this.Strict)
           {
               int pos = this.FindStringExact(this.Text);
               if (pos == -1)
               {
                   OnNotInList(e);
               }
               else
               {
                   this.SelectedIndex = pos;
               }
           }

           base.OnValidating(e);
       }

       protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
       {
           isEditing = (e.KeyCode != Keys.Back && e.KeyCode != Keys.Delete);
           base.OnKeyDown(e);
       }
   }

C# Thread

At its most basic level, a thread is an independent path of execution within an application. By "independent," I beggarly that the cilia acts a little like a mini-program, but  important to accept that all accoutrement are in actuality endemic by a accustomed application. In other words, a thread can’t just come into existence spontaneously, do some work, and then vanish. Rather, all accoutrement are absolutely created by an appliance and again managed by the runtime environment specifically, the Common Language.

 

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.Runtime.InteropServices;
using System.Timers;
using System.Threading;
namespace ToadwaterMacro
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        [DllImportAttribute("User32.dll")]
        private static extern int FindWindow(String ClassName, String
        WindowName);
        [DllImportAttribute("User32.dll")]
        private static extern int SetForegroundWindow(int hWnd);
        private void button1_Click(object sender, EventArgs e)
        {
                int hWnd = FindWindow(null, textBox1.Text);
                if (hWnd > 0)
                {
                    int i = 0;
                    string P = Keys.P.ToString();
                    while (i < 7)
                    {
                        SetForegroundWindow(hWnd);
                        SendKeys.Send(P);
                        SendKeys.Send(P);
                        SendKeys.Send(P);
                        SendKeys.Send(P);
                        SendKeys.Send(P);
                        SendKeys.Send(P);
                        SendKeys.Send(P);
                        Thread.Sleep(40000);
                        i++;
                    }
                }
            }
        }
}

C# DropDownList

A commonly used C# web control is the DropDownList. A DropDownList acquiesce a web user to baddest from a set of items. Each selectable item has a text field (which the web user sees) plus a hidden value field for programming purposes. adding a DropDownList is simple via drag and drop from the toolbox under the Standard section. To add items to your DropDownList via the Designer view, cross to the Properties of the DropDownList. Under the Misc section, click Items. You will see a button with an ellipses. Clicking that button opens a chat box that lists the accepted items. The options for anniversary items are Enabled, Selected, Text, Value.

Example of a DropDownList with three items where item A is selected by default:

 

<asp:DropDownList ID="DropDownList1" runat="server"> 
    <asp:ListItem Value="1" Selected="True">A</asp:ListItem> 
    <asp:ListItem Value="2">B</asp:ListItem> 
    <asp:ListItem Value="3">C</asp:ListItem> 
</asp:DropDownList>

C# Repeater

The Repeater ascendancy is acclimated to affectation a again account of items that are apprenticed to the control. It accredit the customization of the blueprint by anniversary again account of items. The Repeater ascendancy may be apprenticed to a database table, an XML file, or addition account of items. The Repeater ascendancy has no congenital baddest and adapt support.

Below are 2 simple Repeater controls. The aboriginal one affectation its items in a table, and the additional one affectation its items afar by comma.

 

public class PositionData
{
private string name;
private string ticker;

public PositionData(string name, string ticker)
{
this.name = name;
this.ticker = ticker;
}

public string Name
{
get
{
return name;
}
}

public string Ticker
{
get
{
return ticker;
}
}

C# TreeView

This article addressing some of the basics of working with a TreeView control; the commodity will abode dynamically abacus TreeNodes to a TreeView control, earching the nodes to find and highlight a single node or a collection of nodes matching a search term against the TreeNode's tag, text, or name properties, and manually or programmatically selecting nodes.

The application solution contains a single Windows Application project comprised;all cipher supplied in abutment of this activity is independent in two anatomy classes; one is the capital anatomy absolute the TreeView and a few controls acclimated to affectation bulge advice nd to execute searches for a specific node or group of nodes based upon a user supplied search term. The other form class is used to create new nodes; within the application, this form is displayed by selecting a node from the TreeView and then selecting the "Add Node" option from the context menu.

The functionality contained in the class is broken up into several regions; the class begins with the default imports, namespace declaration, and class declaration:

 

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace EasyTreeView

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            // start off by adding a base treeview node

            TreeNode mainNode = new TreeNode();

            mainNode.Name = "mainNode";

            mainNode.Text = "Main";

            this.treeView1.Nodes.Add(mainNode);

        }

C# Checkbox

The CheckBox class represents a check box that users can select and clear.This affair introduces you to the CheckBox ascendancy in Windows Presentation Foundation (WPF) and describes how to actualize CheckBox elements in Extensible Application Markup Language (XAML) and C#, set event handlers in C#, create CheckBox controls that contain rich content such as images, and use styling to change the control's appearance.

Example:

 

<%@ Page Language="C#" %>
<script runat="server">
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblResult.Text = chkNewsletter.Checked.ToString();
}
</script>
<html>
<head>
<title>Show CheckBox</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox
id="chkNewsletter"
Text="Receive Newsletter?"
Runat="server" />
<br />
<asp:Button
id="btnSubmit"
Text="Submit"
OnClick="btnSubmit_Click"
Runat="server" />
<hr />
<asp:Label
id="lblResult"
Runat="server" />
</div>
</form>
</body>
</html>

C# File

C-Sharp provides a File class which is used in manipulating text files.The File chic is aural the System namespace. Also we can use the StreamReader and StreamWriter classes, which are within the System.IO, namespace for reading from and writing to a text file. In this commodity we'll see examples of Creating a argument file, account capacity of a argument book and appending curve to a argument file.

For creating text file we use the CreateText Method of the File Class. The CreateText methods takes in the aisle of the book to be created as an argument. It creates a file in the specified path and returns a StreamWriter object which can be used to write contents to the file.

 

public class FileClass
{
    public static void Main()
    {
    WriteToFile();
    }
    static void WriteToFile()
    {
    StreamWriter SW;
    SW=File.CreateText("c:\\MyTextFile.txt");
    SW.WriteLine("God is greatest of them all");
    SW.WriteLine("This is second line");
    SW.Close();
    Console.WriteLine("File Created SucacessFully");
    }
}

Monday, September 28, 2009

C# Winform

Windows Forms is a graphical user interface appliance programming interface (API) included as a allotment of Microsoft's .NET Framework. As of 13 May 2008, Mono's System.Windows.Forms 2.0 is API complete. Simply put, Winforms is a library for creating GUI applications.

This program is for beginners who want to learn the basics of C# WinForms. The following code gives a quick and easy example of how WinForms work.

//Compilation
//CSC /r:system.drawing.dll /r:system.windows.forms.dll filename.cs
//For [ Beta 2]
using System;
using System.Drawing;
using System.Windows.Forms;
public class Form1 : Form
{
Label label1  = new Label();
TextBox textBox1 = new TextBox();
Button button1 = new Button();
Label label2 = new Label();
public Form1()
{
  label1.Location = new Point(56, 48);
  label1.Name = "label1";
  label1.TabIndex = 0;
  label1.Text = "Enter Ur Name : ";
  textBox1.Location = new Point(176, 48);
  textBox1.Name = "textBox1";
  //textBox1.Size = new Size(112, 20);
  textBox1.Text = "";
  button1.Location = new Point(128, 104);
  button1.Name = "button1";
  button1.Text = "Click Me";
  label2.Location = new Point(88, 192);
  label2.Name = "label2";
  button1.Click += new System.EventHandler(button1_Click1a);
  //Controls.AddRange(new Control[]
  //{label2, button1, textBox1, label1});
  //Instead of this u can use the Following
  Controls.Add(label2);
  Controls.Add(label1);
  Controls.Add(button1);
  Controls.Add(textBox1);
}
static void Main()
{
  Application.Run(new Form1());
}
private void button1_Click1a(object sender, System.EventArgs e)
{
  label2.Text = "Thanks a Lot ";
}
}

C# Form

One of the a lot of advantageous elements on any Windows anatomy is the ComboBox (often accepted as a drop-down box). It allows the user to accept from an account from authentic account of options (for instance the canicule of the week) and again the programmer can use the best abroad in the appliance (for archetype to acquaint the user from which planet the day name is derived). All of this can be accomplished actual calmly with C#.

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.Threading;
namespace WindowsFormsApplication1.Forms
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            this.Text = "Original";
            this.Left = 0;
            Form f = new Form();
            f.Text = "Manual";
            f.Show();
            f.Left = this.Width;
            TimerCallback tCallback = new TimerCallback(Timer_Tick);
            System.Threading.Timer timer = new System.Threading.Timer(tCallback, null, 1000, System.Threading.Timeout.Infinite);
        }

        void Timer_Tick(object o)
        {
            Form f = new Form();
            f.Text = "Timer";
            f.Show();
            f.Left = this.Width * 2;
        }
    }
}

C# Namespace

A Namespace in Microsoft .Net is like containers of objects.They may lath unions, classes, structures, interfaces, enumerators and delegates. Main appetence of apparatus namespace in .Net is for creating a hierarchical alignment of program. In this case a developer does not allegation to affliction about the allocation conflicts of classes, functions, variables etc., axial a project. In Microsoft .Net, every address is created with a absence namespace. This absence namespace is declared as all-around namespace.But the address itself can accede any bulk of namespaces, ceremony of them with a adapted name. The advantage is that every namespace can board any bulk of classes, functions, variables and aswell namespaces etc. whose names are adapted alone axial the namespace. The accumulation with the aloft name can be created in some added namespace afterwards any compiler complaints from Microsoft .Net.

To acknowledge namespace C# .Net has a aloof keyword namespace. If a new activity is created in Visual Studio .NET it automatically adds some all-around namespaces. These namespaces can be different in different projects. But each of them should be placed under the base namespace System. The names space must be added and used through the using operator, if used in a different project.

namespace Math
{
    class Addition
    {
        static public double add(params int[] numbers)
        {
            int total = 0;
            for(int i=0; i<numbers.Length; i++)
            {
                total += numbers[i];
            }   
            return total;
        }
    }
}

class MyMath
{
    public static void Main()
    {
        double x = Math.Addition.add(1, 3, 5, 6);       
        System.Console.WriteLine(x);
    }
}

C# Function

C#.NET comes with a lot of great string processing functions like Substring, Compare, IndexOf. But the accuracy is the congenital .NET cord functions are actual limited. Programmers consistently accept to carbon agnate argument processing functions over and over. Luckily we can aggrandize on them and actualize all kinds of C# avant-garde cord functions. As for a amount of speed, there are is one affair to consider: Cord vs StringBuilder.

//Triangle full of star
using System;
class star
{
public static void space(int x)
{
  for(int i=0 ; i <= x ; i++)
   Console.Write(" ");
}

public static void Main()
{
  int no=31;
  Console.WriteLine("How many lines of star you want?");
  int s=Int32.Parse(Console.ReadLine());
  space(32);
  Console.WriteLine("*");
  for(int i=2;i<=s;i++)
  {
   space(no);
   for(int k=1;k<=i+i-1;k++)
    Console.Write("*");
   no=no-1;
   Console.WriteLine();
  }
}
}

C# Controls

Windows programmers have a wide variety of controls to choose from in the System.Windows.Forms namespace in .NET's Framework class library. You accept controls as simple as Label, TextBox, and CheckBox, as able-bodied as controls as adult as the MonthCalendar and ColorDialog controls. hese Windows controls are more than enough for most applications; however, sometimes you charge controls that are not accessible from the accepted library. . In these circumstances, you have to roll up your sleeves and write your own. This article shows you how to develop a custom control with C# and presents a simple custom control.

Before you start writing the first line of code for your custom control,you should familiarize yourself with two classes in the System.Windows.Forms namespace: Control and UserControl. The Control chic is important because it is the ancestor chic of Windows beheld components. Your custom chic will be a descendent of the Control chic as well. Your custom controls, however, don't normally inherit directly from the Control class. Instead, you extend the UserControl class. The aboriginal two sections of this commodity altercate these two classes. In the final section, you'll body your own custom control, the RoundButton control.

//specify the namespace in which the control resides
namespace Test.Control
{
      //specify the name spaces of other classes that are commonly referenced
      using System.WinForms;
      //the control definition and implementation
      public class MyControl : System.WinForms.RichControl
      {
      }
}

C# Button

A button is a control, which is an alternate basic that enables users to acquaint with an application. The Button ascendancy is a ContentControl, which agency that a button can accommodate agreeable like text, images, or panels.

A button is a control, which is an alternate basic that enables users to acquaint with an application. The Button ascendancy is a ContentControl, which agency that a button can accommodate agreeable like text, images, or panels.

<Button Name="btn1" Background="Pink" BorderBrush="Black" BorderThickness="1" Click="OnClick1">
        ClickMe1</Button>
<Button Name="btn2" Background="LightBlue" BorderBrush="Black" BorderThickness="1" Click="OnClick2">
        ClickMe2</Button>
<Button Name="btn3" Click="OnClick3">Reset</Button>

C# Event

An event is a mechanism via which a class can notify its clients when something happens. For example when you click a button, a button-click-event notification is sent to the window hosting the button. Events are declared using delegates. So if you don't know what a delegate is,  Just try out the sample program and go through the sample source, line by line. Maybe, you can read the article once more after that. Once you get the hang of it, things will seem simple.

using System;
public delegate void DivBySevenHandler(object o, DivBySevenEventArgs e);
public class DivBySevenEventArgs : EventArgs
{
    public readonly int TheNumber;
    public DivBySevenEventArgs(int num)
    {
        TheNumber = num;
    }   
}
public class DivBySevenListener
{
    public void ShowOnScreen(object o, DivBySevenEventArgs e)
    {
        Console.WriteLine(
            "divisible by seven event raised!!! the guilty party is {0}",
            e.TheNumber);
    }   
}
public class BusterBoy
{
    public static event DivBySevenHandler EventSeven;
    public static void Main()
    {
        DivBySevenListener dbsl = new DivBySevenListener();
        EventSeven += new DivBySevenHandler(dbsl.ShowOnScreen);
        GenNumbers();
    }
    public static void OnEventSeven(DivBySevenEventArgs e)
    {
        if(EventSeven!=null)
            EventSeven(new object(),e);
    }   
    public static void GenNumbers()
    {
        for(int i=0;i<99;i++)
        {
            if(i%7==0)
            {
                DivBySevenEventArgs e1 = new DivBySevenEventArgs(i);
                OnEventSeven(e1);
            }
        }       
    }
}

Sunday, September 27, 2009

C# List View

A ListView ascendancy allows you to affectation a account of items with an alternative figure in a agnate address to Windows Explorer. A lot of generally acclimated address is to appearance a multicolumn account of items as displayed here.
However, the ListView ascendancy supports 5 audible modes of viewing, actual agnate in attributes to those that can be accomplished application Windows Explorer. This is done through the View property.


Example:
lass ListViewBase:ListView
{
    private Timer tmrLVScroll;
    private System.ComponentModel.IContainer components;
    private int mintScrollDirection;
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
    const int WM_VSCROLL = 277; // Vertical scroll
    const int SB_LINEUP = 0; // Scrolls one line up
    const int SB_LINEDOWN = 1; // Scrolls one line down
    public ListViewBase()
    {
        InitializeComponent();
    }
    protected void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.tmrLVScroll = new System.Windows.Forms.Timer(this.components);
        this.SuspendLayout();
        //
        // tmrLVScroll
        //
        this.tmrLVScroll.Tick += new System.EventHandler(this.tmrLVScroll_Tick);
        //
        // ListViewBase
        //
        this.DragOver += new System.Windows.Forms.DragEventHandler(this.ListViewBase_DragOver);
        this.ResumeLayout(false);
    }
    protected void ListViewBase_DragOver(object sender, DragEventArgs e)
    {
        Point position = PointToClient(new Point(e.X, e.Y));
        if (position.Y <= (Font.Height / 2))
        {
            // getting close to top, ensure previous item is visible
            mintScrollDirection = SB_LINEUP;
            tmrLVScroll.Enabled = true;
        }else if (position.Y >= ClientSize.Height - Font.Height / 2)
        {
            // getting close to bottom, ensure next item is visible
            mintScrollDirection = SB_LINEDOWN;
            tmrLVScroll.Enabled = true;
        }else{
            tmrLVScroll.Enabled = false;
        }
    }
    private void tmrLVScroll_Tick(object sender, EventArgs e)
    {
        SendMessage(Handle, WM_VSCROLL, (IntPtr)mintScrollDirection, IntPtr.Zero);
    }
}

C# Properties

Properties provide the opportunity to protect a field in a class by reading and writing to it through the property.In other languages,this is generally able by programs implementing specialized getter and setter methods. C# backdrop accredit this blazon of aegis while aswell absolution you admission the acreage just like it was a field.

Example:

using System;
public class Customer
{
    private int m_id = -1;
    public int GetID()
    {
        return m_id;
    }
    public void SetID(int id)
    {
        m_id = id;
    }
    private string m_name = string.Empty;
    public string GetName()
    {
        return m_name;
    }
    public void SetName(string name)
    {
        m_name = name;
    }
}
public class CustomerManagerWithAccessorMethods
{
    public static void Main()
    {
        Customer cust = new Customer();
        cust.SetID(1);
        cust.SetName("Amelio Rosales");
        Console.WriteLine(
            "ID: {0}, Name: {1}",
            cust.GetID(),
            cust.GetName());
        Console.ReadKey();
    }
}

C# Data Grid

Among those many controls is the DataGrid control which helps the developer to display the data on the screen in the format of an arranged table. Datagrid is one of the 3 templated controls provided by the Microsoft.net framework. The added two are DataList and the Repeator control.In this commodity we will see the a lot of accepted use of the datagrid control. Lets set up out datagrid.

private void fnSaveUpdate()
{
   try
   {
      //put the modified DataSet into a new DataSet(myChangedDataset)
      DataSet myChangedDataset= this.dataSet11.GetChanges();
      if (myChangedDataset != null)
     {
        //get how many rows changed
        int modifiedRows = this.oleDbDataAdapter1.Update(myChangedDataset);
        MessageBox.Show("Database has been updated successfully: " +
                      modifiedRows + " Modified row(s) ", "Success");
        this.dataSet11.AcceptChanges(); //accept the all changes
        fnRefresh();
     }
     else
     }
        MessageBox.Show("Nothing to save", "No changes");
      }//if-else
   }
   catch(Exception ex)
  {
     //if something somehow went wrong
    MessageBox.Show("An error occurred updating the database: " +
      ex.Message, "Error",  MessageBoxButtons.OK, MessageBoxIcon.Error);
    this.dataSet11.RejectChanges(); //cancel the changes
  }//try-catch
  fnEnableDisableAllButtons(true);
}

C# Dataset

One of the abundant appearance alien by microsoft in the .net technology is the dataset . The dataset is the article agnate the the acceptable ADO recordset . However the dataset has abounding cogent differences.
  • The dataSet can hold the results of many SQL queries .
  • You can use the dataset while the connection is closed .
  • You can create a dataset from an XML file .
  • You can write XML directly from a dataset .

using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        { InitializeComponent(); }
      
        private void button1_Click(object sender, EventArgs e)  
        {            
            string connetionString = null;
            OleDbConnection connection ;
            OleDbDataAdapter oledbAdapter ;
            DataSet ds1 = new DataSet();
            DataSet ds2 = new DataSet();
            DataTable dt ;
            string firstSql = null;
            string secondSql = null;
            int i = 0;
            connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
            firstSql = "Your First SQL Statement Here";
            secondSql = "Your Second SQL Statement Here";
            connection = new OleDbConnection(connetionString);
            try            
            {
                connection.Open();
                oledbAdapter = new OleDbDataAdapter(firstSql, connection);
                oledbAdapter.Fill(ds1, "First Table");
                oledbAdapter.SelectCommand.CommandText = secondSql;
                oledbAdapter.Fill(ds2, "Second Table");
                oledbAdapter.Dispose();
                connection.Close();

                ds1.Tables[0].Merge(ds2.Tables[0]);
                dt = ds1.Tables[0];

                for (i = 0; i <= dt.Rows.Count - 1; i++)  
                {              
                    MessageBox.Show(dt.Rows[i].ItemArray[0] + " -- " + dt.Rows[i].ItemArray[0]);

                }        
            }          
            catch (Exception ex)  
            {            
                MessageBox.Show("Can not open connection ! ");  
            }      
        }
    }
}

Saturday, September 26, 2009

C# Text Box

To affectation assorted types of formatted text, use the RichTextBox control.The argument displayed by the ascendancy is independent in the Argument property. By default, you can access up to 2048 characters in a argument box. If you set the MultiLine acreage to true, you can access up to 32 KB of text.
The code below sets text in the control at run time.

<%Page Language="c#" %>
<script runat="server">
    void Page_Load()
    {
      if (Page.IsPostBack)
      {
          lblName.Text = “”;
          lblAddress.Text = “”;
          lblPassword.Text = “”;
      }
      if (txtName.Text !="")
        lblName.Text = "You have entered the following name: " +  txtName.Text;
      if (txtAddress.Text !="")
        lblAddress.Text = "You have entered the following address: " + txtAddress.Text;
      if (txtPassword.Text !="")
        lblPassword.Text = "You have entered the following password: " + txtPassword.Text;
    }
</script>
<html>
<head>
    <title>Text Box Example</title>
</head>
<body>
    <asp:Label id="lblName" runat="server"></asp:Label>
    <br />
    <asp:Label id="lblAddress" runat="server"></asp:Label>
    <br />
    <asp:Label id="lblPassword" runat="server"></asp:Label>
    <br />
    <form runat="server">
        Please enter your name:
        <asp:textbox id="txtName" runat="server"></asp:textbox>
        <br />
        <br />
        Please enter your address:
        <asp:textbox id="txtAddress" runat="server" textmode="multiline" rows="5"></asp:textbox>
        <br />
        <br />
        Please enter your password:
        <asp:textbox id="txtPassword" runat="server" textmode="password"></asp:textbox>
        <br />
        <br />
        <input type="submit" value="Submit Query" />
    </form>
</body>
</html>

C# List Box

ListBox affiliated from System.Windows.Forms.ListBox. Its primary action is to architecture anniversary Item into assorted columns. Secondly, the applicant should be able to retrieve the capacity of any cavalcade in any row easily. I absitively the best way to do this would be to actor the cartoon of the accepted DataGrid.


 

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using AsYetUnnamed;

public class Form1 : System.Windows.Forms.Form
{
    private DataSet ds;
    private MultiColumnListBox listBox1;
    public Form1()
    {
        ds = DataArray.ToDataSet(new object[,]{
                    {"Row0, col0",  "Row0, col1" ,1},
                    {"Row00, col0", "Row1, col1" ,new object()},
                    {"Row1, col0",  "Row2, col1" ,"Some String"},
                    {"Row1a, col0", "Row3, col1" ,Rectangle.Empty},
                    {"row1aa,col0", "Row4, col1" ,1},
                    {"row0, col0",  "Row5, col1" ,1},
                    {"pow0, col0",  "Row6, col1" ,1},
                    {"Row7, col0",  "Row7, col1" ,new ExampleClass()},
                    {"Row8, col0",  "Row8, col1" ,Image.FromFile("StopLight.gif")}
                    });
        listBox1 = new MultiColumnListBox();
        listBox1.Parent = this;

        listBox1.DataSource = arr;           
    }
    class ExampleClass
    {
        Public override string ToString()
        {
            return "Hello from ExampleClass!!";
        }
    }

}

C# Programming

C# (pronounced "C Sharp") is a multi-paradigm programming accent encompassing imperative, functional, generic, acquisitive (class-based), and component-oriented programming disciplines. It was developed by Microsoft aural the .NET action and after accustomed as a accepted by Ecma C# is one of the programming languages advised for the Common Accent Infrastructure.

C# is advised to be a simple, modern, general-purpose, acquisitive programming language. The language, and implementations thereof, should accommodate abutment for software engineering attempt such as able blazon checking, arrangement bound checking, apprehension of attempts to use uninitialized variables, and automated debris collection. Software robustness, durability, and programmer abundance are important. The accent is advised for use in developing software apparatus acceptable for deployment in broadcast environments.

C# Array

C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). The afterward examples appearance how to acknowledge altered kinds of arrays:
Single-dimensional arrays:
int[] numbers;

Multidimensional arrays:
string[,] names;

Array-of-arrays (jagged):
byte[][] scores;

Example


// arrays.cs
using System;
class DeclareArraysSample
{
    public static void Main()
    {
        // Single-dimensional array
        int[] numbers = new int[5];
        // Multidimensional array
        string[,] names = new string[5,4];
        // Array-of-arrays (jagged array)
        byte[][] scores = new byte[5][];
        // Create the jagged array
        for (int i = 0; i < scores.Length; i++)
        {
            scores[i] = new byte[i+3];
        }
        // Print length of each row
        for (int i = 0; i < scores.Length; i++)
        {
            Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
        }
    }
}

C# Using

using in C# can be used in two ways:
  • as a shortcut to typing long namespaces used in code
  • as a means of properly and automatically close and dispose any object references implementing the IDisposable interface
For the latter, here's an example, in which a clandestine abettor adjustment allotment a DataSet object. I about address abstracts admission cipher wherein abstracts is pulled from a SQL Server database through a stored action aural a library like so:


using System.Data;
using System.Data.SqlClient;
private DataSet GetFreshData(string sprocName)
{    
using ( SqlConnection conn = new SqlConnection() )    
{    
using ( SqlDataAdapter da = new SqlDataAdapter() )
{                
da.SelectCommand = new SqlCommand();    
da.SelectCommand.CommandText = sprocName;    
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Connection = conn;        
DataSet ds = new DataSet();      
try        
{      
da.SelectCommand.Connection.Open();
da.Fill(ds);    
da.SelectCommand.Connection.Close();  
}          
catch  
{          
return null;        
}        
finally  
{        
// do other things...calling Close() or Dispose()  
// for SqlConnection or SqlDataAdapter objects not necessary  
// as its taken care of in the nested "using" statements
}
return ds;  
}
}
}

C# Class

C# Inheritance C# Class objectives are as follows:
  • Implement Base Classes.
  • Implement Derived Classes.
  • Initialize Base Classes from Derived Classes.
  • Call Base Class Members.
  • Hide Base Class Members.

using System;
public class ParentClass
{
    public ParentClass()
    {
        Console.WriteLine("Parent Constructor.");
    }
    public void print()
    {
        Console.WriteLine("I'm a Parent Class.");
    }
}
public class ChildClass : ParentClass
{
    public ChildClass()
    {
        Console.WriteLine("Child Constructor.");
    }
    public static void Main()
    {
        ChildClass child = new ChildClass();
        child.print();
    }
}

Output:
Parent Constructor. Child Constructor. I'm a Parent Class.

goto Statement in C#

The goto account is the a lot of archaic C# jump statement. It transfers ascendancy to a labeled statement. The characterization have to abide and have to be in the ambit of the goto statement. More than one goto account can alteration ascendancy to the aforementioned label.

if (number % 2 == 0)
   goto Even;
   Console.WriteLine("odd");
   goto End;
Even:
   Console.WriteLine("even");
End:;

foreach Loop in C#

The foreach bend allows you to iterate through anniversary account in a collection. For now, we won worry about absolutely what a accumulating is we will just say that it is an article that contains added objects. Technically, to calculation as a collection, it have to abutment an interface called IEnumerable . Examples of collections cover C# arrays, the accumulating classes in the System .Collection namespaces, and user - authentic accumulating classes.

// cs_foreach.cs
class ForEachTest
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}

do while Loop in C#

The do...while loop is the another form of the while loop. It works same as do while loop works in C++ and Java, and same as in Visual Basic. Consequently, do...while loops are advantageous for situations in which a block of statements have to be executed at least one time. While "while" loop can run 0 to unlimited time. in do while loop user gives condition in the end of loop that's why it runs at least one time.

The general form of the do-while loop is:

do {
statements;
} while(condition);

using System;
class MainClass
{
public static void Main()
{
int n = 0;
do
{
Console.WriteLine("Number is {0}", n);
n++;
} while (n < 10);
}
}

while Loop in C#

the while bend is a lot of generally acclimated to echo a account or a block of statements for a amount of times that is not accepted afore the bend begins. Usually, a account central the while bend ’ s physique will set a Boolean banderole to apocryphal on a assertive iteration. A while bend will analysis a action and afresh continues to assassinate a block of cipher as continued as the action evaluates to a boolean amount of true. When the boolean announcement evaluates to true, the statements will execute. Once the statements accept executed, ascendancy allotment to the alpha of the while bend to analysis the boolean announcement again.

The While Loop: WhileLoop.cs
using System;
class WhileLoop
{
public static void Main()
    {
int myInt = 0;
while (myInt < 10)
        {
            Console.Write("{0} ", myInt);
            myInt++;
        }
        Console.WriteLine();
    }
}

Friday, September 25, 2009

The for Loop in C#

The for loop is so similar to c/c++ for loop. The for loop is accomplished for repeating a account or a block of statements for a specific number of times.
for loop contains the starting point that is i=0, we can have any starting point as per our requirement.
second part is condition, when for loop will break.
third one is increment, what increment should program follow.


Example:
using System; class ForLoop {     public static void Main()     {         for (int i=0; i < 20; i++)         {             if (i == 10) break;             if (i % 2 == 0)                 continue;             Console.Write("{0} ", i);         }         Console.WriteLine();     } }

The switch Statement in C#

The switch expression must be of an integer type, such as char, byte, short, or int, or of type string. The switch Statement is a set of if else statement .The default statement sequence is executed if no case constant matches the expression. The default is optional.If default is not present, no action takes place if all matches fail.When a match is found, the statements associated with that case are accomplished until the breach is encountered.

The general form of the switch statement is 


switch(expression) {
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
.
.
.

default:
statement sequence
break;
}

Thursday, September 24, 2009

The if Statement in C#

For codicillary branching, C# inherits the C and C++ if...else construct. The syntax should be very easy for anyone who has done any programming with a procedural language.

if(condition)

statement;

  1. condition is a Boolean (that is, true or false) expression.
  2. If condition is true, then the statement is executed.
  3. If condition is false, then the statement is bypassed.
The complete anatomy of the if account is


if(condition)
statement;
else
statement;

statement;
The general form of the if using blocks of statements is


if(condition)
{
statement sequence
}
else
{
statement sequence
}

statement sequence
} if-else-if ladder. It looks like this:


if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.

else
statement;

The String Type in C#

A C or C++ string is nothing more than an array of characters, so the applicant programmer has to do a lot of plan just to copy one cord to addition or to concatenate two strings. In fact, for a bearing of C++ programmers, implementing a cord chic that wraps up the blowzy data of these operations was a rite of passage requiring abounding hours of teeth gnashing and arch scratching. Visual Basic programmers have a somewhat easier life, with a string type, and Java people have it even better, with a String class that is in many ways very similar to a C# string. C# recognizes the cord keyword, which beneath the awning is translated to the .NET class, System String . With it, operations like cord chain and cord artful are a snap.
.
string str1 = “Hello “;
string str2 = “World”;
string str3 = str1 + str2; // string concatenation


In C#, the string keyword is an alias for String. So, String and string are equivalent, and one can use whichever naming convention he prefer. The String class provides many methods for safely creating, manipulating, and comparing strings. In addition, the C# language also provide overloads of operators to simplify common string operations.
Despite this accomplishment of assignment, band is a inadvertence type. Behind the scenes, a string is allocated on the heap, not the stack, and if you accredit one band approximate to accretion string, you get two references to the aloft band in memory. However, with band there are some differences from the accustomed behavior for advertence types. For example, should you accomplish changes to one of these strings, this will accomplish an in fact new band object, abolishment the added band unchanged. Consider the afterwards code.

using System;
class StringExample
{
public static int Main()
{
string s1 = “a string”;
string s2 = s1;
Console.WriteLine(“s1 is “ + s1);
Console.WriteLine(“s2 is “ + s2);
s1 = “another string”;
Console.WriteLine(“s1 is now “ + s1);
Console.WriteLine(“s2 is now “ + s2);
return 0;
}
}
The output from this is:
s1 is a string
s2 is a string
s1 is now another string
s2 is now a string


Changing the bulk of s1 had no aftereffect on s2 , adverse to what you apprehend with a advertence type! What`s blow achievement is that if s1 is initialized with the bulk a bond , a new bond commodity is allocated on the heap. If s2 is initialized, the advertence believability to this above object, so s2 aswell has the bulk a bond . However, if you now change the bulk of s1 , instead of replacing the ancient value, a new commodity will be allocated on the affluence for the new value. The s2 arbitrary will still point to the ancient object, so its bulk is unchanged.

The Object Type in C#

Many programming languages and c# hierarchies accommodate a basis type, from which all added datatypes are derived. C# and .NET are no exception. In C#, the article blazon is the ultimate ancestor blazon from which all added built-in and user - authentic types are derived. This is a key feature of C# that distinguishes it from both Visual Basic 6.0 and C++, although its behavior actuality is similar to Java. All types around acquire ultimately from the System.Object class. This feature you can use for two purposes.
  • You can use an object reference to bind to an object of any particular subtype. “ Operators and Casts, ” you will see how you can use the object type to box a value object on the stack to move it to the heap. object references are also useful in reflection, when code must manipulate objects whose specific types are unknown. This is similar to the role played by a void pointer in C++ or by a Variant data type in VB.
  • The object type implements a number of basic, general - purpose methods, which include Equals() , GetHashCode() , GetType() , and ToString(). Responsible user - defined classes may need to provide replacement implementations of some of these methods using an object - oriented technique known as overriding in “ Inheritance. ” When may charge to accommodate backup implementations of some of these methods application an article - oriented address accepted as cardinal in Inheritance.

Wednesday, September 16, 2009

.NET C# Data Types

C# is a strongly typed language and as such all variables and objects must have a declared data type. The data type can be one of the following:

  1. Value
  2. Reference
  3. User – defined
  4. Anonymous

Value Types

A value type variable contains the data that it is assigned. For example, when you declare an int (integer) variable and assign a value to it, the variable directly contains that value. And when you assign a value type variable to another, you make a copy of it. The following example :
class Program1
{
static void Main(string[] args)
{
int intnum1, intnum2;
intnum1 = 5;
intnum2 = num1;
Console.WriteLine(“num1 is {0}. num2 is {1}”, intnum1, intnum2);
intnum2 = 3;
Console.WriteLine(“num1 is {0}. num2 is {1}”, intnum1, intnum2);
Console.ReadLine();
return;
}
}


The output of this program is:
num1 is 5. num2 is 5
num1 is 5. num2 is 3

Reference Types



For reference types, the variable stores a reference to the data rather than the actual data. Consider the following:
Button btnTest1, btnTest2;
btnTest1 = new Button();
btnTest1.Text = “YES”;
btnTest2 = btnTest1;
Console.WriteLine(“{0} {1}”, btnTest1.Text, btnTest2.Text);
btnTest2.Text = “NO”;
Console.WriteLine(“{0} {1}”, btnTest1.Text, btnTest2.Text);

Here, you first declare two Button controls — btn1 and btnTest2 . btnTest1 ’ s Text property is set to “ YES” and then btnTest2 is assigned btnTest1 . The first output will be:
YES YES

When you change btnTest2 ’ s Text property to “ NO” , you invariably change btnTest1 ’ s Text property, as the second output shows:
NO NO
Sponsored Ad

More Related Articles

Website Update

Followers