Link to home
Start Free TrialLog in
Avatar of John (Yiannis) Toutountzoglou
John (Yiannis) ToutountzoglouFlag for Greece

asked on

How to match Button array from a class to dynamically created button on a form

here is my code...
from this code i get a null reference exception...
all other labels,buttons.tooltips are already there the form1 and i got no problem ..the problem is only with the btn
that i want to match it with the dynamically created Button...
thank you very much...
Public Class md
    Public state As String
    Public snoozeIconBtn As Button
    Public lbl As Label
    Public pb As PictureBox
    Public stateLbl As Label
    Public tooltip As ToolTip
    Public hover As Label
    Public c As Integer
    Public sch(40) As timeSpan
    Public sch_count As Integer
    Public name As String
    Public active As Boolean
    Public alarmOn As Boolean
    Public attentionOn As Boolean
    Public Sensor As String
    Public GetSensorsName As String
    Public tr As Label
    Public rec As String
    Public btn As Button
    Private RedFlag As Boolean
    'public readonly property

    
    Public Sub New(ByVal i As Integer)

        Me.btn = Form1.fbtn(i)   '>>>>>>if fbtn(i) buttons are alreadey there , i can figure it out but there are not yet
        Me.lbl = Form1.lbl(i)
        Me.stateLbl = Form1.state(i)
        Me.tooltip = Form1.tooltip(i)
        Me.hover = Form1.hover(i)
        Me.c = i
        Me.sch_count = 0
        Me.snoozeIconBtn = Form1.snoozeIconBtn(i)
        Me.pb = Form1.Picturebox(i)
        Me.Sensor = Form1.sensor(i)
        Me.tr = Form1.act(i)
    End Sub
    
    
    Public Sub setAlarm(ByVal val As Boolean)
        If val = True Then
            RedFlag = True
            Me.btn.BackColor = Color.Red    '>>>> here i got the exception !!!!
            Me.alarmOn = True
            ' rec = tr.Text
            GetSensorsName = Me.btn.Text
        Else
            RedFlag = False
            Me.btn.BackColor = Color.Lime
            Me.alarmOn = False
            ' rec = tr.Text
            GetSensorsName = Me.btn.Text
        End If
    End Sub

'in my form

Public Class Form1

    Public md(NumberOfSensors) As md          '>>>>>>  NumberOfSensors is a public integer variable 
    Public fbtn(NumberOfSensors) As Button
    Public snoozeIconBtn(NumberOfSensors) As Button
    Public lbl(NumberOfSensors) As Label
    Public Picturebox(NumberOfSensors) As PictureBox
    Public state(NumberOfSensors) As Label
    Public tooltip(NumberOfSensors) As ToolTip
    Public hover(NumberOfSensors) As Label
    Public sensor(NumberOfSensors) As String
    Public act(NumberOfSensors) As Label
   

 Private Sub initMdArray()   'this sub is set to form load event
              For j = 0 To NumberOfSensors - 1
'here i initiallize also the other controls
            btn(j) = Me.fbtn(j + 1)

            md(j) = New md(j)
        Next        
    End Sub


'form1 create buttons

For i As Integer = 0 To Rcount - 1

            Button.Name = "Button" & i + 1
            Button.Text = ds.Tables(0).Rows(i).Item(1)
            Button.Dock = DockStyle.Fill
            Button.FlatStyle = FlatStyle.Flat
            Button.Cursor = Cursors.Hand
            Button.BackColor = Color.White
                        fbtn(i) = Button      '<<<<<< is this correct   ??????
            dynamicTableLayoutPanel.Controls.Add(Button, 0, i)

Open in new window

Avatar of John (Yiannis) Toutountzoglou
John (Yiannis) Toutountzoglou
Flag of Greece image

ASKER

Sorry i forgot to say that somewhere in my form1 i call the function setAlarm in a loop

md(i).SetAlarm(true)
Avatar of Nasir Razzaq
I am not sure if I understand this correctly but are you saying that

Me.btn = Form1.fbtn(i)

does assign a valid button reference to Me.btn?
exactly...
in a previous version i got 8 buttons
and the declaration in form1 was like this:
Public fbtn(8) As Button


Private Sub initMdArray()
       
       fbtn(0) = Me.fbtn1
       fbtn(1) = Me.fbtn2
       fbtn(2) = Me.fbtn3  'and so on



     For j = 0 To 7
          md(j) = New motionDetector(j)
        Next    
end sub

Open in new window

Is this code AFTER the call to create an MD instance? If so move it to BEFORE that code.

For i As Integer = 0 To Rcount - 1

            Button.Name = "Button" & i + 1
            Button.Text = ds.Tables(0).Rows(i).Item(1)
            Button.Dock = DockStyle.Fill
            Button.FlatStyle = FlatStyle.Flat
            Button.Cursor = Cursors.Hand
            Button.BackColor = Color.White
                        fbtn(i) = Button      '<<<<<< is this correct   ??????
            dynamicTableLayoutPanel.Controls.Add(Button, 0, i)


