Category Archives: VS 2015

Accessing controls in a panel -C#


Accessing controls using collection is pretty simple in C#. It comes handy when you want to perform group tasks.

I have a panel which contains many text boxes and Labels. Some of the controls used to format the result. Others name start with txt_ and lbl_. Our task is to clear the Text property with “”/null.

2018-01-05_220714

We can iterate through panel controls as follows

foreach(Control c in panel_rateSettings.Controls )
{
if ( c.Name.Contains(“txt_”) || c.Name.Contains(“lbl_”))
{
c.Text=null;
}
}

Maybe you can find another use of the control collection.

Create custom form controls in C#.Net


.Net frame provide rich set of control to design  application GUI with a drag and drop actions. Sometime we love to have extend these control features. This can be achieved using Windows Forms Control Library Projects. Let’s learn how to do.

Extended TextBox control

Our extended control have following features
  • Custom got focus color
  • Custom Lost focus color
  • New Methods
Using the new Text Box you can enable different Leave/Enter colors. The example look like simple but it will demonstrate how you can add new properties for using at run time and design time.

Quick start

  1. Add New  Windows Forms Control Library project in Visual Studio .Net 2012/15.
  2. Drag a Text Box to the user control
  3. Rename the User control as “CPTextBox” where CP stands for Code Poet.
    Windows Forms Control Library Project
Now we need a Windows Application to test our CPTextBox, add a new project by,
  1. Go to File – Add – New Project – Windows Form Application (name it as testProject)
  2. Go to Solution Explorer – There is your two project, right click the Windows Application Project, and choose Set as Start Up Project.

We are almost ready to make changes to our custom control. Double click our custom control  and the following methods and drop properties to our code.

namespace CodePoetControls
{

public partial class CPTextBox: UserControl
{
Color Ecolor;
Color Lcolor;

public CPTextBox()
{
InitializeComponent();
textBox1.BackColor = Color.White;

}

private void textBox1_Enter(object sender, EventArgs e)
{
textBox1.BackColor = Ecolor;
}
private void textBox1_Leave(object sender, EventArgs e)
{
textBox1.BackColor = Lcolor;
}

public string GetText()
{
return (textBox1.Text);
}

[Browsable(true)]
[Category(“Extented Properties”)]
[Description(“Get input Text”)]
[DisplayName(“BoxText”)]
public string BoxText
{
set
{

textBox1.Text = value.ToUpper().Trim();

}
get
{
return (textBox1.Text  );
}
}
[Browsable(true) ]
[Category(“Extented Properties”)]
[Description (“Set Focus Color”)]
[DisplayName(“Enter Color”)]
public Color  EnterColor
{
set
{
Ecolor  = value ;
base.OnEnter(new EventArgs() );
}
get
{
return (Ecolor );

}
}

[Browsable(true)]
[Category(“Extented Properties”)]
[Description(“Set Lost Focus Color”)]
[DisplayName(“Leave Color”)]
public Color LeaveColor
{
set
{
Lcolor  = value;

}
get
{
return (Lcolor );
}
}

}
}

Compiling the User Control project.

After you successfully add the necessary code portion and ready to make your control usable. Right click the Custom control project and Build. It will generate necessary .dll files for your project.

Testing the Control

For using the control , go to the second project, open the Form. The Tool Box will show your new Control, just drag and drop CPTextBox.

The Properties Windows Categorized view will showcased your new Controls Extended Properties and try to change the Leave Color and Enter Color respectively.

If you wish to have more changes to the control, go to the custom control project and make necessary changes and Rebuild.

Distributing and using the control

Distributing and using the Dll file. For working with the new control you only need the compiled Dll not the custom project. You can add it by

  • Right click Tool Box – Choose Items
  • Brow the Dll of your custom control
  • Enable the control and it will be available on your control box.

Note:

The following code snippet will make your properties available at design time and can be accessible by using Properties.
        [Browsable(true)]
        [Category(“Extented Properties”)]
        [Description(“Set Lost Focus Color”)]
        [DisplayName(“Leave Color”)]

Using the existing Property name as Display Name will hide the default, for example if you use Text as Display Name for your property and the default property will be discarded and will be unavailable.

That’s all I have today
 

Forming C# string with multiple values using curly braces


In the last post we discussed about mutable string object, which is derived from the list which is mutable object. Today we will learn how make string with different type of values for console programs.

The boast string will help you to understand the concept. Actually C# has pretty neater treatment with strings. Start a fresh COnsole Application project and here is what we usually do when we have thing like this

            int count=20;
            float am=100 ;
            string symbol=” $”;
            string boastStr=”minutes”;
            double   min=2.50;
  Console.Write(“Boast string : I have finished ” + count + ” Apples and Oranges ( ” + am + symbol + “) in ” + min + ” ” + boastStr + ” , wow”) ;

The message is just a joke , lol.

 You can put values inside within a single string by using a { }, curly braces and cardinals instead of the old fashioned + operator, but limited to console only. It will look like,
“I have to reach the station at {0}”, min . Can also use many variables in a string.

