MySql Query To Get Important Column Properties of A Table

10:57 PM
MySql Query :

SELECT  COLUMN_NAME
      , DATA_TYPE
      , CHARACTER_MAXIMUM_LENGTH
      , NUMERIC_PRECISION
      , NUMERIC_SCALE
      , EXTRA
      , COLUMN_KEY
      , COLUMN_DEFAULT
      , IS_NULLABLE
      , COLUMN_COMMENT
FROM    INFORMATION_SCHEMA.COLUMNS
WHERE   table_name = 'YourTableName'
        AND TABLE_SCHEMA = 'YourDatabaseName'


Example OutPut:





MySql Query To List All The Tables in Perticular Database

10:46 PM
MySql  Query:
 
SELECT  TABLE_NAME
FROM    INFORMATION_SCHEMA.TABLES
WHERE   TABLE_SCHEMA = 'test'
 


Example OutPut:


Understanding StopWatch Class in c#

2:59 AM
Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Startmethod, then eventually call the Stop method, and then you check elapsed time using the Elapsed property. (From MSDN)


Let say i want to find out Total Time a Process has been Running. 
Like
1. How many Minutes or Second it took to insert 1000 record in Database?
2. How many time it took to update the Database ? etc ..


I provide a very Basic Example with a Console Application ..


The Stopwatch Class has two Primary Methods 1. Start() 2. Stop() and One Property that is Elapsed .


The Code:





using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace StopWatchExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Console.WriteLine("Stop Watch Start....\n");
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine(i + "\n");
            }
            sw.Stop();
            Console.WriteLine("Stop Watch Stopped:");
            Console.WriteLine("Total Time: {0}", sw.Elapsed);
            Console.ReadLine();
        }
    }
}


As You can See I have started our Stopwatch Just Before My loop has started.
Now the Loop will Do its work ..
After That As Soon As we are out sw.Stop has been Called.

I have Just Recorded The Timing The Loop Took To Complete.

The Output Will Look SomeThing Like These:


Embeding Firefox Brower (Gecko Engine) in C# using GeckoFX

11:19 PM
Ever Thought if it was possible to not WebBrower control and use the Firefox Browser in your c# window Application...??

Yes ,, It is possible using GeckoFx wrapper class for  C#.net and vb also.

You will need the Followings:

1. GeckoFx Wrapper [Download]
2. Xul Runner [Download] (Download the zip file from here)

How to:

1.   Now Extract Skybound.GeckoFX.bin.v1.9.1.0.zip (First download).
      You will find Skybound.Gecko.dll and that's what we need.
2.   Now create a Project and name is GeckoFxcsharpBorwer or anything you like.
3.   Now  add the reference of the above dll and also add that to your toolbox.
4.   Now Exctract the Second downloaded file (xulrunner-1.9.1.2.en-US.win32.zip). and you will find xulrunner . This is the path to xulrunner runtime.
5.   Create a Form Layout Like The Figure Below:


Now The Coding Part:

Our Form's Constructor:(Providing the Path to XulRunner Runtime)

public Form1()
        {
            InitializeComponent();
            Skybound.Gecko.Xpcom.Initialize("Path To the xulrunner directory [Extracted from the Second Downloaded File]"); // for example "c:\\xulrunner\\"
        }

Form's Load Event:

private void Form1_Load(object sender, EventArgs e)
        {
            geckoWebBrowser1.Navigate("www.google.com");
        }

Stop Button click Event:


private void btnStop_Click(object sender, EventArgs e)
        {
            geckoWebBrowser1.Stop();
        }



Refresh Button Click Event:


private void btnRefresh_Click(object sender, EventArgs e)
        {
            geckoWebBrowser1.Refresh();
        }



Save Page Button Click Event:


private void btnSavePage_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = " Html File | *.html";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                geckoWebBrowser1.SaveDocument(sfd.FileName);
            }
        }


And Now Finally the Output:


That's All.

Complete Project : GeckoNet

ps: You can easily Add an Addressbar and other stuff

Parsing Comma Delemeted String in Sql

9:46 PM
I will just go with the Example as its Self Exclamatory.

Sql Query:
declare @string varchar(500)
set @string = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

declare @pos INT
declare @piece varchar(500)

-- Need to tack a delimiter onto the end of the input string if one doesn’t exist
if right(rtrim(@string),1) <> ','
 set @string = @string  + ','

set @pos =  patindex('%,%' , @string)
while @pos <> 0
begin
 set @piece = left(@string, @pos - 1)
 
 -- You have a piece of data, so insert it, print it, do whatever you want to with it.
 print cast(@piece as varchar(500))

 set @string = stuff(@string, 1, @pos, '')
 set @pos =  patindex('%,%' , @string)
end

Output:






A stored Procedure to Count Numbers of Rows in Table

9:33 PM
This a simple Stored procedure to count the total numbers of rows in each table of your Database.
I assume you have Northwind database installed.

The Stored Procedure
IF EXISTS ( SELECT  *
            FROM    sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[sp_GetRowsCountForAllTables]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[sp_GetRowsCountForAllTables]
GO

CREATE PROCEDURE sp_GetRowsCountForAllTables
    @DBName VARCHAR(128) = NULL
AS 
    SET nocount ON
    IF @DBName IS NULL 
        SET @DBName = DB_NAME()

    CREATE TABLE #a
        (
          TableName VARCHAR(128)
        , norows INT NULL
        , id INT IDENTITY(1, 1)
        )
 
    DECLARE @id INT
      , @maxID INT
      , @TableName VARCHAR(128)
      , @FKName VARCHAR(128)
      , @cmd NVARCHAR(1000)
      , @rc INT
      , @spcmd VARCHAR(1000)
 
    SET @cmd = 'exec ' + @DBName + '..sp_executesql N''insert #a (TableName) 
   select TABLE_NAME from information_schema.tables
   where TABLE_TYPE = ''''BASE TABLE'''' ''
  '
    EXEC (@cmd)
 
    SELECT  @id = 0
          , @maxID = MAX(id)
    FROM    #a
 
    WHILE @id < @maxID 
        BEGIN
            SELECT  @id = MIN(id)
            FROM    #a
            WHERE   id > @id
  
            SELECT  @TableName = TableName
            FROM    #a
            WHERE   id = @id
  
            SET @cmd = 'exec ' + @DBName
                + '..sp_executesql N''update #a set norows = (select rows from sysindexes where indid in (0,1) and id = object_id('''''
                + @TableName + '''''))'
            SET @cmd = @cmd + ' where #a.id = ' + CONVERT(VARCHAR(10), @id)
                + ''''
  
            EXEC  (@cmd)
            IF @rc <> 0
                OR @@error <> 0 
                BEGIN
                    RAISERROR('failed %s',16,-1,@TableName)
                    RETURN
                END
        END

    SELECT  *
    FROM    #a ORDER BY norows desc

    DROP TABLE #a
GO

The Output:

EXEC sp_GetRowsCountForAllTables



Finding Duplicates in a Table 's Column

3:36 AM
I assume You have Northwind Database.

I will be using The Employee Table.


As Show in the figure there are 6 Selected cells which are the Duplicates( Just assume it)
I want to find this number ( i mean 6.)

The query for the above is:

SELECT  Title
      , COUNT(Title) AS NumOccurrences
FROM    dbo.Employees
GROUP BY Title
HAVING  ( COUNT(Title) > 1 )

SELECT  *
FROM    dbo.Employees

Finding Total Number of Rows, Columns in a Database and Tables Sizes

3:24 AM
Here is the Script:

USE Northwind 
GO
CREATE TABLE #temp
    (
      table_name SYSNAME
    , row_count INT
    , reserved_size VARCHAR(50)
    , data_size VARCHAR(50)
    , index_size VARCHAR(50)
    , unused_size VARCHAR(50)
    )

SET NOCOUNT ON

INSERT  #temp
        EXEC sp_msforeachtable 'sp_spaceused ''?'''
SELECT  a.table_name
      , a.row_count
      , COUNT(*) AS col_count
      , a.data_size
FROM    #temp a
        INNER JOIN information_schema.columns b ON a.table_name COLLATE database_default = b.table_name COLLATE database_default
GROUP BY a.table_name
      , a.row_count
      , a.data_size
ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS INTEGER) DESC

DROP TABLE #temp


Output:


Check if a Perticular Database exist or not

3:13 AM

This is simple sql query:
USE master
Go


IF EXISTS ( SELECT  name
            FROM    sys.databases
            WHERE   name = 'MyDataBase' ) 
    PRINT 'Exists'
ELSE 
    PRINT 'Does Not Exists'

.Net Framework 3.0 Vs 3.5 Vs 4.0 (.Net FrameWork Comparisions)

12:09 AM


NET Framework 3.0 consists of four major new components:

  • Windows Presentation Foundation (WPF), formerly code-named Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies. See WPF SDK for developer articles and documentation on WPF.
  • Windows Communication Foundation (WCF), formerly code-named Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
  • Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
  • Windows CardSpace, formerly code-named InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website.


