25 January 2014

Convert DataGridView column to Combo Box

Hi Friends,

Sometime if you work in windows form application in C# or using VB,  you may face a problem where you want to put a combo on a field in grid view for a column from the data source table.

Consider a gridview displaying the information of the student  or employee then for the Gender field you may want a Combo Box having the two value Male and Female,  so that for the new record user no need to type the gender value MALE or FEMALE he will select the value from the Combo Box.


So you want to convert plain text column Combo Box. You can download the above sample from the given download link.  Download Sample.

In Form_Load event code the below part.  just copy-paste the below code.

DataTable dt = new DataTable();

private void getDataSource()
{
 dt.Columns.Add("Name");
 dt.Columns.Add("Last");
 dt.Columns.Add("Gender");

 dt.Rows.Add("Rohit", "Sharma", "Male");
 dt.Rows.Add("Saurabh", "Singh", "Male");
 dt.Rows.Add("Gurpreet", "Kaur", "Female");        
}

private void Form1_Load(object sender, EventArgs e)
{
    // just fill the dummy record in datatable dt
    getDataSource();

    // table dt has three column index 0,1,2
    dataGridView1.DataSource = dt;

    // create Combo Box Cell
    DataGridViewComboBoxCell bc = new DataGridViewComboBoxCell();               
 
    //if want to add the fix value in ComboBox Male and Female
    bc.Items.AddRange("Male","Female");
 
    /*  if you want to get the existing value in gender column 
     * and display them in ComboBox
     */
     // var ss = dt.AsEnumerable()
     //           .Select(_ => _.Field<string>("gender")).
     //           .Distinct();
     // bc.Items.AddRange(ss.ToArray());

    /* add one more column at index 3 as ComboBox for the value
     * in index-2 column "Gender"    
     */
    DataGridViewColumn cc = new DataGridViewColumn(bc);
    dataGridView1.Columns.Add(cc);
    dataGridView1.Columns[3].HeaderText = dataGridView1.Columns[2].HeaderText;
    

    /* hide the plain value for gender mean index-2 column as we
     * have index-3 column as combobox for gender
     */
    dataGridView1.Columns[2].Visible = false;       

    // set the gender value in combobox
    foreach (DataGridViewRow item in dataGridView1.Rows)
    {
       item.Cells[3].Value = item.Cells[2].Value;
    }    
}

Happy Code sharing and Blogging.. :)

22 January 2014

DataGridView not showing the DataSource (List, Array) in Grid

Hi Friends,

Sometime we bind the datasource with DataGridView object but still it doesn't show the data in grid view.

Consider we have a class Employee as

 class Employee
 {
     public string fname;
     public string sname;

     public Employee(string f, string s)
     {
         fname = f;
         sname = s;
     }
 }

and we bind List/Array of the Employee class as the datasource of the DataGridView in window form as below -

public partial class Form1 : Form
{
    List<Employee> lst = new List<Employee>();    
    
    public Form1()
    {
        InitializeComponent();

        lst.Add(new Employee("deepak1", "sharma"));
        lst.Add(new Employee("deepak2", "sharma"));
        lst.Add(new Employee("deepak3", "sharma"));                
        
        dataGridView1.DataSource = lst;
        dataGridView1.Refresh();        
    }

}

but when we open the form we are not able to see the data in datagridview.

The main reason is we don't have get set properties in Employee class.  Even the fname and sname are public but still we have to define the properties for the attribute we want to show.

You just need to modify two line in your Employee class.



 class Employee
 {
     public string fname; 
     public string sname; 
    
     public string fname { get; set; }
     public string sname { get; set; }
    
     public Employee(string f, string s)
     {
         fname = f;
         sname = s;
     }
 }

Now if you run the above code it will display the records in DataGridView. :)

Happy Code Sharing and Blogging.. :)

21 January 2014

Generate the barcode in C# (String to Image in C# )

Hi Friends,

Last day on https://stackoverflow.com one user ask two questions ( one and second) how to generate the barcode in C# like the below image -


he has generated the barcode(only stripe) using the font (free 3 of 9) and string "123456" in string now he wanted to merge them like the above image. and finally he want to output as an image so that he can display that of window form / web page or he can save that for future reference.

well its really interesting task, isn't it??

I tried it at my end and finally got a solution and suggested him the same solution and finally he accepted and appreciated the solution. Use the below code that's it.

 //Set the font style of output image
Font barCodeF = new Font("Free 3 of 9", 45, FontStyle.Regular, GraphicsUnit.Pixel);
Font plainTextF = new Font("Arial", 20, FontStyle.Regular, GraphicsUnit.Pixel);


