Showing posts with label Dot Net. Show all posts
Showing posts with label Dot Net. Show all posts

Tuesday, 8 December 2015

Adding CheckBox to DataGridView in VB.NET

The DataGridView control uses several column types to display its information and enable users to modify or add information. The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types.
The following vb.net program shows how to add a CheckBox in Cell of a DataGridView control and set the third row checkbox value as true. If you want to respond immediately when users click a check box cell, you can handle the CellClick event, but this event occurs before the cell value is updated.

Example:

Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        DataGridView1.ColumnCount = 3
        DataGridView1.Columns(0).Name = "Product ID"
        DataGridView1.Columns(1).Name = "Product Name"
        DataGridView1.Columns(2).Name = "Product_Price"

        Dim row As String() = New String() {"1", "Product 1", "1000"}
        DataGridView1.Rows.Add(row)
        row = New String() {"2", "Product 2", "2000"}
        DataGridView1.Rows.Add(row)
        row = New String() {"3", "Product 3", "3000"}
        DataGridView1.Rows.Add(row)
        row = New String() {"4", "Product 4", "4000"}
        DataGridView1.Rows.Add(row)

        Dim chk As New DataGridViewCheckBoxColumn()
        DataGridView1.Columns.Add(chk)
        chk.HeaderText = "Check Data"
        chk.Name = "chk"
        DataGridView1.Rows(2).Cells(3).Value = True

    End Sub
End Class

Friday, 4 December 2015

Global Connection Code in Vb.net

Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms

Module [Global]

''---------------------------------------------------------------------------------------------------- 
    Public Const scon As String = "Data Source=servername8;Initial Catalog=databasename;" & _
                                                           "Persist Security Info=True;User ID=SA;Password=Welcome"

    Public struser As String = "ADMIN"
    Public ssql As String
    Public strtem As String
    Public inttem As Integer
    Public blntemp As Boolean

    Public dttable As DataTable
    Public dtset As New DataSet()
    Public dataAdapt As New SqlDataAdapter()

    Public sqlConnection As SqlConnection = New SqlConnection(scon)
    Public sqlcmd As SqlCommand
''----------------------------------------------------------------------------------------------------
    Public Function dsdttable(ByVal sql As String)
        Try
            dttable = Nothing
            Using conn As New SqlConnection(scon)
                Using comm As New SqlCommand()
                    With comm
                        .Connection = conn
                        .CommandType = CommandType.Text
                        .CommandText = sql

                        Try
                            conn.Open()
                            dataAdapt.SelectCommand = comm
                            dtset.Dispose()
                            dtset.Tables.Clear()
                            dataAdapt.Fill(dtset)
                            dataAdapt.Dispose()
                            comm.Dispose()
                            conn.Close()
                            dttable = dtset.Tables(0)
                            dtset.Dispose()
                            Return dttable


                        Catch ex As Exception
                            MessageBox.Show(ex.Message.ToString(), "Error Message")
                        End Try
                    End With
                End Using
            End Using

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Function
''----------------------------------------------------------------------------------------------------
    Public Function ExecuteSql(ByVal sql As String) As Boolean
        Try
               Using conn As New SqlConnection(scon)
                Using comm As New SqlCommand()
                    With comm
                        .Connection = conn
                        .CommandType = CommandType.Text
                        .CommandText = sql
                    End With
                    Try
                        conn.Open()
                        comm.ExecuteNonQuery()
                        conn.Close()
                        Return True
                    Catch ex As Exception
                        MessageBox.Show(ex.Message.ToString(), "Error Message")
                    End Try
                End Using
            End Using
        Catch ex As Exception
            MsgBox(ex.ToString)
            Return False
        End Try
    End Function
''----------------------------------------------------------------------------------------------------
  Public Function cConOpen() As Boolean
        Try
            If ConnectionState.Open = True Then
                sqlConnection.Close()
                sqlConnection.Open()
                Return True
             Else
                sqlConnection.Open()
                Return True
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Function
''----------------------------------------------------------------------------------------------------
End Module

Sunday, 29 November 2015

Validating Multiple Controls in VB.NET

If you have ever built a form in Visual Studio with say 10 textboxes, you then want to validate all 10 textboxes on a certain event, well naturally you could go through each one like so
If txtTextBox1.Text = "" then

End If

If txtTextBox1.Text = "" then

End If

If txtTextBox1.Text = "" then

End If
etc.......
But this leads to messy and tedious code so below is an example on how to loop through controls on a form and validate them on the way.
For Each ctrl As Control In Me.Controls
    If ctrl.Text = "" Then
        MessageBox.Show("Invalid input for " & ctrl.Name)
        Exit Sub
    End If
Next
Ok so this validates all the controls on the form which may not be what we are after so how about checking the type of the control inside the loop? This way we can validate only textboxes or only combo boxes as we need, but what if we only want to validate so many of our text boxes? Keep reading!
For Each ctrl As Control In Me.Controls
    If TypeOf ctrl Is TextBox Then
        If ctrl.Text = "" Then
            MessageBox.Show("Invalid input for " & ctrl.Name)
            Exit Sub
        End If
    End If
Next
So now we know how to check different types of controls but what if I have 6 Textfields that are string and then another 4 that are phone numbers or numeric values? Well if we name the controls correctly we could check against any control we like based on their name, this allows us to group controls for specific validation tasks.
        For Each ctrl As Control In Me.Controls
            If TypeOf ctrl Is TextBox Then
                'check if it should be string
                If ctrl.Name.StartsWith("txtString") Then
                    'check if its valid value
                    If ctrl.Text = "" Then
                        'if its blank exit sub
                        MessageBox.Show("Invalid Input")
                        Exit Sub
                    End If
                    'check if it should be numeric
                ElseIf ctrl.Name.StartsWith("txtInt") Then
                    'validate that it is numeric
                    If Not IsNumeric(ctrl.Text) Then
                        'if not show error and exit sub
                        MessageBox.Show("Please enter Numeric Values for Phone Numbers")
                        Exit Sub
                    End If
                End If

            End If
        Next
You can see that for controls where we want string values entering, we name them txtString and for controls where we want numeric values we name them txtInt. This is only a simple example and you could take it further by looking at the rest of the control name say txtStringAddress which would allow you to give more friendly error messages specific to the correct field.

If In Form textbox is within the Groupbox or Panal u can use like:


         For Each ctrl As Control In Me.Controls
                If CheckControlValidation(ctrl) = False Then
                    Exit Sub
                End If
         Next
 Private Function CheckControlValidation(ByVal cnt As Control) As Boolean
     Try
        If TypeOf cnt Is GroupBox  or  TypeOf cnt Is Panel Then
           For Each control As Control In cnt.Controls
                    'Loops through array of controls
              If TypeOf control Is TextBox Then
                   If control.Text = "" Then
                       MessageBox.Show("Invalid input for " & control.Name)
                       control.Focus()
                       Return False
                   End If
               End If
           Next

        ElseIf TypeOf cnt Is TextBox Then

          'check if it should be string
          If cnt.Name.StartsWith("txtString") Then
                 'check if its valid value
              If cnt.Text = "" Then
                'if its blank exit sub
                  MessageBox.Show("Invalid Input")
                  cnt.Focus()
                  Return False
                  End If
            'check if it should be numeric
           ElseIf cnt.Name.StartsWith("txtInt") Then
                    'validate that it is numeric
            If Not IsNumeric(cnt.Text) Then
                        'if not show error and exit sub
               MessageBox.Show("Please enter Numeric Values for Phone Numbers")
               cnt.Focus()
               Return False
            End If
          End If
       End If
       Return True
            
   Catch ex As Exception
            MbErr(ex)
    End Try
End Function
Thank You...

Add Dynamic TextBox, Label and Button controls with TextChanged and Click event handlers in Windows Forms (WinForms) Application

In this article I will explain how to add dynamic controls like Label, TextBox, Button, etc. to Windows Forms Application on click of a Button.
I will here also explain how we can attach event handler to various dynamically added controls like TextBox, Button, etc.

Form Layout
The form layout consists of a Button and a Panel control to add dynamic controls within it.