Changes in 3.5 since 3.0

  • New language features in C# 3.0 and VB.NET 9.0 compiler
  • Adds support for expression trees and lambda methods
  • Extension methods
  • Expression trees to represent high-level source code at runtime.
  • Anonymous types with static type inference
  • Language Integrated Query (LINQ) along with its various providers
  • LINQ to Objects
  • LINQ to XML
  • LINQ to SQL
  • Paging support for ADO.NET
  • ADO.NET synchronization API to synchronize local caches and server side datastores
  • Asynchronous network I/O API.
  • Peer-to-peer networking stack, including a managed PNRP resolver
  • Managed wrappers for Windows Management Instrumentation and Active Directory APIs
  • Enhanced WCF and WF runtimes, which let WCF work with POX and JSON data, and also expose WF workflows as WCF services. WCF services can be made stateful using the WF persistence model.
  • Support for HTTP pipelining and syndication feeds.
  • ASP.NET AJAX is included.


Key focuses for 4.0  release are:

  • Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls., are included.
  • New Visual Basic .NET and C# language features, such as statement lambdas, implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
  • Support for Code Contracts.
  • Inclusion of new types to work with arbitrary-precision arithmetic (System.Numerics.BigInteger) and complex numbers (System.Numerics.Complex).

Source: wikipedia.org

Encryption and Decryption Functions In Vb.net

11:00 PM
Imports:

Imports System.Security
Imports System.Security.Cryptography
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Text


Encryption:

Public Function Encrypt(ByVal plainText As String) As String

        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"

        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256

        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)


        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()

        symmetricKey.Mode = CipherMode.CBC

        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)

        Dim memoryStream As New MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)

        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Close()
        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
        Return cipherText
    End Function

Decryption

Public Function Decrypt(ByVal cipherText As String) As String
        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"

        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        ' Convert strings defining encryption key characteristics into byte
        ' arrays. Let us assume that strings only contain ASCII codes.
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8
        ' encoding.
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        ' Convert our ciphertext into a byte array.
        Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)

        ' First, we must create a password, from which the key will be 
        ' derived. This password will be generated from the specified 
        ' passphrase and salt value. The password will be created using
        ' the specified hash algorithm. Password creation can be done in
        ' several iterations.
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

        ' Use the password to generate pseudo-random bytes for the encryption
        ' key. Specify the size of the key in bytes (instead of bits).
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)

        ' Create uninitialized Rijndael encryption object.
        Dim symmetricKey As New RijndaelManaged()

        ' It is reasonable to set encryption mode to Cipher Block Chaining
        ' (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC

        ' Generate decryptor from the existing key bytes and initialization 
        ' vector. Key size will be defined based on the number of the key 
        ' bytes.
        Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)

        ' Define memory stream which will be used to hold encrypted data.
        Dim memoryStream As New MemoryStream(cipherTextBytes)

        ' Define cryptographic stream (always use Read mode for encryption).
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)

        ' Since at this point we don't know what the size of decrypted data
        ' will be, allocate the buffer long enough to hold ciphertext;
        ' plaintext is never longer than ciphertext.
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}

        ' Start decrypting.
        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)

        ' Close both streams.
        memoryStream.Close()
        cryptoStream.Close()

        ' Convert decrypted data into a string. 
        ' Let us assume that the original plaintext string was UTF8-encoded.
        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)

        ' Return decrypted string.   
        Return plainText
    End Function


Example:
Dim strEncryptedText  As String
strEncryptedText  =  Encrypt("yourEncryptionText")

Dim strDecrptedText As String
strDecrptedText = Decrypt(strEncryptedText)


You can easily set the passphrase, saltvalue and bits to your liking..

For More Info Go to:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx


Fill free to Comment ..

A Function to Concat String Array Values by Specified Delimiter

2:13 AM
Let 's Say I have Following Array:

string[] st = new string[5];
            st[0] = "Animation";
            st[1] = "Action";
            st[2] = "Romance";
            st[3] = "Drame";
            st[4] = "Comedy";

Now I want to Merge all of it with ',' Delimiter Like Below:

Output :   Animation,Action,Romance,Drame,Comedy

Here is the Function For the Above
public string GetAllStringsFromArrary(string[] strArray,string strDelimeter)
        {
            string strFinal = string.Empty;

            for (int i = 0; i < strArray.Length ; i++)
            {
                strFinal += strArray[i];

                if (i != strArray.Length - 1)
                {
                    strFinal += strDelimeter;
                }
            }
            return strFinal;
            

        }
We will Call it Like This:
string str = GetAllStringsFromArrary( st,",");

Reading Tags From Mp3 Files

1:54 AM
In this post i will show you how to read the Tags like Album,Artist,Song Title,Year etc from mp3 , avi , ogg, Asf, Divx, png etc..

You will need Taglib - Sharp Library for this purpose .

Download the Library : http://download.banshee.fm/taglib-sharp/

you will find taglib-sharp.dll That's what we need.

1. Create a project . Name it something like TagReader
2. Add reference to the taglib-sharp.dll
3. Make a Form look something like  below figure.





Most of the Coding is Understandable so i will put the Whole form's coding.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TagLib;

namespace TagReadermp3
{
    public partial class frmTagReader : Form
    {
        public frmTagReader()
        {
            InitializeComponent();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Mp3 Files | *.mp3";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                lblFile.Text = ofd.FileName;
            }

        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            TagLib.File mp3 = TagLib.File.Create(lblFile.Text);
            lblAlbum.Text = mp3.Tag.Album;
            lblAritst.Text = GetAllStringsFromArrary(mp3.Tag.AlbumArtists,",");   // Tag.AlbumAritst is a string array 
            lblBitsPerMinute.Text = mp3.Tag.BeatsPerMinute.ToString();
            lblComposers.Text = GetAllStringsFromArrary(mp3.Tag.Composers,",");
            lblCopyright.Text = mp3.Tag.Copyright;
            lblGenre.Text = GetAllStringsFromArrary(mp3.Tag.Genres,",");
            lblTitle.Text = mp3.Tag.Title;
            lblTrack.Text = mp3.Tag.Track.ToString();
            lblYear.Text = mp3.Tag.Year.ToString();
            lblLength.Text  = mp3.Properties.Duration.ToString();
        }

        public string GetAllStringsFromArrary(string[] strArray,string strDelimeter)
        {
            string strFinal = string.Empty;

            for (int i = 0; i < strArray.Length ; i++)
            {
                strFinal += strArray[i];

                if (i != strArray.Length - 1)
                {
                    strFinal += strDelimeter;
                }
            }
            return strFinal;
            

        }
    }
}

**New Length field added
Here is the Link to Complete Project : Tag Reader (Updated)
TagReader (old)

A Simple Gmail Client

3:42 AM
In This Post I will Guide u To making a Simple Gmail Client  to send Your Emails using Gmail Account Using Vb.net

 Let me Show You how final Result will Look Like:





1. For Sending Mail Through Vb.net. This Client Uses  "Imports System.Net.Mail".
    So First Import it to your Code





Imports System.Net.Mail

2. Layout All the Controls As Shown In the Above Figure

3. There is Progress Bar after the send Button. I have used Backgroud Worker To Send the Mail. So that When Mail Sending is in Progress the Screen Wont Stop Working.

4. Now Here is the Complete Code

First Define This In your Form

Dim msg As New MailMessage 
 Dim i As Integer 

Form's Load Event

Me.ProgressBar1.MarqueeAnimationSpeed = 0

Write This to Send Button's Click Event
msg.To.Add(Me.txtto.Text) 
        msg.From = New MailAddress(Me.txtuser.Text) 
        msg.Subject = Me.txtsubject.Text 
        msg.Body = Me.txtbody.Text 
        '' for attachment 
        For i = 0 To Me.ListBox1.Items.Count - 1 
            msg.Attachments.Add(New Attachment(Me.ListBox1.Items(i).ToString)) 
        Next 
        Me.Button1.Enabled = False 
        Me.Button1.Text = "Sendign.." 
        Me.ProgressBar1.Visible = True 
        Me.ProgressBar1.MarqueeAnimationSpeed = 100 
        Me.BackgroundWorker1.RunWorkerAsync()  


Attach Button's Click Event ( Button beside the listbox)
Dim d As New OpenFileDialog 
        d.ShowDialog() 
        Me.ListBox1.Items.Add(d.FileName.ToString()) 
        Me.ListBox1.Visible = True  


Now its the Back Ground Worker ...
Background worker's Do work Event:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 
        
        Dim i As Integer = 0 
        Dim smtp As New SmtpClient 
        smtp.Host = "smtp.gmail.com" 
        smtp.EnableSsl = True 
        smtp.Port = 587 
        smtp.Timeout = 300000 
        smtp.Credentials = New Net.NetworkCredential(Me.txtuser.Text, Me.txtpass.Text) 
        'Dim ms As MailMessage 
        'ms = e.Argument 
        Try 
            '  Label5.Text = "Sending Message......." 
            'Me.Button1.Text = "Sending...." 
            ' Me.Button1.Enabled = False 
            'Me.BackgroundWorker1.ReportProgress(i,  
            smtp.Send(msg) 
            e.Result = "Done" 
        Catch ex As Exception 
            'Label5.Text = "Sending Failed........" 
            MessageBox.Show(ex.ToString()) 
        End Try  