Lets convert our boast string too

            Console.WriteLine (“\nBoast string : I have finished {0} Apples and Oranges (  {1} {2}  ) in   {3}  {4} , wow”,count,am,symbol,min,boastStr );

Remember it’s only work with Console.Write().

Auto complete TextBox in C#


An Autocomplete Textbox is a must have for a commercial application, it can bring user friendly features to you application.
Lets learn how to add a Auto complete feature, here is the plan


Code poet’s steps

  1. First we make up the Autocomplete string collection.
    1. Create AutoCompleteStringCollection
    2. Add items to the collection.
  2. Set Autocomplete mode
  3. Set Auto complete source as custom source
  4. Set auto complete custom source as Autocomplete string collection.
  5. That is all

Code

AutoCompleteStringCollection a = new AutoCompleteStringCollection();
            a.Add(“Babool”);
            a.Add(“Ice Bowl”);
            a.Add(“Mango”);
            a.Add(“Mangoose”);
            a.Add(“Chiken”);
            a.Add(“Fruits”);
            textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            textBox1.AutoCompleteCustomSource = a;

As you see you can just type the letters Man  and a new list will populate, as result of the AutoCompleteMode.Suggest code, can replace it with append or appendSuggest which will automatically complete text as you type.

How to add a ComboBox to DatagridView programmatically in C#.Net


DatagridView in C# 2015 is an important tool to show database values. This control has different usage such as regular Grid. Here we explore the different approaches to the datagrid programing which will explaining how to add advanced combo, auto suggestion box etc to DataGridView control.

Easy steps we require

Start a new Windows Form project in your Visual Studio and Drop a DatagridView control to your project, our project require a DataGridViewComboBoxColumn object. Here we goes
  1. Initialize column header with appropriate text
  2. Create a DataGridViewComboBoxColumn object and fill with appropriate values, name and a header text.
  3. Add the DataGridViewComboBoxColumn object to the DatagridView

That’s the plan, just the drop the following code to the form’s load event method.

The C# code

            dataGridView1.ColumnCount = 1;
            dataGridView1.Columns[0].Name = “Slno”;
            DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
            dc.HeaderText = “Order Items”;
            dc.Name = “Items”;
            dc.Items.Add(“Mango”);
            dc.Items.Add(“Carrot”);
            dc.Items.Add(“Sugar cane”);
            dc.Items.Add(“Potatto”);
            dc.Items.Add(“Grapes”);
            dc.Items.Add(“Chillie”);
            dc.MaxDropDownItems = 1;
            dataGridView1.Columns.Add(dc);
            dataGridView1.Columns.Add(“Qty”, “Qty”);

Lets run, and that’s all you need to know. Next time we will meet with Autocomplete Box poem.

Accessing child controls in C# with foreach


Simplest way to clear all combo Box/TextBox in Visual Studio C#  2015 is using foreach loop and moving through the control collection.

What about controls grouped within  a group box, things getting complicated,isn’t it? Let me explain how can it get done.

  • First we going through the Base control collection and get each and every control.
  • Secondly we are looking inside each controls if they have child.
  • We further search for the TextBox and ComboBox and do some formatting, or any usual activities you want.

Visual Studio 2015 Tips: Double press Tab after you type foreach for snippet to be inserted, so that you can do more with less time.      

Treating Keystrokes systematically in C#.Net


Walking around the C#.Net 2015 may be little bit fun. Today I will introduce keystroke and show how it can help to move focus between controls.
Sendkeys Object in .Net frame work help you to fire some key stroke, which will enable functions such as move focus forward and backward with the send() method.

 Lets’ start with building a Key Press event for the following Pcode Textbox.

Making of the Key Press Event

Go to the Property Box – Choose Event – locate Key Press and enter Key Press event name as “EnterKey_Treatment” and hit enter, will bring the method structure code.

Now select all controls with Ctrl + Click and select Key Press Event as  EnterKey_Treatment. You can also do it individually. This would save our time indeed. 

Applying Keystroke

For proper working of the keystroke for moving from one box to another, you have keep the Tab Index of all boxes in as sequential order, i.e, 0,1,2 and so on.Let’s fill this cup with some hot tea.

But the MoveToMox and common static class not yet defined, we need the fuel from the common class.( A static class act like a library, it can be called anywhere in the project). 

Static class for Keystroke (MoveToBox)

A static class can contain only static members, and it can access without creating the object, it act like C# library for our project.
For utilizing the KeyPressEventArgs(accessing the keys the user press), have to reference System.Windows.Forms. The new class would look like,

Create a single method for key Press Event and call the commons. That is all you need to know.

Let’s test the program.

OLEDB Database connection string in C#.Net


OledDb database connections allow C# developers to build data powered applications with Access database. It can be possible with Database connection object and command object.

Connection string 

For connecting .mdb Access files you can use the following connection string,
string connstr = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/.Net Project/PharmaERP/PharmaERP/PharmaData.mdb”;
and for the Access 2007, 2012,2016 databases you have to use the following one.          