Namespaces
You will need to import the following namespaces.
C#
using System.Linq;
using System.Drawing;

VB.Net
Imports System.Linq
Imports System.Drawing


Dynamically adding Windows Label Control
Firstly we need to create a new object of the Label control and then count of the Label controls is determined, Count is useful to give number incremented unique Ids to the controls as well as for setting location of the controls on the Windows Form so that controls don’t overlap each other. After the location, the remaining properties like Size, Name and Text are set. Finally the Label control is added to the Windows Forms Panel control.
C#
Label label = new Label();
int count = panel1.Controls.OfType<Label>().ToList().Count;
label.Location = new Point(10, (25 * count) + 2);
label.Size = new Size(40, 20);
label.Name = "label_" + (count + 1);
label.Text = "label " + (count + 1);
panel1.Controls.Add(label);

VB.Net
Dim label As New Label()
Dim count As Integer = panel1.Controls.OfType(Of Label)().ToList().Count
label.Location = New Point(10, (25 * count) + 2)
label.Size = New Size(40, 20)
label.Name = "label_" & (count + 1)
label.Text = "label " & (count + 1)
panel1.Controls.Add(label)


Dynamically adding Windows TextBox Control
Similar to Label the TextBox control is dynamically added, the only difference here is the Text property and the dynamic TextChaned event handler.
C#
TextBox textbox = new TextBox();
count = panel1.Controls.OfType<TextBox>().ToList().Count;
textbox.Location = new System.Drawing.Point(60, 25 * count);
textbox.Size = new System.Drawing.Size(80, 20);
textbox.Name = "textbox_" + (count + 1);
textbox.TextChanged += new System.EventHandler(this.TextBox_Changed);
panel1.Controls.Add(textbox);

VB.Net
Dim textbox As New TextBox()
count = panel1.Controls.OfType(Of TextBox)().ToList().Count
textbox.Location = New System.Drawing.Point(60, 25 * count)
textbox.Size = New System.Drawing.Size(80, 20)
textbox.Name = "textbox_" & (count + 1)
AddHandler textbox.TextChanged, AddressOf TextBox_Changed
panel1.Controls.Add(textbox)

The following dynamic TextChanged event handler is raised when the text is changed inside the dynamic TextBox control.
C#
private void TextBox_Changed(object sender, EventArgs e)
{
    TextBox textbox = (sender as TextBox);
    MessageBox.Show(textbox.Name + " text changed. Value " + textbox.Text);
}

VB.Net
Private Sub TextBox_Changed(sender As Object, e As EventArgs)
    Dim textbox As TextBox = TryCast(sender, TextBox)
    MessageBox.Show(textbox.Name + " text changed. Value " + textbox.Text)
End Sub


Dynamically adding Windows Button Control
Similar to the TextBox control, here a Button control is dynamically added. The only difference is that here we have a dynamic Click event handler.
C#
Button button = new Button();
count = panel1.Controls.OfType<Button>().ToList().Count;
button.Location = new System.Drawing.Point(150, 25 * count);
button.Size = new System.Drawing.Size(60, 20);
button.Name = "button_" + (count + 1);
button.Text = "Button " + (count + 1);
button.Click += new System.EventHandler(this.Button_Click);
panel1.Controls.Add(button);

VB.Net
Dim button As New Button()
count = panel1.Controls.OfType(Of Button)().ToList().Count
button.Location = New System.Drawing.Point(150, 25 * count)
button.Size = New System.Drawing.Size(60, 20)
button.Name = "button_" & (count + 1)
button.Text = "Button " & (count + 1)
AddHandler button.Click, AddressOf Button_Click
panel1.Controls.Add(button)

The following dynamic Click event handler is raised when the dynamic TextBox control is clicked.
C#
private void Button_Click(object sender, EventArgs e)
{
    Button button = (sender as Button);
    MessageBox.Show(button.Name + " clicked");
}

VB.Net
Private Sub Button_Click(sender As Object, e As EventArgs)
    Dim button As Button = TryCast(sender, Button)
    MessageBox.Show(button.Name + " clicked")
End Sub