Background Worker's Run work Completed Event:
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted 
        ' Label5.Text = "Message Sending Complete" 
        Me.ProgressBar1.MarqueeAnimationSpeed = 0 
        Me.Button1.Text = "Send" 
        Me.Button1.Enabled = True 
        MessageBox.Show("Sent") 
    End Sub  

And It's Done.

For Complete Project Email me at sandeepparekh9@gmail.com

A Function to find strings Between a Given Word/string

3:27 AM
For example :
let's say you have following Text:
Title                    Author              Product*         
~~~~~                    ~~~~~~              ~~~~~~~~         
"Aurora's Eggs"          Douglas Niles       Story (Dragons 2)

The Dragons              Douglas Niles       Novel            

The Kinslayer Wars       Douglas Niles       Novel            

The Qualinesti           Paul B. Thompson    Novel            
                         & Tonya C. Cook

Vinas Solamnus           J. Robert King      Novel            

The Dargonesti           Paul B. Thompson    Novel            
                         & Tonya C. Cook

"Storytellers"           Nick O'Donohoe      Story (Dragons 2)

"The Best"               Margaret Weis       Story (Dragons 1)

"Quarry"                 Adam Lesh           Story (Dragons 2)

"Easy Pickings"          Douglas Niles       Story (Dragons 1)

The Legend of Huma       Richard A. Knaak    Novel            

And I want to find Everthing that is in between " character.

The Answer should be like Following

Aurora's Eggs

Storytellers

The Best

Quarry

Easy Pickings


For this use the following Function:


public static List FindStringBetween(string strData,string strFindWhat)
      {
          List lstFound = new List();
          int startIndex, EndIndex;
          startIndex = strData.IndexOf(strFindWhat);

          EndIndex = strData.IndexOf(strFindWhat, startIndex + strFindWhat.Length);

          if (EndIndex > 0)
          {
              lstFound.Add(strData.Substring(startIndex+strFindWhat.Length ,EndIndex - startIndex-strFindWhat.Length )); 
          }

          while (EndIndex > 0)
          {
              startIndex = strData.IndexOf(strFindWhat, EndIndex + 1);
              if (startIndex  == -1) {
                  return lstFound; }
                  EndIndex = strData.IndexOf(strFindWhat, startIndex + 1);
              if (EndIndex > 0)
              {
                  lstFound.Add(strData.Substring(startIndex + strFindWhat.Length, EndIndex - startIndex - strFindWhat.Length)); 
              }
          }

          return lstFound;
      }

Please ignore the last line.

It will give you the complete list of the strings found.


Gradient Panel With Shadow Support and Lots of Other Stuff

11:25 PM
Properties:

Source Code:


Variables
PointF pf;
        SizeF sf = new SizeF();

        public  enum ImageAlign
        {
            Custom,
            TopLeft,
            TopCenter,
            TopRight,
            MiddleLeft,
            MiddleCenter,
            MiddleRight,
            BottomLeft,
            BottomCenter,
            BottomRight
        }

        public enum TextAlign
        {
            Custom,
            TopLeft,
            TopCenter,
            TopRight,
            MiddleLeft,
            MiddleCenter,
            MiddleRight,
            BottomLeft,
            BottomCenter,
            BottomRight
        }


Properties
TextAlign  _TextAlign = TextAlign.TopLeft;
        [Browsable(true), Category("GradientPanel")]
        public TextAlign TxtAlign
        {
            get { return _TextAlign; }
            set { _TextAlign = value; Invalidate(); }
        }

        String  _Text;
        [Browsable(true), Category("GradientPanel")]
        public override string Text
        {
            get { return _Text; }
            set { _Text = value; Invalidate(); }
        }

        private float _TextMargin = 1.0f;
        [Browsable(true), Category("GradientPanel")]
        [DefaultValue("1.0f")]
        public float TextMargin
        {
            get { return _TextMargin; }
            set { _TextMargin = value; Invalidate(); }
        }
        
        ImageAlign _ImageAlign= ImageAlign.TopLeft;
        [Browsable(true), Category("GradientPanel")]
        public ImageAlign ImgAlign
        {
            get { return _ImageAlign; }
            set { _ImageAlign = value; Invalidate(); }
        }

        Image _Image;
        [Browsable(true), Category("GradientPanel")]
        public Image Image
        {
            get { return _Image; }
            set { _Image = value; Invalidate(); }
        }

        Point _ImageLocation = new Point(4, 4);
        [Browsable(true), Category("GradientPanel")]
        [DefaultValue("4,4")]
        public Point ImageLocation
        {
            get { return _ImageLocation; }
            set { _ImageLocation = value; Invalidate(); }
        }

        private float _ImageMargin = 1.0f;
        [Browsable(true), Category("GradientPanel")]
        [DefaultValue("1.0f")]
        public float ImageMargin
        {
            get { return _ImageMargin; }
            set { _ImageMargin = value; Invalidate(); }
        }


        int _BorderWidth = 1;
        [Browsable(true), Category("GradientPanel")]
        [DefaultValue(1)]
        public int BorderWidth
        {
            get { return _BorderWidth; }
            set { _BorderWidth = value; Invalidate(); }
        }

        int _ShadowOffSet = 5;
        [Browsable(true), Category("GradientPanel")]
        [DefaultValue(5)]
        public int Shadow
        {
            get
            {
                return _ShadowOffSet;
            }
            set { _ShadowOffSet = Math.Abs(value); Invalidate(); }
        }

         int _RoundCornerRadius = 4;
        [Browsable(true), Category("GradientPanel")]
        [DefaultValue(4)]
        public int CornerRadius
        {
            get { return _RoundCornerRadius; }
            set { _RoundCornerRadius = Math.Abs(value); Invalidate(); }
        }
      
        Color _BorderColor = Color.Gray;
        [Browsable(true), Category("GradientPanel")]
        [DefaultValue("Color.Gray")]
        public Color BorderColor
        {
            get { return _BorderColor; }
            set { _BorderColor = value; Invalidate(); }
        }

        Color _GradientStartColor = Color.White;
        [Browsable(true), Category("GradientPanel")]
        [DefaultValue("Color.White")]
        public Color GradientStartColor
        {
            get { return _GradientStartColor; }
            set { _GradientStartColor = value; Invalidate(); }
        }

        Color _GradientEndColor = Color.Gray;
        [Browsable(true), Category("GradientPanel")]
        [DefaultValue("Color.Gray")]
        public Color GradientEndColor
        {
            get { return _GradientEndColor; }
            set { _GradientEndColor = value; Invalidate(); }
        }

        LinearGradientMode _LinearGradientMode = LinearGradientMode.Vertical;
        [Browsable(true), Category("GradientPanel")]
        public LinearGradientMode GradientMode
        {
            get { return _LinearGradientMode; }
            set { _LinearGradientMode = value; Invalidate(); }
        }

        Boolean _DrawLine = false;
        [Browsable(true), Category("GradientPanel")]
        public Boolean DrawLine
        {
            get { return _DrawLine; }
            set { _DrawLine = value; Invalidate(); }
        }

        Color _LineColor = Color.Black;
        [Browsable(true), Category("GradientPanel")]
        public Color LineColor
        {
            get { return _LineColor; }
            set { _LineColor = value; Invalidate(); }
        }


Constructor
public GradientPanelR()
        {
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            InitializeComponent();
        }

Overriding OnPaintBackground method
protected override void OnPaintBackground(PaintEventArgs e)
        {
            base.OnPaintBackground(e);

            int tmpShadowOffSet = Math.Min(Math.Min(_ShadowOffSet, this.Width - 2), this.Height - 2);
            int tmpSoundCornerRadius = Math.Min(Math.Min(_RoundCornerRadius, this.Width - 2), this.Height - 2);
            if (this.Width > 1 && this.Height > 1)
            {
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                Rectangle rect = new Rectangle(0, 0, this.Width - tmpShadowOffSet - 1, this.Height - tmpShadowOffSet - 1);
                Rectangle rectShadow = new Rectangle(tmpShadowOffSet, tmpShadowOffSet, this.Width - tmpShadowOffSet - 1, this.Height - tmpShadowOffSet - 1);

                GraphicsPath graphPathShadow = GetRoundPath(rectShadow, tmpSoundCornerRadius);
                GraphicsPath graphPath = GetRoundPath(rect, tmpSoundCornerRadius);

                if (tmpSoundCornerRadius > 0)
                {
                    using (PathGradientBrush gBrush = new PathGradientBrush(graphPathShadow))
                    {
                        gBrush.WrapMode = WrapMode.Clamp;
                        ColorBlend colorBlend = new ColorBlend(3);
                        colorBlend.Colors = new Color[]{Color.Transparent, 
             Color.FromArgb(180, Color.DimGray), 
             Color.FromArgb(180, Color.DimGray)};

                        colorBlend.Positions = new float[] { 0f, .1f, 1f };

                        gBrush.InterpolationColors = colorBlend;
                        e.Graphics.FillPath(gBrush, graphPathShadow);
                    }
                }

                // Draw backgroud
                LinearGradientBrush brush = new LinearGradientBrush(rect,
                    this._GradientStartColor,
                    this._GradientEndColor,
                   GradientMode);
                e.Graphics.FillPath(brush, graphPath);
                e.Graphics.DrawPath(new Pen(Color.FromArgb(180, this._BorderColor), _BorderWidth), graphPath);

                // Draw Image
                if (_Image != null)
                {
                    //e.Graphics.DrawImageUnscaled(_Image, _ImageLocation);
                    DrawImage(e.Graphics);
                }


            }
            DrawText(e.Graphics);
        }

