Showing posts with label .NET Tips. Show all posts
Showing posts with label .NET Tips. Show all posts

Tuesday, June 4, 2019

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine


Error:

The error message Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine is thrown when I tried accessing the Excel file using OLEDB connection.



The issue I described in my scenario occurred basically due to the incompatibility of the Microsoft.Jet.OLEDB.4.0 driver in 64 bit OS.

Solution:

So if we are using Microsoft.Jet.OLEDB.4.0 driver in a 64 bit server, we have to force our application to build in in 32 bit mode(change the build property of the project to X86) and that causes other part of my code to break.

Fortunately, now Microsoft has released a 64 bit compatible 2010 Office System Driver which can be used as replacement for the traditional Microsoft.Jet.OLEDB.4.0 driver. It works both in 32 bit as well as 64 bit servers. I have used it for Excel file manipulation and it worked fine for me in both the environments.

You can download this driver from Microsoft Access Database Engine 2010 Redistributable - 64-bit compatible 2010 office system driver

If the file extension is xls and OS is 32 bit then only you can use "Microsoft.Jet.OLEDB.4.0". Microsoft has not released 64 bit version of this driver.

If file extension is xlsx or OS is 64 bit then you must have to use "Microsoft.ACE.OLEDB.12.0". The application compiled in 32/64 bit mode does not impact the selection of driver.

Always install the 64 bit driver of Microsoft.ACE.OLEDB.12.0 on OS 64 bit. If you have already installed Office 32 bit then you need to run driver from cmd with /passive argument. This hack works till Office 2013 only, Microsoft stopped this workaround from Office 2016 for Microsoft.ACE.OLEDB.16.0 drivers.


private void ProcessFile(string path)
{
    string connString = string.Empty;

    if (Path.GetExtension(path).ToLower().Trim() == ".xls" && Environment.Is64BitOperatingSystem == false)
        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
    else
        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}



There is indeed no 64 bit version of Jet - and no plans (apparently) to produce one.



Monday, June 3, 2019

Rename the Excel Sheet Name in C#


Rename Excel Sheet C#;Excel sheet rename using C#;Excel sheet rename programmatically c#




Rename Excel Sheet C# Code


1) The following code renames an excel worksheet in C#.

To rename an excel sheet we need to open the excel file, rename the sheets, save and close it.

For open an Excel 2007 workbook ,we have to add the Microsoft Excel 12.0 Object Library (For Excel 2007, but it may vary depends on the Excel version you are using) in you project.


From the following pictures to show how to add Excel reference library in your project.
Select Microsoft Excel 12.0 Object Library under COM Tab and click OK button

TEST.xlsx with sheet name "Sheet1"
Now we can start coding to open and rename the first excel sheet from "Sheet1" to "General".

C#  Code

1. Add a button in a windows form



2. Add the below using statement
using Excel = Microsoft.Office.Interop.Excel; 


3. Add the below function

private void RenameExcelSheet(string sFileName)
        {

            Excel.Application app = new Excel.Application();            

            Excel.Workbook excelWorkbook;

            Excel.Worksheet excelWorkSheet;

            try
            {                

                excelWorkbook = app.Workbooks.Open(sFileName);

                if (excelWorkbook.Sheets.Count > 0)
                {

                    excelWorkSheet = excelWorkbook.Sheets[1];
                    //Rename the sheet 
                    excelWorkSheet.Name = "General";
                }

                //Save the excel 
                excelWorkbook.Save();
                //Close the excel
                excelWorkbook.Close();

            }

            catch (Exception ex)
            {
                MessageBox.Show( "Export Excel Failed: " + ex.Message);
            }


            finally
            {
                //Clean up objects 

                app.Quit();
                app = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();

            }
        }

4. Double click the button and paste the code in Click event of btnClick.


private void btnClick_Click(object sender, EventArgs e)
        {
            RenameExcelSheet("C:\\Viji\\Test.xlsx");

        }


4. Execute the project and click the Rename Excel button.


After rename



It's so simple !!!!

Code Comments:

using Excel = Microsoft.Office.Interop.Excel; - we assign the excel reference to a variable Excel.



Sunday, May 26, 2019

How to display code snippets in blogger posts

How to insert code blocks in Blogger posts;code snippets blogspot;code snippets blogger;How to display code snippets in blogger posts;vba code display in blogger

1) First, we need to add the html code(syntax template) below on the head section of our blogger post.

<head>
<link href="https://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css"></link>
<link href="https://alexgorbatchev.com/pub/sh/current/styles/shThemeEclipse.css" rel="stylesheet" type="text/css"></link>
<script src="https://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript">
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script language='javascript' type='text/javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.all();
</script>
</head>

2) Next step is the code rendering. Basically, we need to HTML escape some characters like right angle brackets, e.g. all < must be replaced with <. To do so, you can use the following online tool: http://codeformatter.blogspot.in/2009/06/about-code-formatter.html

3) Once you have the code with escaped characters, you can copy it on your blogger post inside
<pre> tags.


3) That's it! the complete example is below:


 <head>  
 <link href="https://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css"></link>  
 <link href="https://alexgorbatchev.com/pub/sh/current/styles/shThemeEclipse.css" rel="stylesheet" type="text/css"></link>  
 <script src="https://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript">  
 <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>  
 <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>  
 <script language='javascript' type='text/javascript'>  
 SyntaxHighlighter.config.bloggerMode = true;  
 SyntaxHighlighter.all();  
 </script>  
 </head>  
4) Another handy online converter of code to html is hilite.me. Convert the piece of code which is desirable to insert as a code block using this converter and paste the html in the post.

Let’s say we have the following piece of code which is desirable to insert as a code block:

Function OdbcConnectionStringSQLServer(ByVal Driver As String, ByVal Server As String, ByVal database As String, _
ByVal Username As String, ByVal Password As String) As String

'SQL Server

OdbcConnectionStringSQLServer = "Driver={" & Driver & "};Server=" & Server _
& ";UID=" & Username & ";PWD=" & Password & ";Database=" & database


End Function

Below is the result after conversion. style I used: friendly, CSS I used: border:none;



Function OdbcConnectionStringSQLServer(ByVal Driver As String, ByVal Server As String, ByVal database As String, _
    ByVal Username As String, ByVal Password As String) As String

'SQL Server
  
     OdbcConnectionStringSQLServer = "Driver={" & Driver & "};Server=" & Server _
            & ";UID=" & Username & ";PWD=" & Password & ";Database=" & database
  

End Function



Wednesday, October 5, 2016

Access denied error message while saving files on C drive - Windows 7

Access denied,Access denied saving files,Windows 7 Access Denied saving files, Windows 7 Cannot save files to Drive:,open text files as administrator

I have Windows 7 machine and have set myself as the Administrator. However, when trying to modify an XML file in Notepad and save the file, it states 'Access Denied!'. It will not save the file.



Below is the solution worked for me:

Step 1. Open the notepad application in elevated mode. This can be done by right click the Notepad icon from Windows > Click 'Run as administrator'.

Step 2. You can now edit and save that file in the same folder without any issues.



If you want to open the notepad elevated every time, then right click the Notepad shortcut icon > in 'shortcut' tab click on the 'Advanced' button > tick 'run as administrator'.



Tuesday, April 27, 2010

Display line numbers in .NET Code Editor

.NET Tips,Display line numbers in code editor, display line numbers in VS .NET IDE
We can display the line numbers in the Visual studio .NET code editor.

In the VS.NET IDE ,

Click TOOLS > OPTIONS

Expand TEXT EDITOR (in left window)

Select Basic  > Editor

You will find the Line Numbers Option Under Interaction Group box.

 Check Line Numbers option




Click OK

code Editor with Line Number

Monday, April 26, 2010

Display varbinary columns in Datagridview

Display varbinary columns in DataGridview,VB.NET,.NET Tips,Display varbinary,Display varbinary in Datagridview Varbinary to string,Handling of varbinary data,SQL Varbinary datatype, Byte[], Datagridview
I recently faced an issue while displaying SQL query results in a DataGridView, it was crashing on varbinary columns. The reason was that the default format for a varbinary column is to display it as an image. While that seems like a fine default, there is no way to change it.

The following VB.NET code shows how could I handle the varbinary data display after binding the dynamic datatable to DataGridview.

Steps to handle this scenario:

1. Bind the DataGridview DataSource with the datatable.
2. Create a new DataGridview Column of type String
2. Set the DataPropertyName and Name of new Datagridview Column as the Varbinary column name.
3. Remove the original  varbinary column from the DataGridview
4. Insert the new column at the same position as the original column in the Datagridview
5. Implement the CellFormatting event and set the value in the format you want . I have converted each byte  into hex format and displayed the value.

'Global declarationDim sByteArrayColumns As New ArrayList


Private Sub PopulateGrid()

RemoveHandler dbGridView.CellFormatting, AddressOf dbGridView_CellFormatting
AddHandler dbGridView.CellFormatting, AddressOf dbGridView_CellFormatting
  
Dim dataSource As New BindingSource(dt, Nothing)

dbGridView.DataSource = dataSource


sByteArrayColumns.Clear()


For colCnt As Integer = dbGridView.ColumnCount - 1 To 0 Step -1


If DirectCast(dbGridView.Columns(colCnt).ValueType, System.Type).IsArray Then


 sByteArrayColumns.Add(colCnt)

'Creation of new datagridview column
Dim dgColumn As New DataGridViewTextBoxColumn()
dgColumn.DataPropertyName = dbGridView.Columns(colCnt).Name
dgColumn.Name = dbGridView.Columns(colCnt).Name
dgColumn.HeaderText = dbGridView.Columns(colCnt).Name
dgColumn.ValueType = GetType(String)

'Removal of original varbinary column
dbGridView.Columns.RemoveAt(colCnt)

'Add the new column
dbGridView.Columns.Insert(colCnt, dgColumn)
dgColumn.Dispose()
dgColumn = Nothing
End If
Next

End Sub
Implementation of cell formatting event:

Private Sub dbGridView_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs)



Try


 If e.ColumnIndex < 0 OrElse e.Value Is Nothing Then
      Return
  End If

   Dim bArrayField As Boolean = False


   For i As Integer = 0 To sByteArrayColumns.Count - 1


   If e.ColumnIndex = CInt(sByteArrayColumns(i)) Then
        bArrayField = True
        Exit For
   End If


Next
 

If bArrayField Then
  Dim array As Byte() = DirectCast(e.Value, Byte())
  e.Value = String.Empty


  For Each b As Byte In array 'convert each byte value to hex value
      e.Value += [String].Format("{0:X2}", b)
Next

End If 
Catch ex As Exception 
End Try

End Sub


Sample Output

Thursday, April 22, 2010

System.Management.Automation dll missing

System.Management.Automation,.NET,.NET Tips,Microsoft
If the Powershell SDK is already installed, System.Management.Automation dll will be found in the following location.

C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

The Windows PowerShell 2.0 Software Development Kit can be downloaded from the following link:

http://www.microsoft.com/downloads/details.aspx?FamilyID=50633A1F-A665-425D-923C-1A269F8AC084&displaylang=en

Tuesday, April 20, 2010

Populate DataGridView using CSV File

The following VB.NET Code is used to populate the DataGridView using CSV File.


I have used a 2 dimensional array to store the content of csv row and column wise


Also 2 One dimensional arrays are used to populate the row and column data respectively.


The logic is to parse the file content into string and store in a two dimensional array.


Then read row wise and column wise and populate the DataGridview.

A new DataGridView Row will be created for each line of data and the cells will be populated with the column data.

Private Sub PopulateDataGridViewFromCSV(ByVal SFileName As String)

   'Variables to store the count of rows and columns

   Dim nRows As Long
   Dim nCols As Long


  'Index variables to retrieve the data row wise and col wise

  Dim row As Integer
  Dim col As Integer


'Declaration of Two dimensional array to store the csv content row wise and column wise
Dim ParseArray(1, 1) As String


'Use Try Catch block to handle exceptions
Try


'Check if file exist


If File.Exists(SFileName) Then


   dbGridView.DataSource = Nothing
   dbGridView.Columns.Clear()

' Create an unbound DataGridView by declaring a column count.

  dbGridView.ColumnCount = 2
   dbGridView.ColumnHeadersVisible = True
'Set the column header names.
dbGridView.Columns(0).Name = "EmpID"
dbGridView.Columns(1).Name = "Name"

