Friday 31 January 2014

CheckedCombobox in winforms C#

In this article we are going to see how to create a checkbox in the combobox item, For this we have to create a template for the data .

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Windows.Forms.VisualStyles;

namespace CustomControl
{
      class CheckComboBox:ComboBox
    {               
        public class ComboboxData
        {            
             string TotalData;

            private bool _checked;
            public bool Checked
            {
                set { _checked = value; }
                get { return _checked;  }
            }

            private string _data;
            public string Data
            {
                set { _data = value; }
                get { return _data;  }
            }

            public ComboboxData(string value,bool ischeck)
            {
                Data = value;
                Checked = ischeck;              
            }

            public override string ToString()
            {               
                return Data;
            }


        }

        public event EventHandler Checkchanged;

        public CheckComboBox()
        {
            this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
        }

        public List<ComboboxData> CheckItems
        {
            get
            {

                List<ComboboxData> newitems = new List<ComboboxData>();
                foreach (var item in Items)
                {
                    if (item is ComboboxData)
                    {
                        newitems.Add(item as ComboboxData);
                    }
                }
                return newitems;

            }
        }

        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            base.OnSelectedIndexChanged(e);
            ComboboxData data = (ComboboxData)SelectedItem;
            data.Checked = !data.Checked;

            if (Checkchanged != null) {
                Checkchanged(data, e);
            }


        }

        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            if (e.Index == -1)
            {
                return;
            }

            if (Items[e.Index] is ComboboxData)
            {
                ComboboxData data = Items[e.Index] as ComboboxData;
                CheckBoxRenderer.RenderMatchingApplicationState = true;
                CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(e.Bounds.X, e.Bounds.Y),                      e.Bounds, data.Data, this.Font,
                    (e.State & DrawItemState.Focus) == 0, data.Checked ?                                          CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal);
            }
            else
            {
                e.Graphics.DrawString(Items[e.Index].ToString(), this.Font, Brushes.Black,                          new Point(e.Bounds.X, e.Bounds.Y));
                return;
            }

            base.OnDrawItem(e);
        }
   
    }
}



Form.cs:
************

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Testing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            checkComboBox1.Items.Add(new CheckComboBox.ComboboxData("Rajesh", true));
            checkComboBox1.Items.Add(new CheckComboBox.ComboboxData("Suresh", false));
            checkComboBox1.Items.Add(new CheckComboBox.ComboboxData("Ram", true));
            checkComboBox1.Items.Add(new CheckComboBox.ComboboxData("Ravi", true));


            checkComboBox2.Items.Add(new CheckComboBox.ComboboxData("1", true));
            checkComboBox2.Items.Add(new CheckComboBox.ComboboxData("2", false));
            checkComboBox2.Items.Add(new CheckComboBox.ComboboxData("3", true));
            checkComboBox2.Items.Add(new CheckComboBox.ComboboxData("4", true));


        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<CheckComboBox.ComboboxData> dat1 = checkComboBox1.CheckItems;
            var data = new CheckComboBox.ComboboxData("bnm", true);           
            var sdata =data.ToString();
        }
    }
}




Output:




From this post you can learn how to create a Custom Combobox.

Wednesday 29 January 2014

Graphics Path to draw the Elements in WinForms

In this article we are going to see how to draw a elements in the Winforms, To draw the elements we have graphics objects in the paint event. To do the Draw we are using Graphics Path, where we are plotting the points to draw and fill the color. In Graphics path we are adding many elements like line, Ellipse, Curve and Bezier. There is method called Start Figure which will use to draw a figure by the all elements points to finish the figure we have to draw and connect the points by called the CloseFigure(). Finally give the path to the Graphics to draw.