Also, try changing it to

For i As Integer = 0 To Rcount - 1
            Dim btn As New Button
            btn.Name = "Button" & i + 1
            btn.Text = ds.Tables(0).Rows(i).Item(1)
            btn.Dock = DockStyle.Fill
            btn.FlatStyle = FlatStyle.Flat
            btn.Cursor = Cursors.Hand
            btn.BackColor = Color.White
            fbtn(i) = btn
            dynamicTableLayoutPanel.Controls.Add(btn, 0, i)
Next
thank you for your reply codecruiser...
nothing happened...
the problem should be in the

Private Sub initMdArray()   'this sub is set to form load event
              For j = 0 To NumberOfSensors - 1
'here i initiallize also the other controls
            btn(j) = Me.fbtn(j + 1)

            md(j) = New md(j)
        Next        
    End Sub
becuase there is no call of initMdArray the programm runs but without the functionallity of the md class

Ok. I think I am lost now. What does this program actually do?
it is an alarm program.
if have a controller with 8 sockets .i am receiving a string from each socket .each socket transimts 0 and 1...so
the string if all sockets are active normally is "00000000" ..
what i'va done in the previous version is to compare with a background worker every second this string.
its  position of the string matches to a button .
everytime a certan string position goes from  "0"  to "1" (alarm signal) the button goes to Red until the 1 goes to 0 again..
now what i want to now is limit the sockets..
not 8 which is the maximum but depending on users need..form 1 to 8..
So accordind a variable i create such number of buttons according to this.
previous version works fine...
but now i do not know how to match the btn=form1.fbtn(i) from the calss with the created button in the form1
Paste the whole code from both the MD class and the form1.

Try passing the button as parameter to New in MD class instead of an index.
the code in form1 is a little bit mess ..
there is a logic in the declaration...
i stuck...!!
here is my code...
Public Class motionDetector
    Public state As String
    Public snoozeIconBtn As Button
    Public lbl As Label
    Public pb As PictureBox
    Public stateLbl As Label
    Public tooltip As ToolTip
    Public hover As Label
    Public c As Integer
    Public sch(40) As timeSpan
    Public sch_count As Integer
    Public name As String
    Public active As Boolean
    Public alarmOn As Boolean
    Public attentionOn As Boolean
    Public Sensor As String
    Public GetSensorsName As String
    Public tr As Label
    Public rec As String
    Public btn As Button
    Private RedFlag As Boolean
    'public readonly property

    
    Public Sub New(ByVal i As Integer)

        Me.btn = Form1.fbtn(i)
        Me.lbl = Form1.lbl(i)
        Me.stateLbl = Form1.state(i)
        Me.tooltip = Form1.tooltip(i)
        Me.hover = Form1.hover(i)
        Me.c = i
        Me.sch_count = 0
        Me.snoozeIconBtn = Form1.snoozeIconBtn(i)
        Me.pb = Form1.Picturebox(i)
        Me.Sensor = Form1.sensor(i)
        Me.tr = Form1.act(i)
    End Sub
    Public Sub snooze()
        If Me.attentionOn Then
            setAlarm(False)
            setReminder(False)
            Dim now As Date = Date.Now
        Else
            Dim response As MsgBoxResult
            response = MsgBox("Extend arm period for 15 minutes?", 4, "Confirmation Needed")
            If response = MsgBoxResult.Yes Then
                extendTimeSpan(Me.getCurrentTimeSpan(), 15)
            End If
        End If
    End Sub
    Public Sub extendTimeSpan(ByVal ts As timeSpan, ByVal min As Integer)
        '   ts.endTime.AddMinutes(min)
        'Me.sch(ts.order + 1).startTime.AddMinutes(min)
    End Sub
    
    Public Sub setAlarm(ByVal val As Boolean)
        If val = True Then
            RedFlag = True
            Me.btn.BackColor = Color.Red
            Me.alarmOn = True
            ' rec = tr.Text
            GetSensorsName = Me.btn.Text
        Else
            RedFlag = False
            Me.btn.BackColor = Color.Lime
            Me.alarmOn = False
            ' rec = tr.Text
            GetSensorsName = Me.btn.Text
        End If
    End Sub
    Public Sub setNotificationAlarm(ByVal val As Boolean)
        If val = True Then
            RedFlag = True
            Me.btn.BackColor = Color.Red
            Me.alarmOn = True
            rec = tr.Text
            GetSensorsName = Me.btn.Text
        Else
            RedFlag = False
            Me.btn.BackColor = Color.Yellow
            Me.alarmOn = False
            rec = tr.Text
            GetSensorsName = Me.btn.Text
        End If
    End Sub
    Public Sub setOffAlarm(ByVal val As Boolean)
        If val = True Then
            RedFlag = True
            Me.btn.BackColor = Color.Red
            Me.alarmOn = True
            rec = tr.Text
            GetSensorsName = Me.btn.Text
        Else
            RedFlag = False
            Me.btn.BackColor = Color.White
            Me.alarmOn = False
            rec = tr.Text
            GetSensorsName = Me.btn.Text
        End If
    End Sub
   
    Public Sub SetAlarmIcon(ByVal val As Boolean)
        If val = True Then
            ' pb.BackgroundImage
            pb.Image = My.Resources.Resource1.Alert
        Else
            pb.Image = Nothing
        End If
    End Sub
    Public Sub SetTrueFalse(ByVal Val As Boolean)
        If Val = True Then
            snoozeIconBtn.Enabled = True
        Else
            snoozeIconBtn.Enabled = False
        End If
    End Sub
    Public Sub ActTrueFalse(ByVal Val As Boolean)
        If Val = True Then
            tr.Text = "Activated"
        Else
            tr.Text = "De-Activated"
        End If
    End Sub

    Public Sub setReminder(ByVal val As Boolean)
        Me.attentionOn = val
        If val = True Then
            Me.lbl.BackColor = Color.LightCoral
        Else
            Me.lbl.BackColor = SystemColors.Control
        End If
    End Sub
    Public Sub setNotification(ByVal val As Boolean)
        If val = True Then
            Form1.fireNotification()
        End If
    End Sub
    Function findBelongingTimeSpan(ByVal checkDate As Date) As timeSpan
        'given 
        Dim checkStart As Date
        Dim checkEnd As Date
        Dim retvalue As timeSpan

        Dim j As Integer
        For j = 0 To Me.sch_count - 1
            checkStart = Me.sch(j).startTimeComparable()
            checkEnd = Me.sch(j).endTimeComparable()

            If ((DateTime.Compare(checkStart, checkDate) = -1 Or DateTime.Compare(checkStart, checkDate) = 0) And DateTime.Compare(checkEnd, checkDate) = 1) Then
                Me.state = Me.sch(j).type
                retvalue = Me.sch(j)

                'Me.stateLbl.Text = Me.state

                'Console.WriteLine(Me.state & Me.name)
                Exit For
            End If
            'Console.WriteLine(checkDateString1 & " compare " & nowDate & ":::" & DateTime.Compare(checkDate1, nowDate))
            'Dim timeDiff As TimeSpan = nowDate.Subtract(checkDate)
        Next
        'If (retvalue) Then
        '    Return retvalue
        'Else
        '    Return False
        'End If
        Return retvalue

    End Function

    Function getCurrentTimeSpan() As timeSpan
        Dim nowDate As Date = Date.Now
        Dim retvalue As timeSpan

        retvalue = findBelongingTimeSpan(nowDate)
        Return retvalue

    End Function

    Function printSchedule() As String
        Dim i As Integer
        Dim schText As String

        schText = "SCHEDULE for " & Me.name & ControlChars.NewLine & "------------------"
        'Me.tooltip.SetToolTip(Me.hover, "ss")


        Console.WriteLine("SCHEDULE for " & Me.name)
        Console.WriteLine("-----------------------")
        For i = 0 To sch_count - 1
            Console.WriteLine(sch(i).order & ")" & sch(i).startTime.ToString("HH:mm:ss") & " - " & sch(i).endTime.ToString("HH:mm:ss") & " /// " & sch(i).type & "|")
            schText = schText & ControlChars.NewLine & sch(i).order & ")" & sch(i).startTime.ToString("HH:mm:ss") & " - " & sch(i).endTime.ToString("HH:mm:ss") & " /// " & ControlChars.Tab & sch(i).type & "|"
        Next
        'Me.tooltip.SetToolTip(Me.hover, schText)
        Console.WriteLine("-----------------------")
        Return schText
    End Function

    'CLASS TIME SPAN-------------------------------------------------------------------------------
    Public Class timeSpan
        Public startTime As Date
        Public endTime As Date
        Public type As String
        Private parent As motionDetector
        Public order As Integer


        'Public Sub New(ByVal s As Date, ByVal e As Date, ByVal type As String, ByVal parent As motionDetector)

        Function getColor()
            Dim tempColor As Color
            If Me.type = "arm" Then
                tempColor = Color.Red
            ElseIf Me.type = "notify" Then
                tempColor = Color.Yellow
            ElseIf Me.type = "idle" Then
                tempColor = Color.Green
            End If
            Return tempColor
        End Function
        Function getHoverColor()
            Dim tempColor As Color
            If Me.type = "arm" Then
                tempColor = Color.DarkRed
            ElseIf Me.type = "notify" Then
                tempColor = Color.DarkOrange
            ElseIf Me.type = "idle" Then
                tempColor = Color.DarkGray
            End If
            Return tempColor
        End Function
        Function startTimeComparable() As Date
            Dim nowDate As Date = Date.Now
            Dim checkDateString1 As String
            Dim checkDate1 As Date
            checkDateString1 = nowDate.ToString("yyyy-MM-dd") + " " + Me.startTime.ToString("HH:mm:ss")
            checkDate1 = DateTime.ParseExact(checkDateString1, "yyyy-MM-dd HH:mm:ss", Nothing).AddSeconds(1) 'adding this second giati mou spaei ta neura...to 00:00:00 otan ginetai parse hanetai san wra
            Return checkDate1
        End Function

        Function endTimeComparable() As Date
            Dim nowDate As Date = Date.Now
            Dim checkDateString1 As String
            Dim checkDate1 As Date
            checkDateString1 = nowDate.ToString("yyyy-MM-dd") + " " + Me.endTime.ToString("HH:mm:ss")
            checkDate1 = DateTime.ParseExact(checkDateString1, "yyyy-MM-dd HH:mm:ss", Nothing).AddSeconds(1) 'adding this second giati mou spaei ta neura...to 00:00:00 otan ginetai parse hanetai san wra
            Return checkDate1
        End Function
    End Class
End Class


Imports System
Imports System.Net.Sockets
Imports System.Text.Encoding
Imports System.Text
Imports System.Net
Imports System.Threading
Imports System.IO
Imports System.Diagnostics
Imports System.Xml

Public Class Form1

    Public md(NumberOfSensors) As motionDetector
    Public fbtn(NumberOfSensors) As Button
    Public snoozeIconBtn(NumberOfSensors) As Button
    Public lbl(NumberOfSensors) As Label
    Public Picturebox(NumberOfSensors) As PictureBox
    Public state(NumberOfSensors) As Label
    Public tooltip(NumberOfSensors) As ToolTip
    Public hover(NumberOfSensors) As Label
    Public sensor(NumberOfSensors) As String
    Public act(NumberOfSensors) As Label
    Public btn As New Button

    'Public alarm As MyAlarm
    Public AAA As Integer = 1
    Public ALARM As Boolean = True
    Public networkStream2 As NetworkStream
    Public tcpClient2 As New TcpClient()

    Public Event SaveWhileClosingCancelled As System.EventHandler
    Public Event ExitApplication As System.EventHandler
    Private dirtyValue As Boolean = False
    Private closingCompleteValue As Boolean = False
    Private documentNameValue As String
    Private fileNameValue As String




    Dim remoteIPAddress As IPAddress
    Dim ep As IPEndPoint
    Dim tnSocket As Socket
    Public ReadOnly Property ClosingComplete() As Boolean
        Get
            Return closingCompleteValue
        End Get
    End Property

    Public ReadOnly Property DocumentName() As String
        Get
            Return documentNameValue
        End Get
    End Property

    Private Sub initMdArray()
       
        '  snoozeIconBtn(0) = Me.snoozeIconBtn1
        '  snoozeIconBtn(1) = Me.snoozeIconBtn2
        '  snoozeIconBtn(2) = Me.snoozeIconBtn3
        ' snoozeIconBtn(3) = Me.snoozeIconBtn4
        ' snoozeIconBtn(4) = Me.snoozeIconBtn5
        ' snoozeIconBtn(5) = Me.snoozeIconBtn6
        ' snoozeIconBtn(6) = Me.snoozeIconBtn7
        ' snoozeIconBtn(7) = Me.snoozeIconBtn8

        '        lbl(0) = Me.Label1
        '        lbl(1) = Me.Label2
        '        lbl(2) = Me.Label3
        '        lbl(3) = Me.Label4
        '        lbl(4) = Me.Label5
        '        lbl(5) = Me.Label6
        '        lbl(6) = Me.Label7
        '        lbl(7) = Me.Label8

        '        state(0) = Me.state1
        '        state(1) = Me.state2
        '        state(2) = Me.state3
        '        state(3) = Me.state4
        '        state(4) = Me.state5
        '        state(5) = Me.state6
        '        state(6) = Me.state7
        '        state(7) = Me.state8

        tooltip(0) = Me.ToolTip1
        tooltip(1) = Me.ToolTip2
        tooltip(2) = Me.ToolTip3
        tooltip(3) = Me.ToolTip4
        tooltip(4) = Me.ToolTip5
        tooltip(5) = Me.ToolTip6
        tooltip(6) = Me.ToolTip7
        tooltip(7) = Me.ToolTip8

        '        Me.snoozeIconBtn1.Enabled = False
        '        Me.snoozeIconBtn2.Enabled = False
        '        Me.snoozeIconBtn3.Enabled = False
        '        Me.snoozeIconBtn4.Enabled = False
        '        Me.snoozeIconBtn5.Enabled = False
        '        Me.snoozeIconBtn6.Enabled = False
        '        Me.snoozeIconBtn7.Enabled = False
        '        Me.snoozeIconBtn8.Enabled = False

        '        Picturebox(0) = Me.PictureBox1
        '        Picturebox(1) = Me.PictureBox2
        '        Picturebox(2) = Me.PictureBox3
        '        Picturebox(3) = Me.PictureBox4
        '        Picturebox(4) = Me.PictureBox5
        '        Picturebox(5) = Me.PictureBox6
        '        Picturebox(6) = Me.PictureBox7
        '        Picturebox(7) = Me.PictureBox8

        '        act(0) = Me.activated1
        '        act(1) = Me.activated2
        '        act(2) = Me.activated3
        '        act(3) = Me.activated4
        '        act(4) = Me.activated5
        '        act(5) = Me.activated6
        '        act(6) = Me.activated7
        '        act(7) = Me.activated8

        For j = 0 To NumberOfSensors - 1

            fbtn(j) = Me.fbtn(j + 1)
            md(j) = New motionDetector(j)

        Next



        '  hover(0) = Me.hover1
        '  hover(1) = Me.hover2
        '  hover(2) = Me.hover3
        '  hover(3) = Me.hover4
        '  hover(4) = Me.hover5
        '  hover(5) = Me.hover6
        '  hover(6) = Me.hover7
        '  hover(7) = Me.hover8


       

        
    End Sub


    Private RecvString As String = String.Empty
    Private StatusString As String

    Private Sub Wait(ByVal PMillseconds As Integer)
        ' Function created to replace thread.sleep()
        ' Provides responsive main form without using threading.

        Dim TimeNow As DateTime
        Dim TimeEnd As DateTime
        Dim StopFlag As Boolean

        TimeEnd = Now()
        TimeEnd = TimeEnd.AddMilliseconds(PMillseconds)
        StopFlag = False
        While Not StopFlag
            TimeNow = Now()
            If TimeNow > TimeEnd Then
                StopFlag = True
            End If
            Application.DoEvents()
        End While

        ' Cleanup
        TimeNow = Nothing
        TimeEnd = Nothing
    End Sub
    Private Sub ExitApllicationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitApllicationToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private _flash As Boolean = False
    Private Sub PreAlarmFlashLabel(ByVal btn As Button, ByVal pb As PictureBox, ByVal txt As String)
        Dim _color As Color = Color.White
        If _flash = True Then
            If btn.BackColor.Equals(_color) Then
                btn.BackColor = Color.Red
                btn.Text = "ALARM"
                LoopSound()
                pb.Visible = True
                pb.Image = Image.FromFile("C:\Documents and Settings\G¿¿F¿¿¿ ¿¿¿¿¿¿¿¿S¿S\¿a ¿¿¿¿af¿ µ¿¿\Visual Studio 2008\Projects\AlarmTest1\AlarmTest1\Resources\Alert.png")
            Else
                btn.BackColor = _color
                btn.Text.DefaultIfEmpty()
                pb.Visible = False
                btn.Text = txt
            End If

        End If
    End Sub
    Private Sub SnoozeFlash(ByVal btn As Button, ByVal pb As PictureBox, ByVal txt As String, ByVal lbl As Label)
        btn.BackColor = Color.White
        pb.Visible = False
        Timer2.Stop()
        Timer2.Enabled = False
        Timer3.Enabled = False
        lbl.Text = ""
    End Sub
    Private ReceiveSensorsName As String
    ' totalTime As TimeSpan
    Private SF As IO.UnmanagedMemoryStream = My.Resources.Resource1.Siren
    Private SF2 As IO.UnmanagedMemoryStream = My.Resources.Resource1.alarm1
    Private AD As New Microsoft.VisualBasic.Devices.Audio, Cancel As Boolean = True

    Private Sub LoopSound()
        AD.Play(SF, AudioPlayMode.Background) : SF.Position = 0
    End Sub
    Private Sub LoopSound2()
        AD.Play(SF2, AudioPlayMode.Background) : SF.Position = 1
    End Sub



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

        MessageBox.Show("connected" & tcpClient.Connected)
        Dim xmlFile As XmlReader
        xmlFile = XmlReader.Create("C:\Sensors.xml", New XmlReaderSettings())
        Dim ds As New DataSet
        ds.ReadXml(xmlFile)
        Dim Rcount As Integer = ds.Tables(0).Rows.Count

        Dim dynamicTableLayoutPanel As New TableLayoutPanel()

        dynamicTableLayoutPanel.Location = New System.Drawing.Point(26, 12)
        dynamicTableLayoutPanel.Name = "TableLayoutPanel1"
        dynamicTableLayoutPanel.Dock = DockStyle.Top
        ' dynamicTableLayoutPanel.BackColor = Color.Gray
        dynamicTableLayoutPanel.CellBorderStyle = TableLayoutPanelCellBorderStyle.OutsetDouble
        dynamicTableLayoutPanel.ColumnCount = 4

        dynamicTableLayoutPanel.ColumnStyles.Add(New ColumnStyle(SizeType.Absolute, 250.0F))
        For j As Integer = 0 To dynamicTableLayoutPanel.ColumnCount - 1
            dynamicTableLayoutPanel.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 50.0F))
        Next

        For i As Integer = 0 To NumberOfSensors - 1

            dynamicTableLayoutPanel.RowStyles.Add(New RowStyle(SizeType.Percent, (Me.SplitContainer6.Panel1.Height / 8)))
            dynamicTableLayoutPanel.Height = (Me.SplitContainer6.Panel1.Height / 8) * Rcount
        Next

        For i As Integer = 0 To NumberOfSensors - 1

            '  btn.Name = "Button" & i + 1
            btn.Text = ds.Tables(0).Rows(i).Item(1)
            btn.Dock = DockStyle.Fill
            btn.FlatStyle = FlatStyle.Flat
            btn.Cursor = Cursors.Hand
            btn.BackColor = Color.White

            dynamicTableLayoutPanel.Controls.Add(btn, 0, i)

            AddHandler btn.MouseEnter, AddressOf MyFunctionToTriggeronmouseover
            AddHandler btn.MouseLeave, AddressOf MyFunctionToTriggeronmouseleave
            AddHandler btn.MouseDown, AddressOf MyFunctionToTriggeronmousedown
            AddHandler btn.MouseUp, AddressOf MyFunctionToTriggeronmouseup

            dynamicTableLayoutPanel.Controls.Add(btn, 0, i)

            'fbtn(i).Name = button.Name
            xmlFile.Close()

            Dim SnBtn As New Button()
            SnBtn.Name = "SnoozeButton" & i + 1
            SnBtn.Dock = DockStyle.Fill
            SnBtn.Cursor = Cursors.Hand
            SnBtn.Image = My.Resources.snooze
            SnBtn.BackColor = Color.Transparent
            dynamicTableLayoutPanel.Controls.Add(SnBtn, 1, i)




        Next
        Me.SplitContainer6.Panel1.Controls.Add(dynamicTableLayoutPanel)
        initMdArray()
        Dim dgvthread As New Threading.Thread(AddressOf dgvThreadMain)
        dgvthread.Priority = ThreadPriority.Highest
        dgvthread.IsBackground = True
        dgvthread.Start()


        ' readSettings()


        BackgroundWorker1.RunWorkerAsync()

        '  Catch ex As Exception
        'MessageBox.Show("malaka" & " " & ex.Message)
        '   End Try


        Me.Text = "User :" & Uname & " - Alarm Status :" & SelectedStatus
        Me.ToolStripStatusLabel2.Text = "Alarm Status: " & SelectedStatus
    End Sub

    Private Sub readSettings()
        Dim f As String
        Dim delim As Char
        Dim toreadnext As Integer
        Dim i As Integer

        delim = ";"
        f = "C:\motionDetectors.txt"

        Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(f)
            MyReader.TextFieldType = FileIO.FieldType.Delimited
            MyReader.SetDelimiters(delim)
            Dim currentRow As String()
            While Not MyReader.EndOfData
                Try
                    currentRow = MyReader.ReadFields()
                    Console.WriteLine(currentRow(0))
                    If currentRow(0) = "###" Then
                        toreadnext = 1
                    ElseIf toreadnext = 1 Then
                        'read the number of the md
                        i = currentRow(0) - 1
                        toreadnext = 2
                    ElseIf toreadnext = 2 Then
                        'read if active or not
                        If currentRow(0) = 1 Then
                            md(i).active = True
                            toreadnext = 3
                        Else
                            md(i).active = False
                            md(i).btn.Text = "Disabled"
                            md(i).btn.Enabled = False
                            md(i).lbl.Enabled = False
                            'md(i).bar.Enabled = False
                            toreadnext = -1
                        End If
                    ElseIf toreadnext = 3 Then
                        'read md name
                        md(i).name = currentRow(0)
                        md(i).btn.Text = md(i).name
                        toreadnext = 4
                    Else
                        'read time span
                        Console.WriteLine(currentRow(0) & "," & currentRow(1) & "," & currentRow(2))
                        '  md(i).addTimeSpan(currentRow(0), currentRow(1), currentRow(2))
                    End If

                Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                    MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
                End Try
            End While
        End Using
    End Sub
    Private Sub checkData(ByVal data)
        Dim i As Integer
        Dim motionDetected As Integer
        For i = 0 To 7
            motionDetected = Val(data(i))
            'remember to delete this DOWN
            '   If motionDetected = 1 Then
            'motionDetected = 0
            '   Else
            '   motionDetected = 1
            '   End If
            'remember to delete this UP

            If motionDetected = 1 Then
                If (md(i).active) Then
                    If (md(i).getCurrentTimeSpan().type = "arm") Then
                        md(i).setAlarm(True)
                        md(i).setReminder(True)
                    ElseIf (md(i).getCurrentTimeSpan().type = "notify") Then
                        md(i).setNotification(True)
                        fireNotification()
                    End If
                End If
            Else
                md(i).setAlarm(False)
            End If
        Next
    End Sub

    Private Sub AlarmLabel(ByVal btn As Button, ByVal pb As PictureBox)
        Dim _color As Color = Color.Red
        btn.BackColor = _color
        btn.Text = "ALARM"
        pb.Image = Nothing
        pb.Visible = True
        pb.Image = Image.FromFile("C:\Documents and Settings\G¿¿F¿¿¿ ¿¿¿¿¿¿¿¿S¿S\¿a ¿¿¿¿af¿ µ¿¿\Visual Studio 2008\Projects\AlarmTest1\AlarmTest1\Resources\Alert2.png")
        LoopSound()
    End Sub

    Private Sub ResetStatus(ByVal btn As Button, ByVal pb As PictureBox, ByVal txt As String)
        AD.Stop()
        pb.Visible = False
        btn.BackColor = Color.White
    End Sub
    Delegate Sub dgvDelegate()
    Delegate Sub dgvDelegate2()
    Delegate Sub SaveText()
    Private Sub dgvThreadMain()
        If Me.InvokeRequired Then
            Me.Invoke(New dgvDelegate(AddressOf updateDgv))
        End If
    End Sub
    Private Sub dgvThreadMain2()
        If Me.InvokeRequired Then
            Me.Invoke(New dgvDelegate2(AddressOf ClearDgvRows))
        End If
    End Sub
    Private Sub dgvThreadMain3()
        If Me.InvokeRequired Then
            Me.Invoke(New dgvDelegate2(AddressOf SaveToText))
        End If
    End Sub
    Private Sub SaveToText()
        SaveToTextFile("Activity", RecordDatagridView)
    End Sub
    Private Sub updateDgv()
        Dim row0 As String() = {Date.Now.ToShortDateString, Date.Now.ToString("HH:mm:ss"), variable, variable1, variable2, variable3}
        Me.RecordDatagridView.Rows.Add(row0)
    End Sub
    Private Sub ClearDgvRows()
        Me.RecordDatagridView.Rows.Clear()
    End Sub
    Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
        Me.Close()
    End Sub
    Private variable, variable1, variable2, variable3 As String
    Private Delegate Sub SetTextBoxTextDelegate(ByVal text As String)
    Private Delegate Sub SetTextBoxBackColorDelegate(ByVal Clr As Color)
    Private Delegate Sub SetToolStripTextDelegate(ByVal text As String)
    Private Delegate Sub SetSnoozeEnablty(ByVal val As Boolean)
    Private Delegate Sub ActivateTextDelegate(ByVal val As Boolean)
    Private Delegate Sub Dgv(ByVal dgv As DataGridView)


    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        dgvThreadMain2()
        Dim LastDataReceived As String = String.Empty

        Try

            networkStream = tcpClient.GetStream
            While networkStream.CanRead
                Dim myReadBuffer(50) As Byte
                Dim bufferSize As Integer = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length)
                Dim dataReceived As String = System.Text.Encoding.ASCII.GetString(myReadBuffer)
                Console.WriteLine(dataReceived)
                ToolStripStatusLabel3.Text = "Receiving Data From Controller :" & tcpClient.Connected.ToString
                If LastDataReceived = String.Empty Then
                    LastDataReceived = dataReceived
                    checkData(dataReceived, LastDataReceived)

                ElseIf LastDataReceived.Equals(dataReceived) = False Then
                    checkData(dataReceived, LastDataReceived)
                    LastDataReceived = dataReceived
                End If
            End While

        Catch oEx As SocketException
            MessageBox.Show("pousti" & oEx.Message)
        Catch ioEx As IO.IOException
            Me.Invoke(New SetToolStripTextDelegate(AddressOf SetToolStripText), "Receiving Data From Controller :" & tcpClient.Connected.ToString)
            Me.Invoke(New SetTextBoxBackColorDelegate(AddressOf SetBackColor), Color.Red)
            MessageBox.Show(ioEx.Message, "Communication Problem With The Controller", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning)
        End Try

    End Sub
    Public Sub fireNotification()
        Dim i As Integer
        Console.WriteLine("FIRE " & Me.AAA)
        If Me.AAA = 1 Then
            Console.WriteLine("BEEP")
            Me.AAA = 0
            Me.notifyTimer.Enabled = True
            For i = 1 To 5
                Beep()
            Next
        End If
    End Sub
    Private Sub SetToolStripText(ByVal text As String)
        Me.ToolStripStatusLabel3.Text = text
    End Sub
    Private Sub activatedText(ByVal text As String)
        Me.ToolStripStatusLabel3.Text = text
    End Sub
    Private Sub SetBackColor(ByVal Clr As Color)
        Me.ToolStripStatusLabel3.BackColor = Clr
    End Sub
    Private Function CheckData(ByVal CheckString As String, ByVal LastDataString As String)
        Dim i As Integer
        Dim bSet As Boolean

        For i = 0 To CheckString.Length - 1
            Select Case CheckString.Substring(i, 1)
                Case "1"
                    bSet = True

                    md(i).setAlarm(bSet)
                    '  md(i).SetAlarmIcon(bSet)
                    ReceiveSensorsName = md(i).GetSensorsName
                    'Me.Invoke(New SetSnoozeEnablty(AddressOf md(i).SetTrueFalse), bSet)
                    'Me.Invoke(New ActivateTextDelegate(AddressOf md(i).ActTrueFalse), bSet)
                    StatusString = "Activated"
                    If LastDataString.Substring(i, 1) = "0" Then
                        variable1 = ReceiveSensorsName
                        variable2 = StatusString
                        dgvThreadMain()
                        SaveToText()
                    End If
                Case "0"
                    bSet = False
                    md(i).setAlarm(bSet)
                    ' md(i).SetAlarmIcon(bSet)
                    ReceiveSensorsName = md(i).GetSensorsName
                    'Me.Invoke(New SetSnoozeEnablty(AddressOf md(i).SetTrueFalse), bSet)
                    'Me.Invoke(New ActivateTextDelegate(AddressOf md(i).ActTrueFalse), bSet)
                    StatusString = "De-Activated"
                    If LastDataString.Substring(i, 1) = "1" Then
                        variable1 = ReceiveSensorsName
                        variable2 = StatusString
                        dgvThreadMain()
                        SaveToText()
                    End If
            End Select
        Next

        Return CheckString


    End Function

    Private Sub Button11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button11.Click
        If iAdmin = False Then
            MessageBox.Show("¿e¿ ¿¿ete ta apa¿a¿t¿ta d¿¿a¿¿µata ¿¿a t¿¿ e¿¿¿¿e¿a a¿t¿", "Administrator only", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Exit Sub
        End If
    End Sub

    Private Sub RecordDatagridView_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles RecordDatagridView.CellFormatting

        If e.Value = "Activated" Then
            Me.RecordDatagridView.Rows(e.RowIndex).Cells(4).Style.BackColor = Color.Red
        ElseIf e.Value = "De-Activated" Then
            Me.RecordDatagridView.Rows(e.RowIndex).Cells(4).Style.BackColor = Color.Lime

        End If

    End Sub
    Private Sub SaveToTextFile(ByRef Fname As String, ByVal RecordDatagridView As DataGridView)
        Dim i As Integer
        Dim j As Integer
        Dim cellvalue$
        Dim rowLine As String = ""

        Try
            Fname = Fname & "(" & Date.Now.ToString("dd-MM-yy") & ").txt"
            FileOpen(1, Fname, OpenMode.Append)
            For j = 0 To RecordDatagridView.Rows.Count - 2
                For i = 0 To RecordDatagridView.Columns.Count - 1
                    If Not TypeOf RecordDatagridView.Item(i, j).Value Is DBNull Then
                        cellvalue = RecordDatagridView.Item(i, j).Value
                    Else
                        cellvalue = ""
                    End If
                    rowLine = rowLine + " " & cellvalue + ","
                Next
                rowLine = rowLine.Remove(rowLine.Length - 1, 1)
                WriteLine(1, rowLine)
                rowLine = ""
            Next
            FileClose(1)

        Catch ex As Exception
            MessageBox.Show("Error occured while writng to the file." + ex.ToString())
        Finally
            FileClose(1)
        End Try
    End Sub

    Private Sub DailyLogToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DailyLogToolStripMenuItem.Click
        Try
            Dim Opendirectory As New OpenFileDialog
            Dim file_name As String = "C:\Documents and Settings\G¿¿F¿¿¿ ¿¿¿¿¿¿¿¿S¿S\¿a ¿¿¿¿af¿ µ¿¿\Visual Studio 2008\Projects\AlarmTest1\AlarmTest1\bin\Debug\"
            With Opendirectory
                .InitialDirectory = file_name
                .Filter = "Text Files|*.txt"
                .FilterIndex = 1
                If .ShowDialog = Windows.Forms.DialogResult.OK Then
                    Process.Start(Opendirectory.FileName)
                End If
            End With
        Catch ex As Exception
        End Try
    End Sub

    Private Sub cmdSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSend.Click

    End Sub
    Private WithEvents obj As Form
    Private Sub CreateUserToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CreateUserToolStripMenuItem.Click
        If obj Is Nothing Then
            obj = New Users
        End If

        obj.StartPosition = FormStartPosition.CenterScreen
        obj.ShowDialog()

    End Sub

    Private Sub ManageUsersToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManageUsersToolStripMenuItem.Click
        If obj Is Nothing Then
            obj = New ManageUsers
        End If

        obj.StartPosition = FormStartPosition.CenterScreen
        obj.ShowDialog()
    End Sub

    Private Sub obj_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles obj.FormClosing
        obj = Nothing
    End Sub
    Public Sub MyFunctionToTriggeronmouseover(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Dim ButtonControl As Button = sender

        'Changes the color of the buttons to blue when the mouse is over it' 

        ButtonControl.BackColor = Color.LightGreen
    End Sub

    Public Sub MyFunctionToTriggeronmouseleave(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Dim ButtonControl As Button = sender

        'Changes the color back to red when the mouse leaves.' 

        ButtonControl.BackColor = Color.White

    End Sub
    Public Sub MyFunctionToTriggeronmousedown(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Dim ButtonControl As Button = sender

        'Changes the color to green when mouse goes down.' 

        ButtonControl.BackColor = Color.Green

    End Sub
    Public Sub MyFunctionToTriggeronmouseup(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Dim ButtonControl As Button = sender

        'Changes the color to red when the mouse goes up' 

        ButtonControl.BackColor = Color.White

    End Sub
End Class

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>1) You are adding the same btn again and again to the array...
codecruiser this was the problem...
thank you !!
glad to help :-)