Automatic ListView Grouping

Lets say you have lots of data your listview. Now you want to Group This data According to a Particular Subitem.

For Example:

Suppose i have some books data in my ListView.
this listview items contains Author name and Books Title.

And there are 2000 Books in list view.

Now i want to group the data in listview according to the Authors.

Now lets say there are 50 Unique Authors , meaning we will have to create 50 Groups in listview.

this seem hectic, and i don’t know if there is any inbuilt function to automatically group this items, but i have created mine To automatically do the above.

Hope it becomes useful to someone.

public void GroupListView(ListView lstV, int SubItemIndex) {
 bool flag = true;

 foreach(ListViewItem l in lstV.Items) {
  string strmyGroupname = l.SubItems[SubItemIndex].Text;

  foreach(ListViewGroup lvg in lstV.Groups) {
   if (lvg.Name == strmyGroupname) {
    l.Group = lvg;
    flag = false;
   }
  }

  if (flag == true) {
   ListViewGroup lstGrp = new ListViewGroup(strmyGroupname, strmyGroupname);
   lstV.Groups.Add(lstGrp);
   l.Group = lstGrp;
  }

  flag = true;
 }
}

How To Use The Code:
Lets say the author’s sub item’s index is 1 and listview name is LstBooks then call the function like:

GroupListView(LstBooks,1);

Vb.net Version:

Public Sub GroupListView(ByVal lstV As ListView, ByVal SubItemIndex As Int16)
Dim flag As Boolean = True
For Each l As ListViewItem In lstV.Items

Dim strmyGroupname As String = l.SubItems(SubItemIndex).Text

For Each lvg As ListViewGroup In lstV.Groups

If lvg.Name = strmyGroupname Then
l.Group = lvg
flag = False
End If

Next

If flag = True Then
Dim lstGrp As New ListViewGroup(strmyGroupname, strmyGroupname)
lstV.Groups.Add(lstGrp)
l.Group = lstGrp
End If

flag = True

Next
End Sub

Output:

listgroup

 

Auto Increment Invoice Number For Vb.net

Let’s say you have some invoice numbers which contains Alphabets as well as numeric number.
And you want to increment it one by one.
For Example:

if Invoice number is “AZ99999999” then Next Invoice Number will be “BA00000001”

Notice here that , the invoice number’s length is 10 Characters out of which first 2 are Alphabets and the rest (8) are Numeric. invoice number can be of any digit with any combination of numeric and alphabets.

The function can be changed to your need very easily. but here i will demonstrate for the above example.

Function:

Public Function IncrementInvoice(ByVal strInvoiceNumber As String) As String

If strInvoiceNumber.Length <> 10 Then
Return "Error"
End If

Dim strAlphaPart(1) As Char
strAlphaPart(0) = strInvoiceNumber(0)
strAlphaPart(1) = strInvoiceNumber(1)

Dim IntPart As Int64
IntPart = strInvoiceNumber.Substring(2, 8)
If IntPart = 99999999 Then
If strAlphaPart(1) = "Z" Then
strAlphaPart(0) = Chr(Asc(strAlphaPart(0)) + 1)
strAlphaPart(1) = "A"

IntPart = 1

Return strAlphaPart(0) & strAlphaPart(1) & IntPart.ToString.PadLeft(8, "0")
Else
strAlphaPart(1) = Chr(Asc(strAlphaPart(1)) + 1)
End If

Else
IntPart += 1
Return strAlphaPart(0) & strAlphaPart(1) & IntPart.ToString.PadLeft(8, "0")
End If

End Function

Output:

‘outputs example:
strTemp = IncrementInvoice(“AA99999998”) ‘Output will be: “AA99999999”
strTemp = IncrementInvoice(“AA00000005”) ‘Output will be: “AA00000006”
strTemp = IncrementInvoice(“AZ00000007”) ‘Output will be: “AZ00000008”
strTemp = IncrementInvoice(“AZ99999999”) ‘Output will be: “BA00000001”

 

Dataset To Excel Export Function

The Function:

Public Sub ExportDatasetToExcel(ByVal ds As DataSet, ByVal strExcelFile As String)

    Dim conn As New OleDbConnection(String.Format("provider=Microsoft.Jet.OLEDB.4.0; Data Source='{0}';" & "Extended Properties='Excel 8.0;HDR=YES;'", strExcelFile))
    conn.Open()

    Dim strTableQ(ds.Tables.Count) As String

    Dim i As Integer = 0

    'making table query
    For i = 0 To ds.Tables.Count - 1

        strTableQ(i) = "CREATE TABLE [" & ds.Tables(i).TableName & "]("

        Dim j As Integer = 0
        For j = 0 To ds.Tables(i).Columns.Count - 1
            Dim dCol As DataColumn
            dCol = ds.Tables(i).Columns(j)
            strTableQ(i) &= " [" & dCol.ColumnName & "] varchar(255) , "
        Next
        strTableQ(i) = strTableQ(i).Substring(0, strTableQ(i).Length - 2)
        strTableQ(i) &= ")"

        Dim cmd As New OleDbCommand(strTableQ(i), conn)
        cmd.ExecuteNonQuery()

    Next

    'making insert query
    Dim strInsertQ(ds.Tables.Count - 1) As String
    For i = 0 To ds.Tables.Count - 1
        strInsertQ(i) = "Insert Into " & ds.Tables(i).TableName & " Values ("
        For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
            strInsertQ(i) &= "@" & ds.Tables(i).Columns(k).ColumnName & " , "
        Next
        strInsertQ(i) = strInsertQ(i).Substring(0, strInsertQ(i).Length - 2)
        strInsertQ(i) &= ")"
    Next

    'Now inserting data
    For i = 0 To ds.Tables.Count - 1
        For j As Integer = 0 To ds.Tables(i).Rows.Count - 1
            Dim cmd As New OleDbCommand(strInsertQ(i), conn)
            For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
                cmd.Parameters.AddWithValue("@" & ds.Tables(i).Columns(k).ColumnName.ToString(), ds.Tables(i).Rows(j)(k).ToString())
            Next
            cmd.ExecuteNonQuery()
            cmd.Parameters.Clear()

        Next
    Next