public Image stringToImage(string inputString)
{
  //remove the blank space after and before actual text
  string text = inputString.Trim();

  Bitmap bmp = new Bitmap(1, 1); 
  Graphics graphics = Graphics.FromImage(bmp);

  
  
  int barCodewidth = (int)graphics.MeasureString(text, barCodeF).Width;
  int barCodeHeight = (int)graphics.MeasureString(text, barCodeF).Height;

  int plainTextWidth = (int)graphics.MeasureString(text, plainTextF).Width;
  int plainTextHeight = (int)graphics.MeasureString(text, plainTextF).Height;

  
  
  //image width 
  if (barCodewidth > plainTextWidth)
  {
    bmp = new Bitmap(bmp,
                     new Size(barCodewidth, barCodeHeight + plainTextHeight));
  }
  else
  {
    bmp = new Bitmap(bmp,
                     new Size(plainTextWidth, barCodeHeight + plainTextHeight));
  }
  graphics = Graphics.FromImage(bmp);

  
  
  //Specify the background color of the image
  graphics.Clear(Color.White);
  graphics.SmoothingMode = SmoothingMode.AntiAlias;
  graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

  

  //Specify the text, font, Text Color, X position and Y position of the image
  if (barCodewidth > plainTextWidth)
  {
    //bar code strip
    graphics.DrawString(text,
                        barCodeF,
                        new SolidBrush(Color.Black),
                        0,
                        0);
    
    // plain text
    graphics.DrawString(text,
                        plainTextF, 
                        new SolidBrush(Color.Black),
                        (barCodewidth-plainTextWidth)/2,
                        barCodeHeight);
  }
  else
  {
    //barcode stripe
    graphics.DrawString(text,
                        barCodeF,
                        new SolidBrush(Color.Black),
                        (plainTextWidth - barCodewidth) / 2,
                        0);

    //plain text
    graphics.DrawString(text,
                        plainTextF,
                        new SolidBrush(Color.Black),
                        0,
                        barCodeHeight);
  }

  
  
  graphics.Flush();
  graphics.Dispose();

  
  //if you want to save the image  uncomment the below line.
  //bmp.Save(@"d:\myimage.jpg", ImageFormat.Jpeg);

  return bmp;
}
use this code.  Pass the string in this method and it will return you the barcode image.  Remember you must have installed the free 3 of 9 font in you systems to generate the bar code. You can download the free3 of 9 font from the given linke. Download Free3of9 Font.

This is the output of the above code when I pass string as "NRL9685325PR".


You can download the sample from here.  Download BarCodeSample .

Happy Coding and Sharing.. :)

20 January 2014

C# Extension Methods

Hi All,

Lets see whats the extension method in C# and whats the main use of it.  Sometime we want to add a method in existing class.  This class can be from the .net library or any third party class.  To do so we generally extends the existing class in our new class and then compile it and use that new class.

Like in c# library class - "string" does not have any such method to count if we want such method we have to design our own method.  Remember you can not inherit the "string" class as its sealed.

static class MyClass
{
  public static int WordCount(string line)
  {
      line = line.Trim();
      return line.Split(' ').Length;
  }
}


now you have to call this method like -

int n = MyClass.WordCount("String whatever we want to pass");


but if we want to merge this method with existing c# library string class?  but as we dont have source code of string class we can not edit the source code write?

Extension method do this job.  Using the extension method we can add the method in compiled class without needing source code, so that you can call your own method like the previous existing method in string class.

string str = "string whatever we want to pass";
int n = str.WordCount();


to add an extension method to existing class you just need to class a static class and static method like we created earlier.  The only change we required in passing parameter we need to add the "this" keyword.

static class MyClass
{
    public static int WordCount( this string line)
    {
        line = line.Trim();
        return line.Split(' ').Length;
    }
    
    public static int WordCountStartsWith( this string line, char c)
    {
        int result = 0;
        line = line.Trim();
        
        var word = from wrd in line.Split(' ')
                   where wrd.First() == c
                   select wrd;
        result = word.Count();

        return result;
    }

    public static int WordCountContains( this string line, string str)
    {
        int result = 0;
        line = line.Trim();

        var word = from wrd in line.Split(' ')
                   where wrd.Contains(str)
                   select wrd;
        result = word.Count();

        return result;
    }
}


Now to call these method we can just use the object of string class.

This is the beauty of the extension method, we do not need to recompile the parent class(in this case string class).  We just need to remember when want to design an extension method -
  1. static class
  2. static method
  3. this keyword just before the passing parameter class, whose extension we want. 
Download Sample


See we are getting our own three extension method on string class.

string line = "string value or line whose word we want to count";
int n = line.WordCountContains("nt");