string connstr = “Provider=Microsoft.ACE.OLEDB.12.0;;Data Source=D:/.Net Project/PharmaERP/pharmaData.accdb;Jet OLEDB:Database Password=password”;

 Now we are ready to setup the connection, let build the connection objects and get started.

Connecting database with OleDbConnection object.

     OleDbConnection  conn;

     OleDbCommand Rs;

      public void Connect()
        {
            conn = new OleDbConnection(connstr);
            conn.Open(); 
        }
With the OleDbConnection object, we are ready to establish connection with the data base, all we need to manipulate data is Command object. Let start with Insertion command first.
We can use insert into SQL statement and execute, DML command with ExecuteNonquery() of command object. We can also use the Parameter to pass arguments to the insert statements. Lets have a look at the code.
 

public void New_Medicines(Product_Registration f)

        {
               Connect();
                Rs = new OleDbCommand(“insert into new_Medicines(product_name,pdate,manufacture,catagory,subcatagory,type,packing,printpack,reorderlevel,tax,ptr,pts,contents,rackno) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)”, conn);
                Rs.Parameters.Add(new OleDbParameter(“product_name”, f._txtPname));
                Rs.Parameters.Add(new OleDbParameter(“pdate”,f._txtPrdate ));
                Rs.Parameters.Add(new OleDbParameter(“manufacture”, f._txtmanufacture));
                Rs.Parameters.Add(new OleDbParameter(“catagory  “, f._txtCatagory));
                Rs.Parameters.Add(new OleDbParameter(“subcatagory”, f._txtSubCatagory));
                Rs.Parameters.Add(new OleDbParameter(“type”, f._txtType));
                Rs.Parameters.Add(new OleDbParameter(“packing”, f._txtPackNo));
                Rs.Parameters.Add(new OleDbParameter(“printpack”, f._txtPackPrint));
                Rs.Parameters.Add(new OleDbParameter(“reorderlevel”, f._txtReorderLevel));
                Rs.Parameters.Add(new OleDbParameter(“tax”, f._txtTax));
                Rs.Parameters.Add(new OleDbParameter(“ptr”, f._txtPTR));
                Rs.Parameters.Add(new OleDbParameter(“pts”, f._txtPTS));
                Rs.Parameters.Add(new OleDbParameter(“contents”, f._txtContents));
                Rs.Parameters.Add(new OleDbParameter(“rackno”, f._txtRack));
                Rs.ExecuteNonQuery();
        }

The command object is also capable of running queries and join statements. Try it yourself.

Privately set able and publicly get able property in C#


Properties in C# classes are safer way to access and manipulate data. With Set and Get function user can configure the functionality. How about a privately Get able property, which can be accessible only through the class itself and publicly setable property.

This can be done by putting private keyword before the set property.

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

namespace ConsoleApplication2
{
    class Data
    {
        private String Narration;

        public Data()
        {
            this.Narration = “Expese”;
         
        }
        public string narration
        {
         
            get
            {
                return  Narration;
            }
            private set
            {
                Narration=value;
            }
        }
        public void SetData()
        {
            this.narration = “Other expense”;
        }

    }
}

Let’s configure the console application. Create the object call the properties and methods.

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Data d = new Data();
            Console.WriteLine(d.narration);
         
            d.SetData();
            Console.WriteLine(d.narration);
 Console.ReadKey();
        }
    }
}

The SetData() is call the privately get able property, which can be on;y accessible within the class itself.

The public property can access the data because it is public property and by default all set and get are public.

Download Source

How to make method obsolete in c#.Net


C# has packed magical feature like ‘property, which can be used in a variety of ways. We will start with a console application with two methods and going to make one of them obsolete.

Under what condition I should make a method obsolete, that is the question in your mind, isn’t it?

Here we goes, suppose you work with bigger application with lots of developers involved in, and the team want to make some serious change to the API or some of the methods, which is already used by others. All you need to make the old method obsolete and tell fellow developers to use the new one. This can be done with property of C# class.

A property cam placed inside a set of square brackets just below the method that is deprecated as follows.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DisplayString(“Welcome”);
            Console.ReadKey();
        }
        [Obsolete]
        static void DisplayString(string st)
        {
            Console.Write(st);
        }

        static void DisplayStringNew(string st)
        {
            Console.Write(“\nMessage: ” + st);
        }
    }
}

This will place an warning message for the method that is deprecated. C# has a special class for Obsolete actions, which come with three constructor, the default one and with arguments.

The second constructor allow us to pass a message for indicating the new method you just added, and the third constructor will make the usage of obsoleted methods caused for compile error, if it set true. (this is the best way to force other programmers to use the new DisplaySretingNew method).

Lets rewrite the above code with third constructor and it will put red line under the old method call. Just point the error line and it will show the following message.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DisplayString(“Welcome”);
            Console.ReadKey();
        }
        [Obsolete(“Use DisplayStringNew”,true)]
        static void DisplayString(string st)
        {
            Console.Write(st);
        }

        static void DisplayStringNew(string st)
        {
            Console.Write(“\nMessage: ” + st);
        }
    }
}

Download source code
Requirements: VS 2012/2015
More property magic will coming soon.