Drawing Image
#region DrawImage
        public void DrawImage(Graphics g)
        {
            

            if (this.Image != null && _ImageAlign != ImageAlign.Custom)
            {
                pf = new PointF(0, 0);

                if (_ImageAlign  == ImageAlign.TopLeft)
                {
                    pf.X = 1; pf.Y = 1;
                    pf.X += _ImageMargin;
                    pf.Y += _ImageMargin;

                    if (_DrawLine)
                    {
                       // HatchBrush hbr = new HatchBrush(HatchStyle.ZigZag , _LineColor );
                        Pen P = new Pen(_LineColor, 3);
                        g.DrawLine(P, new PointF(Image.Width + pf.X + 2 + 10, Image.Height + pf.Y + 2), new PointF(Width - 10, Image.Height + pf.Y + 2));
                    }

                }
                if (_ImageAlign == ImageAlign.TopCenter)
                {

                    pf.X = ((float)Width - (float)Image.Width) / 2;
                    pf.Y += _ImageMargin;
                }
                if (_ImageAlign == ImageAlign.TopRight)
                {

                    pf.X = (float)Width - (float)Image.Width;
                    pf.Y = 1;
                    pf.X -= _ImageMargin;
                    pf.Y += _ImageMargin;
                }

                if (_ImageAlign == ImageAlign.MiddleLeft)
                {

                    pf.X = 1;
                    pf.Y = ((float)Height - (float)Image.Height) / 2;
                    pf.X += _ImageMargin;

                }

                if (_ImageAlign == ImageAlign.MiddleCenter)
                {
                    pf.X = ((float)Width - (float)Image.Width) / 2;
                    pf.Y = ((float)Height - (float)Image.Height) / 2;

                }
                if (_ImageAlign == ImageAlign.MiddleRight)
                {
                    pf.X = (float)Width - (float)Image.Width;
                    pf.Y = ((float)Height - (float)Image.Height) / 2;
                    pf.X -= _ImageMargin;

                }

                if (_ImageAlign == ImageAlign.BottomLeft)
                {
                    pf.X = 1;
                    pf.Y = ((float)Height - (float)Image.Height);
                    pf.X += _ImageMargin;
                    pf.Y -= _ImageMargin;
                }
                if (_ImageAlign == ImageAlign.BottomCenter)
                {
                    pf.X = ((float)Width - (float)Image.Width) / 2;
                    pf.Y = ((float)Height - (float)Image.Height);

                    pf.Y -= _ImageMargin;
                }
                if (_ImageAlign == ImageAlign.BottomRight)
                {
                    pf.X = (float)Width - (float)Image.Width;
                    pf.Y = ((float)Height - (float)Image.Height);

                    pf.X -= _ImageMargin;
                    pf.Y -= _ImageMargin;

                }

                g.DrawImage(this.Image, pf);
            }
            if (this.Image != null && _ImageAlign == ImageAlign.Custom)
            {
                pf = new PointF(0, 0);
                pf.X = _ImageLocation.X ;
                pf.Y = _ImageLocation.Y;
                
                g.DrawImage(this.Image, pf);
            }
        }
        #endregion

Drawing Text
#region DrawText
          public void DrawText(Graphics g)
        {
            SolidBrush b = new SolidBrush(this.ForeColor);

            pf = new PointF();
            sf = g.MeasureString(this.Text, this.Font);

            //calculate textalign
            if (_TextAlign == TextAlign.TopLeft)
            {
                pf.X = 1 + _TextMargin ; pf.Y = 1 + _TextMargin ;
            }
            if (this._TextAlign == TextAlign.TopCenter)
            {
                
                pf.X = ((float)Width - sf.Width) / 2;
                pf.Y =1 + _TextMargin ; 
            }
            if (this._TextAlign == TextAlign.TopRight)
            {
                
                pf.X = (float)Width - sf.Width  - _TextMargin ;
                pf.Y = 1 + _TextMargin ;
            }

            if (this._TextAlign == TextAlign.MiddleLeft)
            {
                
                pf.X = 1 + _TextMargin ;
                pf.Y =( (float)Height - sf.Height) / 2;
            }

            if (this._TextAlign == TextAlign.MiddleCenter)
            {
                pf.X = ((float)Width - sf.Width) / 2;
                pf.Y = ((float)Height - sf.Height) / 2;
            }
            if (this._TextAlign == TextAlign.MiddleRight)
            {
                pf.X = (float)Width - sf.Width - _TextMargin ;
                pf.Y = ((float)Height - sf.Height) / 2;
            }

            if (this._TextAlign == TextAlign.BottomLeft)
            {
                pf.X = 1 + _TextMargin ;
                pf.Y = ((float)Height - sf.Height) - _TextMargin ;
            }
            if (this._TextAlign == TextAlign.BottomCenter)
            {
                pf.X = ((float)Width - sf.Width) / 2;
                pf.Y = ((float)Height - sf.Height) - _TextMargin ;
            }
            if (this._TextAlign == TextAlign.BottomRight)
            {
                pf.X = (float)Width - sf.Width - _TextMargin;
                pf.Y = ((float)Height - sf.Height) - _TextMargin ;
            }

            //g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias ;
            g.DrawString(this.Text, this.Font, b, pf);
            
        }
       
        #endregion

Other Helping Methods
public static GraphicsPath GetRoundPath(Rectangle r, int depth)
        {
            GraphicsPath graphPath = new GraphicsPath();

            graphPath.AddArc(r.X, r.Y, depth, depth, 180, 90);
            graphPath.AddArc(r.X + r.Width - depth, r.Y, depth, depth, 270, 90);
            graphPath.AddArc(r.X + r.Width - depth, r.Y + r.Height - depth, depth, depth, 0, 90);
            graphPath.AddArc(r.X, r.Y + r.Height - depth, depth, depth, 90, 90);
            graphPath.AddLine(r.X, r.Y + r.Height - depth, r.X, r.Y + depth / 2);

            return graphPath;
        }

For Complete source mail me at : sandeepparekh9@gmail.com

Dashed Label [Design Mode Only]

10:55 PM
Sometimes you have so many controls on your design form that can make you confused.  So i have developed a Dashed Label Control which provide each control a boundry in Design Mode only. For better Understanding see the Screen Shots Below:


Design Mode

At Run Time

I hope your getting what i am saying.

Now to the Code.

1. Add a custom Control to your project. Name is DashedLabel (or anything you like.)
2. Now on its Paint Event Write the following Code.

private void DashedLabel_Paint(object sender, PaintEventArgs e)
        {
            if (this.DesignMode)
            {
                using (Pen pen = new Pen(Color.Gray))
                {
                    pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                    e.Graphics.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
                }
            }
        }

That's it.

Complete Project : Dashed Label

3d - Pie Chart [Transparent]

10:19 PM
3d- Pie chart Control for .net Framework

This one is not Made By me.
Reference: http://www.codeproject.com/KB/graphics/julijanpiechart.aspx

Dll:  You can Download The Control Dll from above website.

Now for the Coding :

Simply add the dll to your project through : ToolBox -> Choose items > Your Dll
You will see a  Pie chart Control in your Tool box of the Visual Studio

Drag and drop it to a form.

Write the following code on Form's Load event.

private void Form1_Load(object sender, EventArgs e)
        {
            pcc1.Values = new decimal[] { 10, 15, 5, 35 };
            int alpha = 80;
            pcc1.Colors = new Color[] { Color.FromArgb(alpha, Color.Red), 
                                    Color.FromArgb(alpha, Color.Green), 
                                    Color.FromArgb(alpha, Color.Yellow), 
                                    Color.FromArgb(alpha, Color.Blue) };

            pcc1.SliceRelativeDisplacements = new float[] { 0.1F, 0.2F, 0.2F, 0.2F };

            pcc1.Texts = new string[] { "red", 
                                    "green", 
                                    "blue", 
                                    "yellow" };

            pcc1.ToolTips = new string[] { "Peter", 
                                       "Paul", 
                                       "Mary", 
                                       "Brian" };

            pcc1.Font = new Font("Arial", 10F);
            pcc1.ForeColor = SystemColors.WindowText;
            pcc1.LeftMargin = 10F;
            pcc1.RightMargin = 10F;
            pcc1.TopMargin = 10F;
            pcc1.BottomMargin = 10F;
            pcc1.SliceRelativeHeight = 0.25F;
            pcc1.InitialAngle = -90F;
            
        }