Happy Coding and Blogging.. !! :)

16 January 2014

Pipe (|) symbol, Blank line and Comment in batch programming

Hi Friends,

Lets see how can you print the pipe line ( | ) symbol in batch file.  If you directly use the | symbol then batch file will throw an error.  To display the pipeline symbol in batch file, you have to use the "^" symbol just before the pipeline symbol.

As we know we use "echo hello" to print the hello then you might think to print line we can use the "echo" only. Am I right? but to display the blank line, we have to use the dot( . ) just after the echo word "echo." remember there should not be any space between echo and dot(.)

To mark the line as comment we have to use the double colon ( :: )

 Check the below example -

@echo off
echo.
echo above line is blank
::echo This line is comment as the line starts with Double colon (::)
echo +--------------------------------+
echo ^|                          ^|
echo ^|        Hello World..!!      ^|
echo ^|                          ^|
echo +--------------------------------+
pause

when you will try to run the above batch code, you will get the below output.


Happy Sharing.. :)

Command Line Argument to Batch file (Parameter)

Hi All,

Lets see how can we pass the parameter to batch file.  If you have worked with C, C++ and anyother programming language then I hope you must be familir with "Command Line Args" and whats the use of it.

lets see the basic batch file code to print the value.
@echo off
set n=Hello World..!!!
echo Hello Friends the value stored in variable n is = %n%
pause

when i will run the above batch code it will show the output as below -

Hello Friends the value stored in variable n is = Hello World..!!!
Press any key to continue . . .

but I want to pass the value to the batch code, to run the file I have to use the file name followed by the value we want to pass.

batch_file.bat value1 value2

now our job is to take these value from the command line and use it in our batch code. %1 will refer to the first parameter value and %2 will point to the second value.

@echo off

if %1.==. goto novar1
if %2.==. goto novar2

set first_var= %1
set second_var=%2

echo first variable pass as command line is = %first_var%
echo second variable pass as command line is = %second_var%
goto end

:novar1
echo no command line argument passed in.
goto end

:novar2
echo only one command line argument passed in.
goto end

:end
pause
so in this way you can pass the command line argument to batch file,  and can check either command line argument is passed or not.

Happy Coding & Sharing..

3 January 2014

How to Change the Login Screen - Windows

Hi All,

Lets see how can we have the Login screen in Windows.  Its a registry trick.  Let me tell you this trick so that you can change.

I have bundle all these step together and create a software for you in C# net framework 4.0.  You can download this tool from the following link
Download

You can do all this manually also.  Follow the below steps.
  1. Goto to "C:\Windows\System32\oobe\"
  2. Create a directory "info" at the above location.
  3. Create another directory "backgrounds" inside "info".
  4. Goto the path "C:\Windows\System32\oobe\info\backgrounds"
  5. Paste your "jpg" file (Remember  file size must be less than 256KB)
  6. Rename the file as "backgroundDefault.jpg"
  7. Press "Win key + R" type "regedit.exe"
  8. Goto the path "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background"
  9. Double click the key "OEMBackground" and change the value from "0" to "1".

Thats it.  Now if you lock your system you will see the new background image.

To restore the original image you just need to revert back the registry value from "1" to "0".


Or 

Use the below link, download the tool designed by me and do the above step in just few clicks.  
Download (Tested on Win7/Server 64 bit. If facing any issue in 32 bit please let me know.)

  • Browse - use this button to find your image.  This button has the filter on image size.  As it allowed the jpeg image having the size less then 256 kb.
  • Default - if you click this button it will show you the default login screen.
  • Current - it will show you the current background image which is active.
  • Preview - this will show you the Preview of the image select on full screen mode.
  • Save - This will be used to save the changes.

when click the preview button 



Happy coding and sharing.. !! :)

2 January 2014

This app needs permission to use the camera. Camera app: error in Windows 8.

Hi All,

Lets see how to enable the Camera App's in window 8 once it got disable by mistake.  First time when you open the "Camera app" in "Windows 8" it will prompt and ask you to for the permission to access the hardware - "Camera and Mic".  If by mistake you click on "Block" that mean windows will consider this app as blocked app which can not access the "Camera and Mic".  Now whenever you will start this app you will get a message



Now lets see you to allow the this app to access your "Camera and Mic"

1.  Open your Windows 8 "Camera App".  You will see the above error screen.

2. Press "Win + C" to bring the Windows 8 Charms Bar.

3. Click on the "Settings".

4.  Select the "Permissions" from the setting Menu.

5.  Change the access permission of your "Camera and Mic".

6.  Done. Close the Camera app and reopen it.  Its work. :)

Happy knowledge sharing.. !! :)
Happy Blogging.. :)