C#:
    public class AnimatedForm:Form
    {
        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            GraphicsPath path = new GraphicsPath();
            path.StartFigure();
            path.AddLine(20, 50, 70, 230);
            path.AddArc(30, 60, 70, 140, 130, 120);
            path.AddBezier(30, 40, 50, 20, 50, 60, 100, 20);
            path.CloseFigure();

            path.AddEllipse(60, 50, 180, 180);
           
            PathGradientBrush pgb = new PathGradientBrush(path);
            pgb.SurroundColors = new Color[] { Color.Green,Color.Yellow,Color.Red,
                                            Color.Blue,Color.Orange, Color.White,
                                          };
            e.Graphics.FillPath(pgb, path);
            e.Graphics.DrawPath(Pens.Black, path);  
            path.Dispose();         
        }

    }   
    public partial class Form1 :AnimatedForm
    {
        public Form1()
        {
            InitializeComponent();
        }
    }

partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(288, 262);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        #endregion

    }


Output:


From this post you can learn how to implement the draw in the forms.

Tuesday 28 January 2014

Action and Func in C#

In this post we are going to see Action and Func. Action will have a reference of  method with out return type, function have return type as last parameter.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            /* Action Sample */
            Console.WriteLine("*** Action sample ***");
            Action read = ReadData;
            Action write = WriteData;
            ExecuteActions(new List<Action>() { read,write});

            Console.WriteLine();
            Console.WriteLine("*** Func Sample ***");
            /* Function samples */
            Func<string> returnmethod = Sam;
            Func<string, string> empfunc = Name;
            Console.WriteLine(returnmethod.Invoke());
            Console.WriteLine(empfunc("Rajesh"));
            Console.Read();
        }

        public static string Sam()
        {
            return "Sample";
        }

        public static string Name(string name)
        {
            return "Employee " + name;
        }

        public static void ExecuteActions(List<Action> actions)
        {
            foreach (Action act in actions)
            {
                act.Invoke();
            }
        }

        public static void ReadData()
        {
            Console.WriteLine("Read Data : Started ");
        }

        public static void WriteData()
        {
            Console.WriteLine("Write Data : Started");
        }

    }
}



Output :-
*** Action sample ***
Read Data : Started
Write Data : Started

*** Func Sample ***
Sample
Employee Rajesh


From this article you can learn how to use action and func

Tuple in c#

In this article we are going to see a concept called Tuple, which is present in the dotnet framework 4.0, why Tuple is there in framework, what is the usage of the That ? Tuple is a data structure to store the identifiers, The Tuple is stored in a separated location of a memory.Once we create the Tuple, it can be be changed.


Tuple:


Create<T1>(T1)
1Create<T1, T2>(T1, T2)
2Create<T1, T2, T3>(T1, T2, T3)
3Create<T1, T2, T3, T4>(T1, T2, T3, T4)
4Create<T1, T2, T3, T4, T5>(T1, T2, T3, T4, T5)
5Create<T1, T2, T3, T4, T5, T6>(T1, T2, T3, T4, T5, T6)
6Create<T1, T2, T3, T4, T5, T6, T7>(T1, T2, T3, T4, T5, T6, T7)
7Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1, T2, T3, T4, T5, T6, T7, T8)

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{

    class Employee
    {
        public string EmpId { get; set; }

        public string Address { get; set; }

        public int PhoneNumber { get; set; }

        public string Department { get; set; }

        public string EmpName { get; set; }
    }


    class Program
    {
        static void Main(string[] args)
        {
            var Company = Tuple.Create<int, string, string, Employee>(1, "Rajesh", "Chennai", new Employee() { EmpId = "E1", EmpName = "Rajesh . G", Department = "Technical", PhoneNumber = 1233444, Address = "chennai" });    
       
            Console.WriteLine("Number:- {0}, Name:- {1}, Employee Department:- {2}", Company.Item1.ToString(), Company.Item2, Company.Item4.Department);           
            Console.Read();
        }
    }
}




Output:
Number:- 1, Name:- Rajesh, Employee Department:- Technical


From this article you can learn how to use the Tuple.