Tag Archives: Winforms

[C# and VB.Net] How to close a form after confirmation in Winforms

How to close a form in c#  after confirming

 

 

You can put the following code in any button

 

          if (MessageBox.Show("Are you sure you want to exit?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                               this.Close();
            }

 

In VB.NET you can use the following code

 

 If MsgBox("Are you sure you want to close", MsgBoxStyle.YesNo, "Close Application") = MsgBoxResult.Yes Then

            Me.Close()
        End If

How to create a GUID in VB.NET

Here is a small function to return the GUID.

GUID stands for Globally Unique Identifiers. GUIDs are 128-bit globally unique identifiers and they are generated automatically based on close to two zillion frequently varying factors.
It has extremely low possibility that a generated GUID would equal to another GUID.

Function GenerateGUID() as string
return System.Guid.NewGuid.ToString()
End function

How to use Application Settings in Windows Forms using VB.NET

Learn how to use Applications Settings in Visual Studio 2013 Winform project in VB.NET

 

Here is a simple way of storing applications settings.

 

Step 1

In your Visual Studio Project open the settings.

Winform Settings
Winform Settings

Step 2

When you click on the Settings as shown in Step 1, you would get the following screen.

You can create your settings as shown below by providing your customised values in the Value column as shown below

Best-Answer.net

 

 

Step 3

 

Here is how you will use those values in your project .

Best-Answer.net Learn how to use settings in winform

How to create a Datatable programatically in VB.NET

Dim dt as new DataTable   
        ' Add the columns which you need in your datatable
        dt.Columns.Add("SNo", GetType(Integer))  '1
        dt.Columns.Add("Details", GetType(String))  '2
        dt.Columns.Add("Qty", GetType(String))  '3
        dt.Columns.Add("UnitRate", GetType(Double)) '4
        dt.Columns.Add("ApplyTax", GetType(Boolean))  '5
        dt.Columns.Add("ExTaxTotal", GetType(Double))  '6
        dt.Columns.Add("Tax", GetType(Double))  '7
        dt.Columns.Add("InclTaxTotal", GetType(Double)) '8
       
        ' Create a new row for your table
        Dim drow = dt.NewRow()

        ' Now add the items in your newly created row
        drow.Item(0) = 1
        drow.Item(1) = "My Details go here"
      
        drow.Item(2) = 1
        drow.Item(3) = 234
        drow.Item(4) = 1
        drow.Item(5) = drow.Item(2) * drow.Item(3)   ' You can also calculate the values
        drow.Item(6) = drow.Item(2) * 0.1
        drow.Item(7) = drow.Item(5) * drow.Item(6)


        ' Now add this row to the table
        dt.Rows.Add(drow)

        ' If you want you can display this  data in a datagrid  
        Me.DataGridView1.DataSource = dt

How to get the list of installed printers in vb.net

To get the list of installed printers on your computer use the following code which will populate a Combo box with the list of installed printers.

 

Private Sub PopulateInstalledPrintersCombo()
        ' Add list of installed printers found to the combo box. 
        ' The pkInstalledPrinters string will be used to provide the display string. 
        Dim i As Integer
        Dim pkInstalledPrinters As String

        For i = 0 To Printing.PrinterSettings.InstalledPrinters.Count - 1
            pkInstalledPrinters = Printing.PrinterSettings.InstalledPrinters.Item(i)
            comboInstalledPrinters.Items.Add(pkInstalledPrinters)

        Next
    End Sub

Learn how to printer address labels on Dymo Label Printer in VB.NET

How to loop through records in LINQ using VB.NET in Entity Framework

Here is a simple code snippet to loop through the records in VB.NET using LINQ

 

The following code example takes the records from an Entity Framework Model named as Video and then allows to loop through each record.

 

 

Dim List As List(Of Video)

List = (From video In db.Videos Order By video.ID Descending).ToList
For Each item In List
Debug.Print(item.CategoryID)
Debug.Print(item.VideoName)
Next

How to pass a variable from one winform to another in vb.net

There is often a need to pass a variable from one Winform to another.

There are two scenarios

Let us say you have two forms

1. You opened Form1 and then you want to open a new form called Form2 and you would want to carry some information from Form 1 to Form2.

The user has typed the Employee name  JOHN in the text box on the first form and then clicked on the Lookup Dept. This openes the second lookup form (Form2) where the user can select a Dept Name.

Notice that on the Form2 we have the Employee Name shown ( form1 opened  form2 and passed the value of EmployeeName)

SendVariablefromForm1ToForm2

2. You  have Form1 and Form2 already open and you want to pass a variable from Form2 to Form1

 

Once we select the Dept B on the Form 2 we click on Select and close. The second form (Form2) closes and the value of the selected department Dept B is passed back to the First form (Form1)

 

SendVariablefromForm2toForm1

 

Here is the code for the Form1

 

Public Class Form1
WithEvents fr As New Form2   ‘ Declare the new form using WithEvents
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
fr.lblEmployeeName.Text = Me.TextBox1.Text  ‘ Send the value of Textbox1 to the second Form
fr.Show()
End Sub

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

End Sub

Private Sub fr_GetDepartment() Handles fr.GetDepartment   ‘ This is the new Event which has been declared and raised from Second Form

Me.TextBox2.Text = fr.ListBox1.SelectedItem.ToString  ‘ The Listbox selected item value has been received from the second form

End Sub
End Class

Here is the code for Form2

 

 

Public Class Form2
Event GetDepartment()   ‘ You declare this Event for this Form which can be trapped from Form1
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With Me.ListBox1
.Items.Add(“Dept A”)
.Items.Add(“Dept B”)
.Items.Add(“Dept C”)
End With
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RaiseEvent GetDepartment()   ‘ We raise the event here in Form2 which will provide you an opportunity to trap it in Form1
Me.Close()
End Sub
End Class

 

 

 

How to fill a ComboBox using a DataTable in VB.NET

A Combo box has two properties

 

1.One which displays the items in the combo box called the DISPLAY MEMBER

2. Another one which stores the underlying ID for the Item which is being Displayed.

 

eg your table may have EmployeeId and EmployeeName.

You would like to display the EmployeeName in the ComboBox and when a user selects an employee name you would like to save the EmployeeID.

Function Fillcombo(ByVal SQL As String, ByVal CBO As ComboBox, ByVal DisplayMember As String, ByVal ValueMember As String)
Dim dt As New DataTable                  'Create a New DataTable
Dim dc As New SqlCommand              'Create a New SQLCommand
Dim da As New SqlDataAdapter         ' Create a New SQL Data Adapter
dc.CommandTimeout = 0
dc.CommandText = sql
da.SelectCommand = dc
dc.Connection = cn

da.Fill(dt)    ‘ Use the DataAdapter to fill the DataTable with the records
Try
CBO.DataSource = dt
CBO.DisplayMember = DisplayMember   ‘ This is the item which will be displayed on the combo box  eg Employee Name
CBO.ValueMember = ValueMember       ‘ This is the value which is stored eg. employeeID

Catch
MsgBox(“Unable to Fill the Combobox:” & CBO.Name & ” with values” & “:” & Err.Description)
End Try
End Function

 

 How to use the above function

Fillcombo(“Select EmployeeID,EmployeeName from Employees”, Me.EmployeeCombo, “EmployeeName”, “EmployeeID”)