End Sub

Let’s say i have my.xls in D drive. i want to export a Dataset Name dsFinal to this excel file.
Use:

ExportDatasetToExcel(dsFinal, “d:\my.xls”)

 

A simple Class for Moving Controls At Runtime

Here Is The Class:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace MoveControl
{
sealed class clsMoveControl
{
public enum Direction
{
Any,
Horizontal,
Vertical
}

public static void StartMoving(Control cntrl)
{
StartMoving(cntrl, Direction.Any);
}

public static void StartMoving(Control cntrl, Direction dir)
{
StartMoving(cntrl, cntrl, dir);
}

public static void StartMoving(Control cntrl, Control container, Direction dir)
{
bool Dragging = false;
Point DragStart = Point.Empty;
cntrl.MouseDown += delegate(object sender, MouseEventArgs e)
{
Dragging = true;
DragStart = new Point(e.X, e.Y);
cntrl.Capture = true;
};
cntrl.MouseUp += delegate(object sender, MouseEventArgs e)
{
Dragging = false;
cntrl.Capture = false;
};
cntrl.MouseMove += delegate(object sender, MouseEventArgs e)
{
if (Dragging)
{
if (dir != Direction.Vertical)
container.Left = Math.Max(0, e.X + container.Left - DragStart.X);
if (dir != Direction.Horizontal)
container.Top = Math.Max(0, e.Y + container.Top - DragStart.Y);
}
};
}
}
}


How to Use Example :

1. Create a simple project .
2. On the load event of the form write the following coding

clsMoveControl.StartMoving(this);

This will make the form movable by clicking anywhare on the form and dragging it.
The same can be done for other controls like:

clsMoveControl.StartMoving(Button1);
clsMoveControl.StartMoving(Panel1);

See it Live:


 

Trimming a String Arrary

Let’s Say i have following array:

string[] myArray = new string[6];
myArray[0] = "a";
myArray[1] = "b";
myArray[2] = " "; //space
myArray[3] = "c";
myArray[4] = ""; //null
myArray[5] = "d";

I want to remove the space and null parts from the array.
so after trimming the array should be like this:

            myArray[0] = "a";
myArray[1] = "b";
myArray[2] = "c";
myArray[3] = "d";

Code:

public string[] TrimStringArray(string[] strArray)
{

int c = 0;
foreach (string str in strArray)
{
if (str != "" && str != null)
{
c++;
}
}

string[] tempArrary = new string;
int j=0;
for (int i = 0; i < strArray.Length; i++)
{
if( strArray[i] != null && strArray[i] != "")
{
tempArrary[j] = strArray[i];
j++;
}
}

return tempArrary;
}

Examle:

myArray = TrimStringArray(myArray);
 

MultiPicBox control [With SlidShow]

Once i was working with the Microsoft’s PictureBox control. I noticed the each time i want to change the image i will have to create an Image object and Load my Image into and Assign it to PictureBox . And if i want to see the old pic (before assigning to new) i will have to again do the same.

So i thought why not make a control which support Multiple Pictures and a Slidshow Option..(with interval option).

Here are some pics of  the Control:

Properties:


AutoPreview               : Will automatically start the slideshow if enabled.
AutoResizeImages     : will automatically fit images to picture box if enabled.
ImageLimit                 : How many images should be there in control.
ImagesArrary             : Arrary of images to be displayed.
Interval                       : the interval time for the slidshow

Download Control:
Multipicbox

See it Live:

 

Listing All the Installed Softwares in Computer using .Net

We will be Accomplishing using the Windows Registry.

Main Registry to work here is : “SOFTWAREMicrosoftWindowsCurrentVersionInstallerUserDataS-1-5-18Products”

Just Write Down The Following Code the Form’s Loading Event (Form Contains No Control):

C#.NET

private void Form1_Load(object sender, EventArgs e)
{
string SoftwareKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products";
RegistryKey rk = default(RegistryKey);
rk = Registry.LocalMachine.OpenSubKey(SoftwareKey);
//string skname = null;
string sname = string.Empty;

ListView ListView1 = new ListView();
this.Controls.Add(ListView1);
ListView1.Dock = DockStyle.Fill;

ListView1.View = View.Details;
ListView1.Columns.Add("Installed Software");

foreach (string skname in rk.GetSubKeyNames())
{

try
{
sname = Registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("DisplayName").ToString();
ListView1.Items.Add(sname);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);


}

VB.NET

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim SoftwareKey As String = "SOFTWAREMicrosoftWindowsCurrentVersionInstallerUserDataS-1-5-18Products"
Dim rk As RegistryKey
rk = Registry.LocalMachine.OpenSubKey(SoftwareKey)
Dim skname As String
Dim sname As String = String.Empty

Dim ListView1 As New ListView
Me.Controls.Add(ListView1)
ListView1.Dock = DockStyle.Fill

ListView1.View = View.Details
ListView1.Columns.Add("Installed Software")

For Each skname In rk.GetSubKeyNames
Try
sname = Registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("DisplayName")
ListView1.Items.Add(sname)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next

ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)

End Sub

Output:

Downloads:


vb.net : Download
c#.net : Download

 
%d bloggers like this: