Showing posts with label Visual Basic. Show all posts
Showing posts with label Visual Basic. Show all posts

Tuesday, November 2, 2021

[VB.net][example] Remove all subfolder from a list of Folder

I have a list of folders, where "C:\Source\hidden" and "C:\Source\hidden\hidden" are subFolder of "C:\Source" and "C:\Shit\hidden" and "C:\Shit\hidden\hidden" are subFolder of C:\Shit\", what i want is remove all subFolder from a lists and keep the folders "C:\Source\" and "C:\Shit\" only.

folder structure:

  • C:\Source\
    • C:\Source\hidden
      • C:\Source\hidden\hidden
  • C:\Shit\
    • C:\Shit\hidden
      • C:\Shit\hidden\hidden

Solution:

Module VBModule

    Sub Main()

        Dim dirs As System.Collections.Generic.List(Of String) = new System.Collections.Generic.List(Of String)

        Dim res As System.Collections.Generic.List(Of String) = new System.Collections.Generic.List(Of String)

        dirs.Add("C:\Source\")

        dirs.Add("C:\Source\hidden")

        dirs.Add("C:\Source\hidden\hidden")

        dirs.Add("C:\Shit\")

        dirs.Add("C:\Shit\hidden")

        dirs.Add("C:\Shit\hidden\hidden")

        

        for each dir as String in getRootFolders(dirs)

            Console.WriteLine(dir)

        Next 

    End Sub

    

    private function getRootFolders(ByRef dirs As System.Collections.Generic.List(Of String))As System.Collections.Generic.List(Of String)

        Dim res As System.Collections.Generic.List(Of String) = new System.Collections.Generic.List(Of String)

        If dirs.Count = 0 then return res

            

        dirs.sort()

        res.add(dirs(0))

        

        for i as integer = 1 To dirs.count - 1

            Dim cur As String = dirs(i)

            Dim prev As String = res(res.Count - 1)

            Dim curLen As integer = cur.length

            Dim prevLen As integer = prev.length

            

            ' Path.DirectorySeparatorChar = "\"

            If curLen > prevLen AndAlso cur(prevLen-1) = "\" AndAlso prev.Equals(cur.subString(0, prevLen)) Then

                continue For

            Else

                res.add(cur)

            End if

        Next

        return res

    End Function

End Module

result:
C:\Shit\
C:\Source\

reference:

Monday, November 1, 2021

[VB.net][Example] Sort file by last modified date, and then the file name

This function is added for custom compare feature. ordering files by last-modified date by descending-order and then if files' modified-date are same, these files with same modified-date would be sort by ascending order.

Solution

private function CompareFiles(ByVal xObj As Object, ByVal yObj As Object) As Integer

  Dim comparer As New CaseInsensitiveComparer()

  Dim x As FileInfo = Ctype(xObj, FileInfo)

  Dim y As FileInfo = Ctype(yObj, FileInfo)

  Return Iif(x.LastWriteTime = y.LastWriteTime _ 

    comparer.Compare(x.Name, y.Name), _ 

    comparer.Compare(y.LastWriteTime, x.LastWriteTime))

End function

Call functions:

Dim result As List(Of FileInfo) = New List(Of FileInfo)

result.Add(New FileInfo("C:\Source\1.txt"))

result.Add(New FileInfo("C:\Source\2.txt"))

result.Add(New FileInfo("C:\Source\3.txt"))

result.Sort(AddressOf CompareFiles)

Wednesday, October 27, 2021

[VB.net][example] Get total files size of a directory

 For example, i have a directory tree (# is a folder):


  • #root (C://root/) -----------0kb
    • #hidden 
      • 0byte.txt -------------0kb
      •    - 2bytes.txt --------2kb
      • hidden.txt ------------13kb
    • #noChild 
    • #normal 
      • 0byte.txt -------------0kb
      • 2bytes.txt ------------2kb
      • hidden.txt ------------13kb


solution

imports System.IO

Class test

  Private function getDirFilesSize(ByVal rootPath as String, Optional ByRef size As Long=0) As Long

    if directory.Exists(rootPath) Then

                Dim di As DirectoryInfo = New DirectoryInfo(path) 

      Dim folderInfo As DirectoryInfo = new IO.DirectoryInfo(rootPath)

      'For Each fileInfo in In folderInfo.GetFiles: size += fileInfo.Length

                 For Each fileInfo in In di.GetDirectories("*.*", SearchOption.AllDirectories) : size += fileInfo.Length 

      Next

      'For Each subFolderInfo In folderInfo.GetDirectories: getDirFilesSize(subFolderInfo.FullName, size)

For Each subFolderInfo In di.GetFiles("*.*", SearchOption.AllDirectories): getDirFilesSize(subFolderInfo.FullName, size) 

      Next 

    End if

    Return size

  End function

End Class


call the function getDirFilesSize("C://root/") would get the result as 30.

Monday, October 25, 2021

[VB.net][Example] Safely delete directories

This project required delete folders with thread-safe, support you added a list of directory-path into pendingDelteDirectories before you call removeDirectories() function.


Class Test

Private pendingDelteDirectories As List(Of String) = New List(Of String)

Private sortLock As New Object

Private removeDirectoryLock As New Object


Public Sub removeDirectories()

  Dim currentHandleDir As String = String.Empty

  SyncLock sortLock

    pendingDeleteDirectories.Sort(Function(x,y) y.Length.CompareTo(x.Length))

    If (pendingDeleteDirectory).Count > 0 AndAlso getFolderSize(pendingDeleteDirectories) > 0) Then Return

  End


  Try

    SyncLock removeDirectoryLock 

      For Each dir As String in pendingDeleteDirectories

        If Directory.Exists(dir) Then

          currentHandler = dir

          'Delete after checked empty

          If(Directory.Exists(dir) AndAlso _

             getFolderSize(dir) = 0 AndAlso _ 

             Directory.GetDirectories(dir,"*", SearchOption.AllDirectories).Length = 0) Then

               Directory.Delete(dir, False)

          End If

        End If

      Next 

      pendingDeleteDirectories = New List(Of String)

    End SyncLock

  Catch ex As Exception

    Debug.WriteLine(ex.toString())

  End Try

End Sub


End Class

Wednesday, October 20, 2021

[VB.NET][example] Replace all date-Patterns within a string

 

i have a string with 2 date-patterns "yyyyMMdd" and "yyyyMMddHHmmss" within a pair of <>:

"C:\Main\Program\Log\<yyyyMMdd>\infoReport_<yyyyMMddHHmmss>.log"

what i would like to do is replace the first date-pattern with "#", and the second with "@".

so that the result should be :

"C:\Main\Program\Log\#\infoReport_@.log"


Solution:

Imports System.Text.RegularExpressions

Module VBModule

    private filepath As String ="C:\Main\Program\Log\<yyyyMMdd>\infoReport_<yyyyMMddHHmmss>.log"

    private Const PREFIX As String = "<"

    private Const SURFIX As String = ">"

        

    Sub Main()

        Console.WriteLine("result: " & replaceDatePatterns(filepath))

    End Sub

    

    function replaceDatePatterns(ByVal filepath as String) As String

        Dim result As String = filepath

        Dim regex As New Regex(String.Format("({0}).+?({1})", PREFIX, SURFIX))

        Dim i As integer = 0

        

        If NOt filepath.Contains(PREFIX) AndAlso not filepath.contains(SURFIX) then return result

        For Each match As Match In regex.Matches(filepath)

            Select case i

               CASE 0 :

                   result = Replace(result, match.Value, "#")

               CASE 1 :

                   result = Replace(result, match.Value, "@")

            End Select

            i +=1

        Next

        return result

    End function

End Module

output:

result: "C:\Main\Program\Log\#\infoReport_@.log"

Reference:

https://vimsky.com/zh-tw/examples/detail/vbnet-method-system.text.regularexpressions.regex.matches.html

https://www.dotnetperls.com/regex-vbnet

https://www.dreamincode.net/forums/topic/118009-how-i-read-text-between-specific-begin-end-tags/

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/select-case-statement

Friday, August 27, 2021

[VB.net][Example] print message with commend prompt console in WFA

I found a script works and copy here, i worry i don't know where to found this again someday:


Option Compare Binary

Option Explicit On

Option Infer Off

Option Strict On


Imports System


Public Class Form1

   Private Declare Function AllocConsole Lib "Kernel32.dll" () As Integer

   Private Declare Function GetStdHandle Lib "Kernel32.dll" (ByVal nStdHandle As Integer) As Integer

   Private Declare Function WriteConsoleA Lib "Kernel32.dll" (ByVal hConsoleOutput As Integer, ByVal lpBuffer As String, ByVal nNumberOfCharsToWrite As Integer, lpNumberOfCharsWritten As Integer, lpReserved As Integer) As Integer


   Private Const STD_OUTPUT_HANDLE As Long = -11


   Private Sub Form1_DoubleClick(sender As Object, e As EventArgs) Handles MyBase.DoubleClick

      AllocConsole()

      Dim OutputHandle As Integer = GetStdHandle(STD_OUTPUT_HANDLE)

      Dim Text As String = "test"


      WriteConsoleA(OutputHandle, Text, Text.Length, 0, 0)

   End Sub

End Class


Beware the text highlighted with yellow text, if you use the keyword "WriteConsole" would got "EntryPointNotFoundException was unhanded" error


Reference:

https://www.vbforums.com/showthread.php?888189-Console-from-Winform-App-not-writing-lines

Thursday, August 26, 2021

[VB.Net][Example] vb get date before some days

Requirement:

Client want provide a filename pattern and an number about how many days before:

for example, today is 2021/08/26

0 --> cmsPhoto_20210826.xml

1 --> cmsPhoto_20210825.xml

2 --> cmsPhoto_20210824.xml

3 --> cmsPhoto_20210823.xml

4 --> cmsPhoto_20210822.xml


So I found the pattern of this filename is:

cmsPhoto_<yyyyMMdd>.xml


Code:

Dim XML_FILENAME_PATTERN = "cmsPhoto_<yyyyMMdd>.xml"

Sub Main()

    Console.WriteLine("filename: " & getXmlFilenameByDay(1))

End Sub

    

Function getXmlFilenameByDay(ByVal day As Integer) As String

    Dim filename As String = XML_FILENAME_PATTERN

    Dim openChar As String = "<"

    Dim closeChar As String = ">"

    Dim datePattern As String = filename.Substring(filename.IndexOf(openChar) + 1, filename.IndexOf(closeChar, filename.IndexOf(openChar)) - filename.IndexOf(openChar) - 1)

    Dim dateStr As String = DateTime.Now.AddDays(day*-1).ToString(datePattern)

    return XML_FILENAME_PATTERN.replace(openChar & datePattern & closeChar, dateStr)

End Function


Result :

If use 1 as arugument:

filename: cmsPhoto_20210825.xml

If use 2 as arugument:

filename: cmsPhoto_20210824.xml

If use -3 as arugument:

filename: cmsPhoto_20210829.xml


Reference:

https://stackoverflow.com/questions/25421425/print-yesterdays-date

Thursday, June 24, 2021

[VB.net][example] Get all form controls

Example:

For Each ctrl In Form1.Control

    Trace.WriteLine(ctrl.getType().toString())

Next

where Form1 is your form name, if you omit it mean you loop for controls in current form.


Addition examples:

To do validation on all form-control which are in groupBox and are not label:

For Each ctrl In Control

  If GetType(ctrl) IS System.Window.Forms.Groupbox

    For Each ctrlItem In ctrl

        If NOT GetType(ctrlItem) IS System.Window.Forms.Label

          IF ctrlItem.Text.Length = 0 THEN

            MessageBox.Show("Please fill in all blanks.")

            ctrlItem.Focus()

          END IF

        End If

    Next

  End If

Next


Reference

https://stackoverflow.com/questions/199521/vb-net-iterating-through-controls-in-a-container-object

https://bytes.com/topic/net/answers/560738-determining-control-type-vb-net-runtime

https://stackoverflow.com/questions/11335529/going-through-controls-in-order

Thursday, June 17, 2021

[VB.net][Resolved] dataGridView dataAdapter value not show

I have set some dataSet and BindingSource and used this code.

These code should show 5 rows of record but it shows 6 empty rows only (including 1 empty new lines), 

the values form database can't be matched:


Source

Import Oracle.DataAccess.Client

Public Class Form1

  Dim dbCommand As OrcaleCommand

  Dim sAdapter As OracleDataAdapter

  Dim sBuilder As OracleCommandBuilder

  Dim dsData As DataSet

  Dim dtData As DataTable

  

  Private Sub loadBtn_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loadBtn.Click

    Dim connStr As String = "DataSource=.;Initial Catalog=pubs;Integrated Security=Time"

    Dim sql As String = "SELECT * FROM (SELECT * FROM LIBBKN_BATCH ORDER BY BATCH_NO) WHERE ROW_NAME <=5"

    Dim conn As OrcaleConnection(connStr)

    conn.Open()

    dbCommand = New OrcaleCommand(sql, conn)

    sAdapter = New OrcaleDataAdapter(dbCommand)

    sBuilder = New OrcaleCommandBuilder(sAdapter)

    dsData = New DataSet()

    sAdapter.Fill(sDs,"BATCH")

    sTable = sDs.Tables("BATCH")

    conn.Close()

    

    Me.dgv.DataSource = dsData.Tables("BATCH")

    Me.dgv.DataSource.ReadOnly = True

  End Sub

End Class


After some search from internet, I found my problem is I set the "name" of column only,

I should also set "DataPropertyName" value, value need to same as database column name.

(This Image from ShunNien's Blog)


Reference

https://stackoverflow.com/questions/24049866/winforms-datagridview-showing-blank-rows

https://shunnien.github.io/2015/12/15/DataGridView-in-winform-1/

Tuesday, June 15, 2021

[VB.net][Resolved] DataAccess.Client.OracleException ORA-00911 invalid character

Error message:

DataAccess.Client.OracleException ORA-00911 invalid character


Source:

Dim oradb As String = "Data Source=127.0.0.1/CLP;User Id=user;password=password"

com = New OracleConnection(oradb)


Dim cmd As New OrcaleCommand

cmd.Connection = conn

cmd.CommandText = "SELECT COUNT(*) AS amount FROM batches WHERE batch_no LIKE '20200713%';"


Dim dr As OracleDataReader = cmd.ExecuteReader()

dr.Read()


Solution:

sql syntax error, for my case is remove the semi-colon from the end of sql:

change 

cmd.CommandText = "SELECT COUNT(*) AS amount FROM batches WHERE batch_no LIKE '20200713%';"

to 

cmd.CommandText = "SELECT COUNT(*) AS amount FROM batches WHERE batch_no LIKE '20200713%'"


Reference: 

https://stackoverflow.com/questions/12262145/ora-00911-invalid-character/18456333


Sunday, June 6, 2021

[VB.net][Resolved] hide column from data grid view

 Suppose the name of dataGridView is "dgv1" and you want to hide column "age":

if(dgv1.Columns.Contains("age")){

  dgv1.Columns("age").Visible = False

}


Reference:

https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-hide-columns-in-the-windows-forms-datagridview-control?view=netframeworkdesktop-4.8

https://stackoverflow.com/questions/12836064/how-to-check-if-column-exists-in-a-datagridview

Tuesday, May 11, 2021

[VB.net][Resolved] 父資料行和子資料行沒有型別相符的資料行

我用Visual Basic 的 DataRelation 將2個dataTable connect,

parent column 的mysql dataType 是int(10), 

child column 的mysql dataType 是int(18)。


然後我得到一個error message「父資料行和子資料行沒有型別相符的資料行」,

網民討論原因都是說parent column 及 child column的dataType不相符。

那麼好吧,我在MySql database alter table 統一設定成dataType 為int(18),

但仍是有這個「父資料行和子資料行沒有型別相符的資料行」error message,

百思不得其解,然後我嘗試print 出兩個dataTable的dataType 出黎:


Dim dt As Datatable = dataSet.Tables(TERRAPINS_SKY)

Dim row As DataRow

Dim column As DatColumn

For Each row In dt.Rows

    For Each column In dt.Columns

        Debug.Writeline(row(Column) & ", (" & column.DatType.toString() &")")

    Next

    Debug.WriteLine(Envirnment.NewLine())

Next


dt = dataSet.Tables(TERRAPINS_SKY_DETAIL)

For Each row In dt.Rows

    For Each column In dt.Columns

        Debug.Writeline(row(Column) & ", (" & column.DatType.toString() &")")

    Next

    Debug.WriteLine(Envirnment.NewLine())

Next


然後得出作為parent的dataTables PAPAER_NAME 的key column dataType是 System.Int32,作為child的dataTables PAPAER_NAME_DETAIL 的key column dataType是 System.UInt32。


UInt32 ?!?!?這是什麼鬼!??!

原來我在MySql把其中一個table的column set了作unsigned, 所以這個column內容的data type在visual basic成了System.UInt32,而另一個table的column 沒有set unsigned, 所以這個column內容的data type在visual basic成了System.Int32,

alter table column 的sql例子:

ALTER TABLE 'lib'.'terrapinssky_table' CHNAGE COLUMN 'PAPER_ID' 'PAPER_ID' INT(18) UNSIGNED NOT NUL DEFAULT '0';


所以如果遇上「父資料行和子資料行沒有型別相符的資料行」error message,

不單要確保你想有vb relation 的兩個database table 的column data Type 相同,而且連是否unsigned也須一樣。


Thursday, April 22, 2021

[VB.net][Resolved] Incorrect datatime value '' for column 'in_pub_date' at row 417

Visual Basic Exception message:

Incorrect datatime value '' for column 'in_pub_date' at row 417


Mysql Stored prodcedure

DELIMITER$$

CREATE PEFINER='root'@'%' PROCEDURE 'SP_TEST'(

  IN_DATE DATETIME

)

BEGIN

  -- Do sth here

END


VB code

Case 1

With dbCommand

  .CommandText = 'SP_TEST'

  .Parameters.Clear()

  .Parameter.AddWithValue("?IN_DATE","")

  .CommandType = CommandType.StoredProcedure

End If


To 

With dbCommand

  .CommandText = 'SP_TEST'

  .Parameters.Clear()

  .Parameter.AddWithValue("?IN_DATE",DBNull.Value)

  .CommandType = CommandType.StoredProcedure

End If


Case 2

With dbCommand

  .CommandText = 'SP_TEST'

  .Parameters.Clear()

  .Parameter.AddWithValue("?IN_DATE", inDate) -- Where valse of inDate is ""

  .CommandType = CommandType.StoredProcedure

End If


To 

With dbCommand

  .CommandText = 'SP_TEST'

  .Parameters.Clear()

  .Parameter.AddWithValue("?IN_DATE", IIF(NOT inDate = "", inDate, DBNull.Value))

  .CommandType = CommandType.StoredProcedure

End If

Wednesday, April 21, 2021

[VB.Net][stored procedure] vb date type to mysql datetime format

Source:

Dim dbCommand As New MySqlCommand

With dbCommand

  .Connection = gConn

  .CommandText = "SP_TEST"

  .Parameters.Clears()

  .Parameters.AddWithValue("?IN_DATE",paper.pubDate) 'Where paper.pubDate is type "Date"

  .Parameters.Add("?OUT_RESULT",MySqlDbType.Int16.).Direction = ParamterDirection.Output

  .CommandType = CommandType.StoredParameter

End With


Correction: Using toString() function to out the date to mysql datetime format string.

Dim dbCommand As New MySqlCommand

With dbCommand

  .Connection = gConn

  .CommandText = "SP_TEST"

  .Parameters.Clears()

  .Parameters.AddWithValue("?IN_DATE",paper.pubDate.toString("yyyy-MM-dd HH:mm:ss"))

  .Parameters.Add("?OUT_RESULT",MySqlDbType.Int16.).Direction = ParamterDirection.Output

  .CommandType = CommandType.StoredParameter

End With


Reference:

https://www.vbforums.com/showthread.php?733665-RESOLVED-Insert-date-into-mysql

Wednesday, March 31, 2021

[VB.net][Resolved] VB DataSource 上找不到DataMember屬性 "xxx"

 I change the code from .net framework 2 to 3 and get this problem

Source

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

  girdDatasrc.DataSource = dataSet

  girdDatasrc.DataMember = "AUDIT_LOG" // cause error

  Me.girdDatasrc.DataSource = girdDatasrc

End Sub


Firstly, you need to initial the bindingSource in xxx_load function

And then you have to set DataMember of BindingSource before setting DataSource.

Updated

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

  Dim girdDatasrc As New BindingSource = New BindingSource()

  girdDatasrc.DataMember = "AUDIT_LOG"

  girdDatasrc.DataSource = dataSet

  Me.girdDatasrc.DataSource = girdDatasrc

End Sub


Reference

http://www.blueshop.com.tw/board/FUM20050124191756KKC/BRD201012200958052AN.html

Wednesday, February 24, 2021

[VB.Net][example] get string within tags

 Module VBModule

    Sub Main()

        Dim patternStr AS String = "<NUM> <PUBNAME> | <PUBDATE>"

        Dim patterns As String() = patternStr.split("<")

        Dim patternLen As Integer = patterns.length - 1

        

        For index As Integer = 1 To patternLen

            Console.WriteLine(patterns(index).Substring(0, patterns(index).IndexOf(">")))

        Next

    End Sub

End Module


Result:

NUM

PUBNAME

PUBDATE


Sunday, January 10, 2021

[VB.net][example] vb.net open file browser multiselect

 vb.net open file browser multiselect

Dim ofd As OpenFileDialog = New OpenFileDialog()

Dim ofdFileName As String

ofd.Title = "Open File Dialog"

ofd.InitialDirectory = "C:\"

ofd.Filter = "All files(*.*)|*.*"

ofd.FilterIndex=2

ofd.RestoreDirectory=True

ofd.Multiselect = True


If ofd.ShowDialog() == DialogResult.OK Then

  For Each mFile As String In fd.FileNames

    Debug.WriteLine(mFile)

  Next

EndIf

Result:

C:\1.txt

C:\2.jpg

C:\3.txt


Reference:

https://stackoverflow.com/questions/32288216/select-multiple-files-and-load-the-file-names-to-checked-list-box

Thursday, January 7, 2021

[VB.net][Oracle][example] Add items to datagridView from Orcale

This part of script is from one of the vb projects.

beware that there is some syntax such as OracleDataAdapter Class has been deprecated :

Imports System.Data

Imports System.IO

Imports Orcale.DataAccess.Client

Imports Orcale.DataAccess.Types


Public Class Form1

  Private connStr As String = "Data Source=192.168.1.1/TestDb; User Id=user; password=pwd"

  Private conn As New OrcaleConnection

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

  Try

    Dim ds As New DaatSet()

    Using conn As OracleConnection = New OracleConnection(connStr)

      conn.Open()

      Using cmd As OracleCommand = New OracleCommand("SELECT * FROM TEST_TABLE ORDER BY ID",conn)

      Dim dr As OracleDataReader = cmd.ExecuteReader()

        While dr.Read()

          Dim rowId As Integer = DataGridView1.Rows.Add()

          Dim row As DataGridViewRow = DataGridView1.Rows(rowId)

          row.Cells("idColumn").Value = dr.Item(0)

          row.Cells("typeColumn").Value = dr.Item(1)

        End While

      End Using

    End Using

  Catch ex As Exception

    Debug.WriteLine(ex.ToString())

  Finally

    conn.Dispose()

  End Try

End Sub

Reference

  • https://www.codegrepper.com/code-examples/csharp/vb.net+add+row+to+datagridview+programmatically
  • https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/GettingStartedVBVersion/GettingStartedNET_VBVersion.htm

Wednesday, January 6, 2021

[VB.net][Resolved] property value is not valid

I want last column of dataGridView automatically resize according width of application.

White I set the autoSize property to Fill on last column, it pop up an error message:

Error message: Property value is not valid

check details

Column's AutoSize mode cannot be set to Fill when it is also a frozen column


Steps:

I fix this problem in design mode but not using code.

1) Select dataGridView in designmode, and click the right-arrow icon to open "DataGridView Task" menu.

2) Select "edit Columns..." item in menu and it would popup "Edit Column" window.

3) There should be some column items under "selected Columns" text (if you don't have, add some columns)

4) In edit column panel, set "frozen" property value to False in "layout" catalog. apply on all your columns in dataGridView.

5) For last column, set "AutoSizeMode" property value to "Fill" in "layout" catalog., others columns all set to "AllCells"

6) Click "OK"


Remark: If you want dataGridView able to autoresuze according you window form application size, Set Anchor in your property panel to "Top, Bootom, Left, Right"


Reference:

https://stackoverflow.com/questions/1025670/how-do-you-automatically-resize-columns-in-a-datagridview-control-and-allow-the

Tuesday, January 5, 2021

[VB.net][WFA][example] Get ToolStripMenu items

 

Private Sub ColourToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ColourToolStripMenuItem.Click
  Dim count As Integer = sender.DropDownItems.Count
  For Each subItem In sender.DropDownItems
    Dim objAsConvertible = TryCast(subItem, ToolStripMenuItem)
    If Not objAsConvertible Is Nothing Then
      Dim tsm As ToolStripMenuItem = DirectCast(subItem, ToolStripMenuItem)
      Debug.WriteLine(CStr(tsm.Text)+":"+CStr(tsm.Name))
    End If
  Next
End Sub