'Open the CSV File into stream

Dim sr As StreamReader = File.OpenText(SFileName)

'Declaration of two single dimensional arrays to store the individual content

Dim RowStringArray() As String
Dim ColStringArray() As String





'Load content of file to RowStringArray array


RowStringArray = sr.ReadToEnd().Split(Environment.NewLine)


'Retrieve the total number of rows
nRows = UBound(RowStringArray)



' Split the content based on "," delimiter


ColStringArray = RowStringArray(0).Split(",")


'Retrieve the total number of columns


nCols = UBound(ColStringArray)


' Redimension the array.


ReDim ParseArray(nRows, nCols)


'Copy the csv content into the 2-dimensional array.


For row = 0 To nRows




ColStringArray = RowStringArray(row).Split(",")



For col = 0 To nCols


ParseArray(row, col) = ColStringArray(col)


Next
Next



Dim dgRow As DataGridViewRow = Nothing


For row = 0 To nRows


dgRow = New DataGridViewRow()


'Add the row
dbGridView.Rows.Add(dgRow)


For col = 0 To nCols


dbGridView.Rows(row).Cells(col).Value = ParseArray(row, col)

Next
Next

End If


Catch ex As Exception


MessageBox.Show(ex.Message)

End Try
End Sub


USAGE


PopulateDataGridViewFromCSV ("C:\Test.csv")

will populate the DataGridView With the C:\Test.Csv file.

 
Sample File: Test.CSV

1001,XXX
1002,YYY

Output


Monday, April 19, 2010

Panel Double buffering VB.NET and C# - Flicker Free

I faced a problem when loading background image in the panel. It used to flicker a lot. I thought of double buffering concept. But there is no in-built double buffering property for panel.

All what I did is to write a class which inherits from Panel Class, and in the constructor  set the DoubleBuffered to true and set the appropriate control styles.

VB.NET Code

Public Class DoubleBufferPanel

Inherits Panel


Public Sub New()


Me.DoubleBuffered = True

SetStyle(ControlStyles.AllPaintingInWmPaint Or _

ControlStyles.DoubleBuffer Or ControlStyles.ResizeRedraw Or ControlStyles.UserPaint, True)

UpdateStyles()


End Sub
End Class

 
After building the project, we should be able to see the DoubleBufferPanel component in the ToolBox.

Double buffer Panel


Then drag and drop the panel  and used it. The problem is solved. It's so simple.

C# Code

public class DoubleBufferPanel : Panel
{


public DoubleBufferPanel()
{


// Set the value of the double-buffering style bits to true.
   this.DoubleBuffered = true;



   this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint |
    ControlStyles.AllPaintingInWmPaint,true);


    this.UpdateStyles();


}


}

Wednesday, March 31, 2010

Items collection cannot be modified when the DataSource property is set

I received the following error "Items collection cannot be modified when the DataSource property is set"  when populating the combo box with data table.

Reason:

The Items.Clear method was called while the combo box's data source was assigned.

Solution:


Need to set the combo box's data source to nothing before calling Items.Clear method
 
The following sample code explains this scenario clearly.
 
Private Sub populateProducts()
Dim SQLAdapter As SqlDataAdapter = Nothing

Try

 
Dim strSQl As String = "SELECT ID, ProdName  FROM  tblProducts"
SQLAdapter = New SqlDataAdapter(strSQl, SConnectionString)

Dim dt As New DataTable

SQLAdapter.Fill(dt)

cmbProducts.DataSource = Nothing // Need to set the data source nothing
                                                           // Comment this line to reproduce the error

cmbProducts.Items.Clear()

cmbProducts.DataSource = dt


cmbProducts.DisplayMember = "ProdName"


cmbProducts.ValueMember = "ID"

Catch ex As Exception


lblStatus.Text = ex.Message
End Try
End Sub

Thursday, February 25, 2010

Display Logical drives information of Machine VB.NET

The following code snippets explains how to retrieve the logical drives in the system, information about the logical drives (Drive Name, Drive Type, Available Free Size, Volume Label etc.,)  present in the system.

All we have to do is to reference the namespace System.IO

The System.IODirectory.GetLogicalDrives method is used to get an array of the drive names.  I have displayed them in a ListBox.




' List the drives.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal _


e As System.EventArgs) Handles MyBase.Load


For Each drive As String In Directory.GetLogicalDrives()


    lstDrives.Items.Add(drive)


Next drive

End Sub


This code snippet how to retrieve information about each logical drive. The important thing to be noted here that, we have to check whether the device is ready before accessing it's properties, otherwise it will throw the exception "Device is not ready"
'List the Drives Information for each drive

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click



Dim strInfo As String = ""



For Each drive_info As DriveInfo In DriveInfo.GetDrives()


If drive_info.IsReady() Then


' Display information about the selected drive.


strInfo = strInfo & " Device is ready" & vbCrLf


strInfo = strInfo & "Drive Name: " & drive_info.Name.ToString & Environment.NewLine


strInfo = strInfo & "Drive Type: " & drive_info.DriveType.ToString & Environment.NewLine


strInfo = strInfo & "Drive Format: " & drive_info.DriveFormat.ToString & Environment.NewLine


strInfo = strInfo & "Available Free Space: " & drive_info.AvailableFreeSpace().ToString & Environment.NewLine


strInfo = strInfo & "Total Free Space: " & drive_info.TotalFreeSpace.ToString & Environment.NewLine


strInfo = strInfo & "Total Size: " & drive_info.TotalSize.ToString & Environment.NewLine


strInfo = strInfo & "Volume Label: " & drive_info.VolumeLabel.ToString & Environment.NewLine


strInfo = strInfo & "Root Directory: " & drive_info.RootDirectory.ToString & Environment.NewLine



Else


' Display information about the selected drive.


strInfo = strInfo & " Device not ready" & vbCrLf


strInfo = strInfo & "Drive Name: " & drive_info.Name.ToString & Environment.NewLine


strInfo = strInfo & "Drive Type: " & drive_info.DriveType.ToString & Environment.NewLine


'strInfo = strInfo & "Drive Format: " & drive_info.DriveFormat.ToString & Environment.NewLine


'strInfo = strInfo & "Available Free Space: " & drive_info.AvailableFreeSpace().ToString & Environment.NewLine


'strInfo = strInfo & "Total Free Space: " & drive_info.TotalFreeSpace.ToString & Environment.NewLine


'strInfo = strInfo & "Total Size: " & drive_info.TotalSize.ToString & Environment.NewLine


'strInfo = strInfo & "Volume Label: " & drive_info.VolumeLabel.ToString & Environment.NewLine


strInfo = strInfo & "Root Directory: " & drive_info.RootDirectory.ToString & Environment.NewLine


End If


Next drive_info



lblDriveInfo.Text = strInfo 'Displaying the information in the label


End Sub


Finally display the information in the label.

Wednesday, February 24, 2010

DBNull is a type and cannot be used as an expression

This is a compile time error which occurs when checking whether the value is System.DBNULL with the following statement..



If result Is System.DBNULL Then


End If



The correct statement should be



If result Is System.DBNULL.Value Then


End If

Sunday, July 5, 2009

Creating Alias name for namespace

The namespaces in .NET can be very long and less obvious.

And to refer the class of the name space we need to include the entire path.

There is a way to simplify this by creating your own alias for the namespace.

How to do?

You can use the Imports statement (VB.NET) or using directive (C#) with an assignment operation.

Syntax:

VB

Imports < AliasName > = < NameSpace >

C#

Using < AliasName > = < NameSpace >


Example - VB


Imports MyaliasName = Microsoft.VisualBasic


Example - C#


Using MyaliasName = Microsoft.VisualBasic;


That way, you can refer to specific class elements within the class referred to using the variable you created in the assignment operation.


'VB

Private Sub TestFunction()

MyaliasName.MsgBox("I am Alias")

End Sub


// C#

void TestFunction()

{

MyaliasName.MsgBox("I am Alias");

}

Database Exception Handling Best Practices

This article would highlight on how to deal with exceptions in our code and the end result would be better code.

1. Validate data prior passing it to DB at client and server.

2. Left validation to DB and handle DB exceptions properly

3. Validate on both sides

4. Validate some obvious constraints in business logic and left complex
validation to DB

5. Strong type checking and validation are powerful tools to prevent unexpected
exceptions. So be ready to always check types, objects value etc before
passing to database.

6. Don't trust external data -External data is not reliable. It must be extensively checked.

7. Generic exception handling should be done in a central point in your
application. Each thread needs a separate try/catch block, or you'll lose
exceptions and you'll have problems hard to understand. When an application
starts several threads to do some background processing, often you create a
class for storing processing results. Don't forget to add a field for storing an
exception that could happen or you won't be able to communicate it to the
main thread. In "fire and forget" situations, you probably will need to duplicate the main application exception handler on the thread handler.

8. Log Exception.ToString(); never log only Exception.Message!

9. Cleanup code should be put in finally blocks

10. Don't use exception handling as means of returning information from a
method
11. Don't clear the stack trace when re-throwing an exception.

12. When in doubt, don't Assert, throw an Exception Don't forget that Debug.Assert is removed from release code. When checking and doing validation, it's often better to throw an Exception than to put an assertion in your code.
Save assertions for unit tests, for internal loop invariants, and for checks that should never fail due to runtime conditions (a very rare situation, if you think about it).

13. Use "using" everywhere -

Simply calling Dispose () on an object is not enough. The "using" keyword will
prevent resource leaks even on the presence of an exception.


14. Avoiding exception handling inside loops

Check if your code uses exceptions inside loops. This should be avoided. If you
need to catch an exception, place the try/catch block outside the loop for better performance.

Find the Operating System Version

The System.Environment.OSVersion static (shared) property is used to find the operating system version of the system.

Prerequisites

Import System.Environment in the top of the Windows form.

Example


Imports System.Environment

Public Class Form1

Private Sub DisplayOSVersion

Dim os As OperatingSystem = Environment.OSVersion

MessageBox.Show("OS Version:" & os.Version.ToString())

MessageBox.Show("OS platform:" & os.Platform.ToString())

End Sub

End Class


Find the executable path of current application

There are two ways to find the path the current running application.


1. Using Application.ExecutablePath

2. System.Reflection.Assembly.GetExecutingAssembly()

Prerequisties:

Import the System.Reflection name space in the top of the windows Form

Example:

[CODE]

Imports System.Reflection

Public Class Form1

....

Private Sub FindPathOfExe()

Dim appPath as String

'Method 1

appPath = Application.ExecutablePath

Debug.Print "Application path: " & appPath

'Method 2
appPath = System.Reflection.Assembly.GetExecutingAssembly().Location


Debug.Print "Application path: " & appPath


End Sub

End Class

[/CODE]

Saturday, July 4, 2009

Using System icons in Windows Forms

How to use System Icons in Windows Forms?

You need to import System.Drawing.SystemIcons name space in the top of the form

Imports System.Drawing.SystemIcons 'to use System Icons


Public Class Form1

//.....
'Some of the System Icons
Dim ico1 As Icon = SystemIcons.Application
Dim ico2 As Icon = SystemIcons.Asterisk

//......
End Class

Windows Forms - Hide the display in task bar

To hide the display of windows Form in the task bar,

we need to set the ShowInTaskbar Property of Windows form to True in the entry point.

Example:

Public Sub New()

Me.ShowInTaskbar = False 'Hide the display in task bar

End Sub

Sort on Multiple Columns in DataGridView

By default DataGridView supports Single Column Sort only.

To sort on multiple columns, we can use the following methods:


For Bounded DataGridview

1. Use Sort Method of DefaultView Property


DataView view = dt.DefaultView;
view.Sort = "C2 ASC, C3 ASC";
bindingSource.DataSource = view;


For UnBounded DataGridview

We need to do Custom Sorting

1. Using the SortCompare event

2. Sort(IComparer) overload of the Sort method for greater sorting flexibility

Same article available under http://www.dotnetspider.com/resources/29470-Sort-Multiple-Columns-DataGridView.aspx

Friday, July 3, 2009

Single statement to remove multiple spaces in a string

We can use System.Text.RegularExpressions Namespace to remove multiple spaces in a string

For example

Imports System.Text.RegularExpressions

Dim MyTrimmedWord() As String = Regex.Split(textbox1.text, "\s+")


will remove multiple spaces from the string