This is just a Demo of how the Control works
pcc1 is the Pie chart Control's Name

Complete Project: 3d -Pie Chart

A Transparent Textbox

5:13 AM

I have tried so hard to find a transparent textbox on the web but all in vain.
so i have tried to create a one..

This a User Control not a Custom Control so it has less functionality that the traditional texbox but i have tried to cover most of the important properties.

here are some pics..





This Control is inherited from UserControl


Properties:


#region Properties
        [Browsable(false), Category("Appearance")]
        public override Font Font
        {
            get
            {
                return base.Font;
            }
            set
            {
                base.Font = value;
            }
        }

        [Browsable(false), Category("Appearance")]
        public override Color ForeColor
        {
            get
            {
                return base.ForeColor;
            }
            set
            {
                base.ForeColor = value;
            }
        }

        [Browsable(false), Category("Appearance")]
        public override Color BackColor
        {
            get
            {
                return base.BackColor;
            }
            set
            {
                base.BackColor = value;
            }
        }

        [Browsable(false), Category("Appearance")]
        public override Image BackgroundImage
        {
            get
            {
                return base.BackgroundImage;
            }
            set
            {
                base.BackgroundImage = value;
            }
        }

        [Browsable(false), Category("Appearance")]
        public override ImageLayout BackgroundImageLayout
        {
            get
            {
                return base.BackgroundImageLayout;
            }
            set
            {
                base.BackgroundImageLayout = value;
            }
        }


        [Browsable(true), Category("Appearance")]
        public  Font  _Font
        {
            get { return this.Font; }
            set
            {
                txt.Font = value;
                lbl.Font = value;
                Invalidate();
            }
        }

        [Browsable(true), Category("Appearance")]
        public  Color _ForeColor
        {
            get { return this.ForeColor; }
            set
            {
                txt.ForeColor = value;
                lbl.ForeColor = value;
                this.ForeColor = value;
                Invalidate();
            }
        }

        [Browsable(true), Category("Appearance")]
        public  Color _BackColor
        {
            get { return this.BackColor; }
            set
            {
                if (value != Color.Transparent) { txt.BackColor = value; this.BackColor = value; }
                Invalidate();
            }
        }

        [Browsable(true), Category("Appearance")]
        public ScrollBars _ScrollBars
        {
            get { return txt.ScrollBars; }
            set { txt.ScrollBars = value; Invalidate(); }
        }

        [Browsable(true), Category("Appearance")]
        public string Text
        {
            get { return txt.Text; }
            set { txt.Text = value; lbl.Text = value; Invalidate(); }
        }

        [Browsable(true), Category("Appearance")]
        public string[] _Lines
        {
            get { return txt.Lines; }
            set { txt.Lines = value; Invalidate(); }

        }

        [Browsable(true), Category("Appearance")]
        public HorizontalAlignment _TextAlignMent
        {
            get { return txt.TextAlign; }
            set 
            {   txt.TextAlign = value;
                if (value == HorizontalAlignment.Center) { lbl.TextAlign = ContentAlignment.TopCenter; }
                if (value == HorizontalAlignment.Left ) { lbl.TextAlign = ContentAlignment.TopLeft ; }
                if (value == HorizontalAlignment.Right) { lbl.TextAlign = ContentAlignment.TopRight ; }
                Invalidate();
            }
        }

        [Browsable(true), Category("Behavior")]
        public bool AcceptsTab
        {
            get { return txt.AcceptsTab; }
            set { txt.AcceptsTab = value; Invalidate(); }
        }

        [Browsable(true), Category("Behavior")]
        public bool AcceptsReturn
        {
            get { return txt.AcceptsReturn ; }
            set { txt.AcceptsReturn = value; Invalidate(); }
        }

        [Browsable(true), Category("Behavior")]
        public override bool AllowDrop
        {
            get { return txt.AllowDrop; }
            set { txt.AllowDrop = value; lbl.AllowDrop = value; Invalidate(); }
            
        }

        [Browsable(true), Category("Behavior")]
        public CharacterCasing CharacterCasing
        {
            get { return txt.CharacterCasing; }
            set { txt.CharacterCasing = value; Invalidate(); }
        }

        [Browsable(true), Category("Behavior")]
        public bool HideSelection
        {
            get { return txt.HideSelection; }
            set { txt.HideSelection = value; Invalidate(); }
        }

        [Browsable(true), Category("Behavior")]
        public int MaxLength
        {
            get { return txt.MaxLength; }
            set { txt.MaxLength = value; Invalidate(); }
        }

        [Browsable(true), Category("Behavior")]
        public char PasswordChar
        {
            get { return txt.PasswordChar; }
            set { 
                    txt.PasswordChar = value;
                    lbl.Text ="";
                    for (int i = 0; i < value.ToString().Length; i++)
                    {
                        lbl.Text += PasswordChar;
                    }
                    Invalidate();
                }
        }

        [Browsable(true), Category("Behavior")]
        public bool Multiline
        {
            get { return txt.Multiline; }
            set { txt.Multiline = value; }
        }

        [Browsable(true), Category("Behavior")]
        public bool ReadOnly
        {
            get { return txt.ReadOnly; }
            set { txt.ReadOnly = value; }
        }

        [Browsable(true), Category("Behavior")]
        public bool ShortcutsEnabled
        {
            get { return txt.ShortcutsEnabled; }
            set { txt.ShortcutsEnabled = value; Invalidate(); }
        }

        [Browsable(true), Category("Behavior")]
        public bool UseSystemPasswordChar
        {
            get { return txt.UseSystemPasswordChar; }
            set { txt.UseSystemPasswordChar = value; Invalidate(); }
        }
        
        [Browsable(true), Category("Behavior")]
        public bool WordWrap
        {
            get { return txt.WordWrap; }
            set { txt.WordWrap = value; }
        }

        [Browsable(true), Category("Misc")]
        public AutoCompleteStringCollection AutoCompleteCustomSource
        {
            get { return txt.AutoCompleteCustomSource; }
            set { txt.AutoCompleteCustomSource = value; }
        }

        [Browsable(true), Category("Misc")]
        public AutoCompleteMode AutoCompleteMode
        {
            get { return txt.AutoCompleteMode;  }
            set { txt.AutoCompleteMode= value; }
        }

        [Browsable(true), Category("Misc")]
        public AutoCompleteSource  AutoCompleteSource
        {
            get { return txt.AutoCompleteSource;  }
            set { txt.AutoCompleteSource = value; }
        }
        #endregion

        #region Events
        [Browsable(true), Category("Misc")]
        public event EventHandler TextChanged
        {
            add { txt.TextChanged += value; }
            remove { txt.TextChanged -= value; }
        }

        #endregion
Other Importand Event and Methods
#region Events
        [Browsable(true), Category("Misc")]
        public event EventHandler TextChanged
        {
            add { txt.TextChanged += value; }
            remove { txt.TextChanged -= value; }
        }

        #endregion

        private void lbl_MouseEnter(object sender, EventArgs e)
        {
            if (txt.PasswordChar != '\0')// && txt.PasswordChar.ToString() != "")
            {
                lbl.Text = "";
                for (int i = 0; i < txt.Text.ToString().Length; i++)
                {
                    lbl.Text += PasswordChar;
                }
            }
            else
            {
                lbl.Text = txt.Text;
            }
            txt.BringToFront();
            lbl.SendToBack();
            txt.Focus();
        }
        public void Clear()
        {
            txt.Clear();
            lbl.Text = "";
        }

        private void txt_MouseLeave(object sender, EventArgs e)
        {
            
            txt.SendToBack();
            lbl.BringToFront();
            if (txt.PasswordChar != '\0')
            {
                lbl.Text = "";
                for (int i = 0; i < txt.Text.ToString().Length; i++)
                {
                    lbl.Text += PasswordChar;
                }
            }
            else
            {
                lbl.Text = txt.Text;
            }
        }

        private void TransTextBoxR_Load(object sender, EventArgs e)
        {
            if (txt.PasswordChar != '\0')
            {
                lbl.Text = "";
                for (int i = 0; i < txt.Text.ToString().Length; i++)
                {
                    lbl.Text += PasswordChar;
                }
            }
            else
            {
                lbl.Text = txt.Text;
            }
        }
For Full Source Code email me at : sandeepparekh9@gmail.com

A Professional Looking Label

4:23 AM
A Professional Looking Label

Some Picks:
Without Glossy Effect


With Glossy Effect


Coding
This on Inherits Label So
public partial class ProfLabel : Label

Properties
  public string _Text;

        private Color _SecondBackColor = Color.Silver;
        public Color SecondBackColor
        {
            get { return _SecondBackColor; }
            set { _SecondBackColor = value; Invalidate(); }
        }

        private bool _IsGlossyeffect = false;
        public bool GlossyEffect
        {
            get { return _IsGlossyeffect; }
            set { _IsGlossyeffect = value; Invalidate(); }
        }

        private int _BottomLineWidth = 3;
        public int BottomLineWidth
        {
            get { return _BottomLineWidth; }
            set { _BottomLineWidth = value; Invalidate(); }
        }

Now Override the OnPaint Method

 protected override void OnPaint(PaintEventArgs pe)
        {
           
            pe.Graphics.FillRectangle(new SolidBrush(Color.Transparent), this.ClientRectangle);

            _Text = this.Text;
            
            this.AutoSize = false;
            SizeF size = pe.Graphics.MeasureString(_Text, this.Font);

            Rectangle r = new Rectangle();
            r.Size = new Size(int.Parse((Math.Round(size.Width)+2).ToString()),int.Parse(( Math.Round(size.Height)+2).ToString()));
            r.Location = new Point(5, 5);


            SolidBrush b = new SolidBrush(_SecondBackColor);
            pe.Graphics.FillPath(b, GetRoundPath(r, 3));


            if (_IsGlossyeffect)
            {
                Rectangle upperrect = new Rectangle();
                upperrect.Location = new Point(5, 5);
                upperrect.Width = r.Width;
                upperrect.Height = r.Height / 2;

                GraphicsPath upPath = GetRoundPath(upperrect, 3);

                using (Brush brushUpper = new LinearGradientBrush(upperrect, Color.White, _SecondBackColor, LinearGradientMode.Vertical))
                {
                    pe.Graphics.FillPath(brushUpper, upPath);
                }
            }
            
            Point pDrawStrPoint = new Point();
            pDrawStrPoint.X = 5;
            pDrawStrPoint.Y = 5;
            pe.Graphics.DrawString(_Text, this.Font, new SolidBrush(this.ForeColor), pDrawStrPoint);
            
            //Drawing Fine Line
            Point startPoint = new Point();
            startPoint.X = r.Left;
            startPoint.Y = r.Bottom;

            Point endpoint = new Point();
            endpoint.X = this.Width;
            endpoint.Y = r.Bottom;
            pe.Graphics.DrawLine(new Pen(_SecondBackColor, _BottomLineWidth), startPoint, endpoint);
         
        }
Other Helping Functions
 public static GraphicsPath GetRoundPath(Rectangle r, int depth)
        {
            GraphicsPath graphPath = new GraphicsPath();

            graphPath.AddArc(r.X, r.Y, depth, depth, 180, 90);
            graphPath.AddArc(r.X + r.Width - depth, r.Y, depth, depth, 270, 90);
            graphPath.AddArc(r.X + r.Width - depth, r.Y + r.Height - depth, depth, depth, 0, 90);
            graphPath.AddArc(r.X, r.Y + r.Height - depth, depth, depth, 90, 90);
            graphPath.AddLine(r.X, r.Y + r.Height - depth, r.X, r.Y + depth / 2);

            return graphPath;
        }

For Complete Source code email me at : sandeepparekh9@gmail.com

Extended Label Control

3:46 AM
Here comes a Custom Label Control

A pic to controls Extended Properties and Control




i have created a smart tag for this one.. like those in Microsoft controls..
See the below Pic

Here is the Coding :

This Control Inherits the Label so:
public partial class ExtendedLabelR : Label


Add the Below Line before the custom control class defination (for Smart Tag to work)
[Designer(typeof(ExtendedLabelRDesigner))]


Properties:
private Boolean _Left = false;
        [Browsable(true), Category("Extended Properties")]
        public Boolean LeftLine
        {
            get { return _Left; }
            set
            {
                _Left = value;
                Invalidate();
            }
        }

        private Boolean _Right = false;
        [Browsable(true), Category("Extended Properties")]
        public Boolean RightLine
        {
            get { return _Right; }
            set
            {
                _Right = value;
                Invalidate();
            }
        }

        private Boolean _Top = false;
        [Browsable(true), Category("Extended Properties")]
        public Boolean TopLine
        {
            get { return _Top; }
            set
            {
                _Top = value;
                Invalidate();
            }
        }

        private Boolean _Bottom = false;
        [Browsable(true), Category("Extended Properties")]
        public Boolean BottomLine
        {
            get { return _Bottom; }
            set
            {
                _Bottom = value;
                Invalidate();
            }
        }

        private Boolean _All = false;
        [Browsable(true), Category("Extended Properties")]
        public Boolean All
        {
            get { return _All; }
            set
            {
                _All = value;
                _Left = false;
                _Right = false;
                _Top = false;
                _Bottom = false;
                Invalidate();
            }
        }

        private System.Drawing.Drawing2D.DashStyle _LineStype;
        [Browsable(true), Category("Extended Properties")]
        public System.Drawing.Drawing2D.DashStyle LineStype
        {
            get { return _LineStype; }
            set
            {
                _LineStype = value;
                Invalidate();
            }
        }

        private Color _LineColor;
        [Browsable(true), Category("Extended Properties")]
        public Color LineColor
        {
            get { return _LineColor; }
            set { _LineColor = value; Invalidate(); }
        }

        private float  _LineWidth=1;
        [Browsable(true), Category("Extended Properties")]
        public float  LineWidth
        {
            get { return _LineWidth; }
            set { _LineWidth = value; Invalidate(); }
        }

Now we will override the OnPaintBackground for the Lines Painting

protected override void OnPaintBackground(PaintEventArgs e)
        {
            base.OnPaintBackground(e);

            using (Pen p = new Pen(_LineColor,_LineWidth))
            {
                p.DashStyle = _LineStype;
                Point start;
                Point end;

                if (_All)
                {
                    e.Graphics.DrawRectangle(p, 1, 1, this.Width - 2, this.Height - 2);
                }
                else
                {

                    if (_Left)
                    {
                        start = new Point(1, 1);
                        end = new Point(1, this.Height - 1);
                        e.Graphics.DrawLine(p, start, end);
                    }

                    if (_Right)
                    {
                        start = new Point(this.Width - 1, 1);
                        end = new Point(this.Width - 1, this.Height - 1);
                        e.Graphics.DrawLine(p, start, end);
                    }

                    if (_Top)
                    {
                        start = new Point(1, 1);
                        end = new Point(this.Width - 1, 1);
                        e.Graphics.DrawLine(p, start, end);
                    }

                    if (_Bottom)
                    {
                        start = new Point(1, this.Height - 1);
                        end = new Point(this.Width - 1, this.Height - 1);
                        e.Graphics.DrawLine(p, start, end);
                    }
                }
                
            }
        }

Smart Tag Coding

#region "Smart Tag Code"
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    public class ExtendedLabelRDesigner : System.Windows.Forms.Design.ControlDesigner
    {
        private DesignerActionListCollection actionLists;
        public override DesignerActionListCollection ActionLists
        {
            get
            {
                if (null == actionLists)
                {
                    actionLists = new DesignerActionListCollection();
                    actionLists.Add(new ExtendedLabelRActionList(this.Component));
                }
                return actionLists;
            }
        }
    }

    public class ExtendedLabelRActionList : System.ComponentModel.Design.DesignerActionList
    {
        private ExtendedLabelR objExtendedLabel;
        private DesignerActionUIService designerActionUISvc = null;

        public ExtendedLabelRActionList(IComponent component)    : base(component) 
        {
            this.objExtendedLabel = component as ExtendedLabelR;
            // Cache a reference to DesignerActionUIService, so the
            // DesigneractionList can be refreshed.
            this.designerActionUISvc =GetService(typeof(DesignerActionUIService)) as DesignerActionUIService;
        }

        private PropertyDescriptor GetPropertyByName(String propName)
        {
            PropertyDescriptor prop;
            prop = TypeDescriptor.GetProperties(objExtendedLabel)[propName];
            if (null == prop)
                throw new ArgumentException("Matching ExtendedLabelR property not found!",propName);
            else
                return prop;
        }

        
        public Boolean LeftLine
        {
            get { return objExtendedLabel.LeftLine; }
            set
            {
                GetPropertyByName("LeftLine").SetValue(objExtendedLabel, value);
            }
        }

        public Boolean RightLine
        {
            get { return objExtendedLabel.RightLine ; }
            set
            {
                GetPropertyByName("RightLine").SetValue(objExtendedLabel, value);
            }
        }

        public Boolean TopLine
        {
            get { return objExtendedLabel.TopLine ; }
            set
            {
                GetPropertyByName("TopLine").SetValue(objExtendedLabel, value);
            }
        }

        public Boolean BottomLine
        {
            get { return objExtendedLabel.BottomLine ; }
            set
            {
                GetPropertyByName("BottomLine").SetValue(objExtendedLabel, value);
            }
        }

        public Boolean All
        {
            get { return objExtendedLabel.All; }
            set
            {
                GetPropertyByName("All").SetValue(objExtendedLabel, value);
            }
        }

        public float LineWidth
        {
            get { return objExtendedLabel.LineWidth; }
            set
            {
                GetPropertyByName("LineWidth").SetValue(objExtendedLabel, value);
            }
        }
        public Color LineColor
        {
            get { return objExtendedLabel.LineColor; }
            set 
            {
                GetPropertyByName("LineColor").SetValue(objExtendedLabel, value);
            }
        }

        public override DesignerActionItemCollection GetSortedActionItems()
        {
            DesignerActionItemCollection items = new DesignerActionItemCollection();
            items.Add(new DesignerActionHeaderItem("Draw Lines"));

            items.Add(new DesignerActionPropertyItem("LeftLine","Left Line","Draw Lines","Should Draw Left Line?"));
            items.Add(new DesignerActionPropertyItem("RightLine", "Right Line", "Draw Lines", "Should Draw Right Line?"));
            items.Add(new DesignerActionPropertyItem("TopLine", "Top Line", "Draw Lines", "Should Draw Top Line?"));
            items.Add(new DesignerActionPropertyItem("BottomLine", "Bottom Line", "Draw Lines", "Should Draw Bottom Line?"));
            items.Add(new DesignerActionPropertyItem("All", "All Line", "Draw Lines", "Should Draw All Line?"));
            items.Add(new DesignerActionPropertyItem("LineWidth", "Line Width", "Draw Lines", "Width of The Line"));
            items.Add(new DesignerActionPropertyItem("LineColor", "Line Color", "Draw Lines", "Color of The Line"));
            return items;
        }

    }
    #endregion

If you want the Complete Source Code then mail me on : sandeepparekh9@gmaill.com

A Custom ListBox Control

3:30 AM
Here is Another User Control

A pick to of The Control:
As you can see this one contains a Listbox and 7 buttons for the Add,Remove,up,down,,RemoveAll,Top,Bottom etc
1. Add a user control to project. Add a list box and 7 button as show in the figure.
Coding:
Properties



This is For Left/Right Side Buttons Docking

public bool _blnLeftSideButtons = false;
        public bool LeftSideButtons
        {
            get { return _blnLeftSideButtons; }
            set {
                _blnLeftSideButtons = value;

                if (_blnLeftSideButtons)
                {
                    lstList.Dock = DockStyle.None;
                    flowLayoutPanel1.Dock = DockStyle.Left;
                    lstList.Dock = DockStyle.Fill;
                    Invalidate();
                }
                else
                {
                    lstList.Dock = DockStyle.None;
                    flowLayoutPanel1.Dock = DockStyle.Right;
                    lstList.Dock = DockStyle.Fill;
                    Invalidate();
                }

                }
        }


Add Button Coding

private void btnAdd_Click(object sender, EventArgs e)
        {
            ofD = new OpenFileDialog();
            ofD.Multiselect = true;
            ofD.Filter = "Image Files(*.gif,*.jpg,*.jpeg,*.bmp,*.png,*.wmf)|*.gif;*.jpg;*.jpeg;*.bmp;*.png;*.wmf";

            if (ofD.ShowDialog() == DialogResult.OK)
            {
                if (ofD.FileNames.Length > 0)
                {
                    for (int i = 0; i < ofD.FileNames.Length; i++)
                    {
                        lstList.Items.Add(Path.GetFileName( ofD.FileNames[i].ToString()));
                    }
                }
            }

        }
Remove Button Coding
//Remove item
        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (lstList.Items.Count > 0 && lstList.SelectedIndex > 0)
            {
                lstList.Items.RemoveAt(lstList.SelectedIndex);
            }
        }
Move An Item Up
// item Up
        private void btnUp_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstList.SelectedItems.Count == 0) { return; }

                int index = lstList.Items.IndexOf(lstList.SelectedItems[0]);

                if ((index - 1) < 0) { return; }

                object[] obj = new object[lstList.SelectedItems.Count];

                for (int i = 0; i < lstList.SelectedItems.Count; i++)
                {
                    obj[i] = lstList.SelectedItems[i];
                }

                lstList.SelectedIndices.Clear();

                for (int j = 0; j < obj.Length; j++)
                {

                    int temp_I = lstList.Items.IndexOf(obj[j]);
                    lstList.Items.RemoveAt(temp_I);
                    lstList.Items.Insert(temp_I - 1, obj[j]);

                    lstList.SelectedIndices.Add(temp_I - 1);

                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }
Move An Item Down
//item down
        private void btnDown_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstList.SelectedItems.Count == 0) { return; }

                int index = lstList.Items.IndexOf(lstList.SelectedItems[0]);

                if (index == lstList.Items.Count - 1) { return; }

                
                if ((index + 1) > lstList.Items.Count) { return; }

                object[] obj = new object[lstList.SelectedItems.Count];

                for (int i = 0; i < lstList.SelectedItems.Count; i++)
                {
                    obj[i] = lstList.SelectedItems[i];
                }

                lstList.SelectedIndices.Clear();

                for (int j = 0; j < obj.Length; j++)
                {


                    int temp_J = lstList.Items.IndexOf(obj[j]);
                    lstList.Items.RemoveAt(temp_J);
                    lstList.Items.Insert(temp_J + 1, obj[j]);

                    lstList.SelectedIndices.Add(temp_J + 1);

                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }

Move An Item To Top
//Top
        private void btnTop_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstList.Items.Count == 0 ) { return; }

                int index = lstList.SelectedIndices[0];
                object obj = new object();
                obj = lstList.SelectedItems[0];

                lstList.Items.RemoveAt(index);
                lstList.Items.Insert(0, obj);

                lstList.SelectedIndices.Clear();
                lstList.SelectedIndices.Add(0);

            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }
Move item to Bottom
//Bottom
        private void btnBottom_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstList.Items.Count == 0) { return; }

                int index = lstList.SelectedIndices[0];
                object obj = new object();
                obj = lstList.SelectedItems[0];

                lstList.Items.RemoveAt(index);
                lstList.Items.Insert(lstList.Items.Count , obj);

                lstList.SelectedIndices.Clear();
                lstList.SelectedIndices.Add(lstList.Items.Count - 1);

            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }
Remove All Items:
//Remove All
        private void btnRemoveAll_Click(object sender, EventArgs e)
        {
            if (lstList.Items.Count > 0)
            {
                if (MessageBox.Show("This Will Delete All The Items", "Are You Sure?", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    lstList.Items.Clear();
                }
            }
        }
For the Source code mail me at: sandeepparekh9@gmail.com

Extended RichTextBox Control

3:10 AM
hi. I really needed a Richtext box with Word like functionality.. i mean Bold,Italic etc etc Function. So i decided to write a Custom Control for this Purpose.

Extended RichTextBox Contains Following Controls

1. Rich Text Box [ rtxtBox ]
2. A tool Strip with Basic button including word Formatting Functionality.. [ tsStrip ]
3. A font Dialog [ fntD ], Color Dialog [ clrD ], OpenFileDialog [ ofD ]
here is a pic.

1. First Add a RichText box and a tool strip as show in figure to your Custom Control.
2. Add basic buttons to tool strip according to screen shot (You can add your own image to buttons)
3. And here is the coding..

Add This Properties to your Custom Control


[Browsable(true), Category("Appearance")] 
        public override Font Font 
        { 
            get { return rtxtBox.Font  ; } 
            set { rtxtBox.Font  = value; 
                Invalidate(); } 
        } 
        [Browsable(true), Category("Appearance")] 
        public override Color  BackColor 
        { 
            get { return rtxtBox.BackColor ; } 
            set 
            { 
                rtxtBox.BackColor  = value; 
                Invalidate(); 
            } 
        } 
        [Browsable(true), Category("Appearance")] 
        public override Color ForeColor 
        { 
            get { return rtxtBox.ForeColor ; } 
            set 
            { 
                rtxtBox.ForeColor  = value; 
                Invalidate(); 
            } 
        } 
         
        [Browsable(true), Category("Appearance")] 
        public  string[]  Lines 
        { 
            get { return rtxtBox.Lines; } 
            set { rtxtBox.Lines = value; } 
        } 
        [Browsable(true), Category("Appearance")] 
        public RichTextBoxScrollBars ScrollBars 
        { 
            get { return rtxtBox.ScrollBars; } 
            set { rtxtBox.ScrollBars = value; } 
        } 
        [Browsable(true), Category("Appearance")] 
        public override string Text 
        { 
            get { return rtxtBox.Text;  } 
            set { rtxtBox.Text = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool AcceptsTab 
        { 
            get { return rtxtBox.AcceptsTab;  } 
            set { rtxtBox.AcceptsTab = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool AutoWordSelection 
        { 
            get { return rtxtBox.AutoWordSelection; } 
            set { rtxtBox.AutoWordSelection = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public int BulletIndent 
        { 
            get { return rtxtBox.BulletIndent; } 
            set { rtxtBox.BulletIndent  = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool DetectUrls 
        { 
            get { return rtxtBox.DetectUrls; } 
            set { rtxtBox.DetectUrls  = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool EnableAutoDragDrop 
        { 
            get { return rtxtBox.EnableAutoDragDrop ; } 
            set { rtxtBox.EnableAutoDragDrop = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool HideSelection 
        { 
            get { return rtxtBox.HideSelection ; } 
            set { rtxtBox.HideSelection = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public int MaxLength 
        { 
            get { return rtxtBox.MaxLength ; } 
            set { rtxtBox.MaxLength = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool Multiline 
        { 
            get { return rtxtBox.Multiline ; } 
            set { rtxtBox.Multiline = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool ReadOnly 
        { 
            get { return rtxtBox.ReadOnly ; } 
            set { rtxtBox.ReadOnly = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public int RightMargin 
        { 
            get { return rtxtBox.RightMargin ; } 
            set { rtxtBox.RightMargin = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool ShortcutsEnabled 
        { 
            get { return rtxtBox.ShortcutsEnabled; } 
            set { rtxtBox.ShortcutsEnabled = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool ShowSelectionMargin 
        { 
            get { return rtxtBox.ShowSelectionMargin ; } 
            set { rtxtBox.ShowSelectionMargin = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public bool WordWrap  
        { 
            get { return rtxtBox.WordWrap; } 
            set { rtxtBox.WordWrap  = value; } 
        } 
        [Browsable(true), Category("Behavior")] 
        public float ZoomFactor 
        { 
            get { return rtxtBox.ZoomFactor ; } 
            set { rtxtBox.ZoomFactor = value; } 
        }  
Code For Font Button on tool strip to change Richtextbox font
private void tbrFont_Click(object sender, EventArgs e) 
        { 
            if (rtxtBox.SelectionFont != null) 
            { 
                fntD.Font = rtxtBox.Font; 
            } 
            else 
            { 
                fntD.Font = null; 
            } 
             
            fntD.ShowApply = true; 
            if (fntD.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
            { 
                rtxtBox.SelectionFont = fntD.Font; 
            } 
        } 

Here Is the Rest of The Code:
//Left Alignment 
        private void tbrLeft_Click(object sender, EventArgs e) 
        { 
            rtxtBox.SelectionAlignment = HorizontalAlignment.Left; 
        } 
        //Center Alignment 
        private void tbrCenter_Click(object sender, EventArgs e) 
        { 
            rtxtBox.SelectionAlignment = HorizontalAlignment.Center; 
        } 
        //Right Alignment 
        private void tbrRight_Click(object sender, EventArgs e) 
        { 
            rtxtBox.SelectionAlignment = HorizontalAlignment.Right; 
        } 
        //Bold 
        private void tbrBold_Click(object sender, EventArgs e) 
        { 
            if (rtxtBox.SelectionFont != null) 
            { 
                System.Drawing.Font currFont = rtxtBox.SelectionFont; 
                System.Drawing.FontStyle newFont; 
                if (rtxtBox.SelectionFont.Bold == true) 
                { 
                    newFont = FontStyle.Regular; 
                    if (rtxtBox.SelectionFont.Italic == true) { newFont = newFont | FontStyle.Italic; } 
                    if (rtxtBox.SelectionFont.Underline == true) { newFont = newFont | FontStyle.Underline; } 
                    if (rtxtBox.SelectionFont.Strikeout == true) { newFont = newFont | FontStyle.Strikeout; } 
                } 
                else 
                { 
                    newFont = FontStyle.Bold; 
                    if (rtxtBox.SelectionFont.Italic == true) { newFont = newFont | FontStyle.Italic; } 
                    if (rtxtBox.SelectionFont.Underline == true) { newFont = newFont | FontStyle.Underline; } 
                    if (rtxtBox.SelectionFont.Strikeout == true) { newFont = newFont | FontStyle.Strikeout; } 
                } 
                rtxtBox.SelectionFont = new Font(currFont.FontFamily, currFont.Size, newFont); 
            } 
        } 
        //Italic 
        private void tbrItalic_Click(object sender, EventArgs e) 
        { 
            if (rtxtBox.SelectionFont != null) 
            { 
                System.Drawing.Font currFont = rtxtBox.SelectionFont; 
                System.Drawing.FontStyle newFont; 
                if (rtxtBox.SelectionFont.Italic == true) 
                { 
                    newFont = FontStyle.Regular; 
                    if (rtxtBox.SelectionFont.Bold == true) { newFont = newFont | FontStyle.Bold; } 
                    if (rtxtBox.SelectionFont.Underline == true) { newFont = newFont | FontStyle.Underline; } 
                    if (rtxtBox.SelectionFont.Strikeout == true) { newFont = newFont | FontStyle.Strikeout; } 
                } 
                else 
                { 
                    newFont = FontStyle.Italic; 
                    if (rtxtBox.SelectionFont.Bold == true) { newFont = newFont | FontStyle.Bold; } 
                    if (rtxtBox.SelectionFont.Underline == true) { newFont = newFont | FontStyle.Underline; } 
                    if (rtxtBox.SelectionFont.Strikeout == true) { newFont = newFont | FontStyle.Strikeout; } 
                } 
                rtxtBox.SelectionFont = new Font(currFont.FontFamily, currFont.Size, newFont); 
            } 
        } 
        //Underline 
        private void tbrUnderline_Click(object sender, EventArgs e) 
        { 
            if (rtxtBox.SelectionFont != null) 
            { 
                System.Drawing.Font currFont = rtxtBox.SelectionFont; 
                System.Drawing.FontStyle newFont; 
                if (rtxtBox.SelectionFont.Underline  == true) 
                { 
                    newFont = FontStyle.Regular; 
                    if (rtxtBox.SelectionFont.Bold == true) { newFont = newFont | FontStyle.Bold; } 
                    if (rtxtBox.SelectionFont.Italic  == true) { newFont = newFont | FontStyle.Italic; } 
                    if (rtxtBox.SelectionFont.Strikeout == true) { newFont = newFont | FontStyle.Strikeout; } 
                } 
                else 
                { 
                    newFont = FontStyle.Underline; 
                    if (rtxtBox.SelectionFont.Bold == true) { newFont = newFont | FontStyle.Bold; } 
                    if (rtxtBox.SelectionFont.Italic == true) { newFont = newFont | FontStyle.Italic; } 
                    if (rtxtBox.SelectionFont.Strikeout == true) { newFont = newFont | FontStyle.Strikeout; } 
                } 
                rtxtBox.SelectionFont = new Font(currFont.FontFamily, currFont.Size, newFont); 
            } 
        } 
        //StrikeThrough 
        private void tbrStrikeThrough_Click(object sender, EventArgs e) 
        { 
            if (rtxtBox.SelectionFont != null) 
            { 
                System.Drawing.Font currFont = rtxtBox.SelectionFont; 
                System.Drawing.FontStyle newFont; 
                if (rtxtBox.SelectionFont.Strikeout == true) 
                { 
                    newFont = FontStyle.Regular; 
                    if (rtxtBox.SelectionFont.Bold == true) { newFont = newFont | FontStyle.Bold; } 
                    if (rtxtBox.SelectionFont.Italic == true) { newFont = newFont | FontStyle.Italic; } 
                    if (rtxtBox.SelectionFont.Underline  == true) { newFont = newFont | FontStyle.Underline; } 
                } 
                else 
                { 
                    newFont = FontStyle.Strikeout; 
                    if (rtxtBox.SelectionFont.Bold == true) { newFont = newFont | FontStyle.Bold; } 
                    if (rtxtBox.SelectionFont.Italic == true) { newFont = newFont | FontStyle.Italic; } 
                    if (rtxtBox.SelectionFont.Underline == true) { newFont = newFont | FontStyle.Underline; } 
                } 
                rtxtBox.SelectionFont = new Font(currFont.FontFamily, currFont.Size, newFont); 
            } 
        } 
        //Add Bullet 
        private void addBulletToolStripMenuItem_Click(object sender, EventArgs e) 
        { 
            rtxtBox.BulletIndent = 10; 
            rtxtBox.SelectionBullet = true; 
        } 
        //Remove Bullet 
        private void removeBulletToolStripMenuItem_Click(object sender, EventArgs e) 
        { 
            rtxtBox.SelectionBullet = false; 
        } 
        //Font Fore Color 
        private void tbrFontColor_Click(object sender, EventArgs e) 
        { 
            clrD.Color = rtxtBox.ForeColor; 
            if (clrD.ShowDialog() == DialogResult.OK) 
            { 
                rtxtBox.SelectionColor = clrD.Color; 
            } 
           
        } 
        //Font Back Color 
        private void tbrBackColor_Click(object sender, EventArgs e) 
        { 
            clrD.Color = rtxtBox.SelectionBackColor ; 
            if (clrD.ShowDialog() == DialogResult.OK) 
            { 
                rtxtBox.SelectionBackColor  = clrD.Color; 
            } 
        } 
        
        //KeyDown Event  [Shortcuts] 
        private void rtxtBox_KeyDown(object sender, KeyEventArgs e) 
        { 
            if (e.Control && e.KeyCode == Keys.B) 
            { 
                tbrBold_Click(null, null); 
            } 
            if (e.Control && e.KeyCode == Keys.I ) 
            { 
                tbrItalic_Click(null, null); 
            } 
            if (e.Control && e.KeyCode == Keys.U) 
            { 
                tbrUnderline_Click(null, null); 
            } 
            if (e.Control && e.KeyCode == Keys.S) 
            { 
                tbrStrikeThrough_Click(null, null); 
            } 
        } 
If you want the Complete Source Code then mail me on : sandeepparekh9@gmaill.com