|
I tried the following way as well as yours on the Visible property of an inherited label but yet it stays True in the properties grid when compiled and dragged in the IDE. I need to change it manually to take effect.
Imports System.ComponentModel
Public Class MyLabel
Inherits Label
Public Sub New()
MyBase.New()
InitializeComponent()
End Sub
<DefaultValue(False)> _
Public Shadows Property Visible As Boolean
Get
Return MyBase.Visible
End Get
Set(ByVal value As Boolean)
MyBase.Visible = value
End Set
End Property
End Class
Another point is, I tried both ways on the AutoSize property too, with the default value of False. In that case though, in the properties grid, it was showing False but actually the property remains True, as that's what I can see while executing. In order to set the value to False, I need to set it to True and then back to False again.
|
|
|
|
|
You just need to set the relevant properties in the constructor of you custom control like this:-
Public Class MyDataGridView
Inherits DataGridView
Public Sub New()
InitializeComponent()
AllowUserToAddRows = False
AllowUserToDeleteRows = False
End Sub
End Class
When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman
|
|
|
|
|
Hello,
- I am using DirectShowLib to acquire video from laptop camera and it can work well.
- I am trying to adjust the brightness by using the software but it does not work.
- As I move the track bar (tbBrightness), I want to change the brightness but it does not change.
The codes are as below :
Imports DirectShowLib
Imports System.Runtime.InteropServices.ComTypes
Private Sub GetSettings()
Try
Dim capDevices As DsDevice() = Nothing
Dim CamDevice As DsDevice = Nothing
Dim CamFilter As IBaseFilter = Nothing
Dim CamControl As IAMCameraControl = Nothing
Dim graphBuilder As IFilterGraph2 = CType(New FilterGraph, IFilterGraph2)
Dim nMin As Long = 0
Dim nMax As Long = 0
Dim nStep As Long = 0
Dim nDefault As Long = 0
Dim nFlags As Long = 0
Dim hr As Int64 = 0
capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice)
CamDevice = capDevices(0)
If (CamDevice.Name = String.Empty) Then
MsgBox("No video capture devices found!", MsgBoxStyle.OkOnly)
Exit Sub
End If
hr = graphBuilder.AddSourceFilterForMoniker(CamDevice.Mon, Nothing, CamDevice.Name, CamFilter)
CamControl = CType(CamFilter, IAMCameraControl)
hr = CamControl.GetRange(VideoProcAmpProperty.Brightness, nMin, nMax, nStep, nDefault, nFlags)
Me.tbBrightness.Minimum = nMin
Me.tbBrightness.Maximum = nMax
Me.tbBrightness.SmallChange = nStep
Me.tbBrightness.Value = nDefault
Catch ex As Exception
End Try
End Sub
Private Sub tbBrightness_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbBrightness.Scroll
Try
Dim capDevices As DsDevice() = Nothing
Dim CamDevice As DsDevice = Nothing
Dim CamFilter As IBaseFilter = Nothing
Dim CamControl As IAMCameraControl = Nothing
Dim graphBuilder As IFilterGraph2 = CType(New FilterGraph, IFilterGraph2)
Dim hr As Int64 = 0
Dim nVal As Int64 = tbBrightness.Value
capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice)
CamDevice = capDevices(0)
hr = GraphBuilder.AddSourceFilterForMoniker(CamDevice.Mon, Nothing, CamDevice.Name, CamFilter)
CamControl = CType(CamFilter, IAMCameraControl)
hr = CamControl.Set(VideoProcAmpProperty.Brightness, nVal, CameraControlFlags.Auto)
Catch ex As Exception
End Try
End Sub
I appreciate your guidance on fixing this problem.
cheers,
Goutam
|
|
|
|
|
Hello,
I'm new to posting in the forum and I've been learning a lot by lurking here. I can write VB programs fine, but have not attempted using the IO ports until now. I come from the embedded field and I am an electrical engineer.
That said, I have read and tried several examples I found on the net regarding the serial ports, with no luck. I am posting the message bacause I'm stuck in something I believe shouldn't be this difficult (but this is Microsoft, so it may well be ) I have a circuit I built and programmed that sends 3 bytes (no text) to the PC and the PC needs to send 3 bytes back to the circuit.
Any good serial port tutorials out there written for VB2010? I don't want to ask anyone to write the code for me as I want to learn so I can do it myself. Many I found are general .NET with examples in C++ which I don't understand (I don't program in that language)sending text but not bytes. Others are older VB versions and don't work in 2010 (or again, more text strings.)
I'll appreciate any help or guidance in the subject. Thanks!
|
|
|
|
|
|
Thank you. I'll check it out.
|
|
|
|
|
Hi,
I've done maybe a hundred serial port applications over the years, and I can tell you all kinds of things can go wrong:
1. using wrong port
2. bad cable
3. null modem needed/not needed
4. voltage levels not appropriate
5. control lines not set properly
6. settings (baud, databits, polarity, stopbits) not matched
7. and then all kinds of software mistakes.
Trust me, you will make some of the above mistakes before everything eventually gets right. Therefore, I strongly suggest you work step-by-step and start with the easiest set-up:
1. start with ASCII text, no handshaking, and a modest setup (9600Bd, 8 databits, no parity, 2 stopbits)
2. let the most trustworthy party initially be the receiver (reason: sending is much easier than receiving)
3. observability: have the receiver show what it receives (e.g. use lowest N bits of the incoming char to set N LEDs)
4. use as much pre-existing stuff as possible on one side (e.g. use HyperTerminal on a PC to get started)
5. once the sender is programmable, make it repeat almost the same transmission regularly (send "ABCxyz" every second,
where xyz is a number between 000 and 999)
If this works, you most likely have avoided/solved most of the above problems already. Then slowly move towards your final setup. The tricky parts will show when you need high bandwidth AND good latency all at the same time, forcing you to use asynchronous operations, overlapping operations, etc. If you must debug protocols, make sure to provide good logging: log all incoming and outgoing messages into a single file.
You may think all this is a waste of time, and aim for the final setup right away. You will probably learn soon a step-by-step approach will reach the finish line much sooner, even if it means you have to modify or even scrap some code in the process.
|
|
|
|
|
Thanks for the reply Luc. I have years of experience doing stuff with serial protocols (RS232, I2C and SPI) in embedded but I am a total noob when it comes to VB programming. I figured from looking at the examples I've seen so far that it is not as "simple" as doing it in a controller chip with a UART.
I'm sure my code attempts so far have had one (or most likely more than one!) of the mistakes listed in your post. I think I'm going to setup a null modem cable between my PC and my old laptop (it has a serial port)and set the laptop with a terminal program and make sure my code is sending something out of the PC in text as you suggest before I try with my chip project. I know the chip is doing what it is supposed to do. I can see the bytes in my terminal program and another chip coded as a receiver can read and reply properly. I wish I had the same level of expertise with VB.
The final objective I have (once I can manage to get my VB code to work) is to have telemetry going from any circuit I build to my PC (yup, wireless serial.) I guess I have to learn how to walk before I can run
|
|
|
|
|
for a simple comm job the SerialPort class isn't hard to use.
Once the port is opened and configured, all it takes is a call to Write(string) or WriteLine(string) to send some text; or Write(byte[]) for binary data.
Some warnings:
- while the doc says ASCII is default, I am not convinced and always set it explicitly.
- receiving data is always harder, as one needs to synchronize; e.g. the DataReceived event occurs some time after a first char is received; when you expect N bytes/chars, there might be fewer in the input buffer when you read it!
- the NewLine property may interfere with both receive and transmit if you're using text methods (i.e. anything but byte[] operations).
If you must solve the receiver first, then teach your microcontroller to send a (almost constant) message repeatedly, say 3 bytes every 5 seconds (and I still recommend printable ASCII here, for starters).
I would go for synchronous receive first; i.e. a loop containing:
- wait 1 second
- read 1 char
- display it in hex (always debug in hex, not in decimal; you'll notice baud rate errors and the like much easier).
Which really means: keep it simple, and add observability where ever you can.
If you need specific help, show us your code (initialization, and read/write functions) and describe the symptoms.
|
|
|
|
|
Thanks Luc. Will do. I'm off to get this thing working and if I hit something specific I'll be back to ask again and post code.
|
|
|
|
|
Here I am again. Sorry to be bothering about something that is probably very easy but I fail to see it yet. I wrote a simple test program with a richtextbox (for receiving) and a textbox for input. There are connect and disconnect buttons and a send button (and exit to end) As suggested, trying text first just so I can see it in hyperterminal on the laptop. Not doing anything with receive yet, I just want to send something.
I made sure the null modem cable works by setting up my pc and laptop to have hyperterminal on and both can send and receive without problem, so I know the computers and the settings are OK. The program listing is below:
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Public Class TERMINAL
Dim instance As SerialPort
Dim output As String
Private mySerialPort As New SerialPort
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DONE.Click
End
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With mySerialPort
.PortName = "COM1"
.BaudRate = 9600
.DataBits = 8
.Parity = Parity.None
.StopBits = StopBits.One
.Handshake = Handshake.None
End With
mySerialPort.Close()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CONNECT.Click
Try
mySerialPort.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SEND.Click
output = OUTGOING.Text
If output = "" Then
MsgBox("this can't be empty to send")
Exit Sub
End If
instance.Write(output)
End Sub
Private Sub DISCONNECT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DISCONNECT.Click
mySerialPort.Close()
End Sub
End Class
Obviously I missed something or I'm doing something incorrectly as the program runs and it won't complain until I hit send (after opening the port OK) It gives me this error: "NullReferenceException was unhandled.
Object reference not set to an instance of an object." pointing to the instance.Write(output) line.
The "verbose" version of the error shows:
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=Serial text try
StackTrace:
at Serial_text_try.TERMINAL.Button1_Click(Object sender, EventArgs e) in D:\Visual Studio Personal
Code\Serial text try\Serial text try\Form1.vb:line 53
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr
lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManag
er.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext
context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext
context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at Serial_text_try.My.MyApplication.Main(String[] Args) in
17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback,
Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback,
Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
What did I do wrong? (this is frustrating)
I'm trying to get this going for over 3 weeks already.
Thanks for looking at it.
|
|
|
|
|
JDBravo wrote:
Dim instance As SerialPort
Private mySerialPort As New SerialPort
Only thing that sticks out for me is that mySerialPort you declare with the new keyword and instance you dont
Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
|
|
|
|
|
(slaps face hard)
That was it! I can see the output in hyperterminal in the laptop.
|
|
|
|
|
Code looks rather fine, except for:
1. how many serial ports do you want? I see "instance" and "mySerialPort", I guess one of them is a mistake.
2. some of the comments are a bit strange:
- mySerialPort.Close() 'MAKE SURE IT IS CLOSED BEFORE START
to your app, all ports are closed at start; they may be open by some other process, but then your app can't close them.
- .Handshake = Handshake.None 'NO HANDSHAKE! I WANT TO TALK TO A CHIP (TX,RX AND GROUND WIRES ONLY)
yes, you talk to some chip; that does not influence what kind of handshake you could use.
- output = OUTGOING.Text
If output = "" Then 'COMPLAINED IT IS NULL SO THIS WAS ADDED
did you mean Nothing? you are testing for empty, not for nothing. And a TextBox.Text never results in Nothing!
|
|
|
|
|
Luc,
1. One serial port. I see that copying the example without understanding something gives no results. Now I understand what the guy who wrote it meant (he was showing 2 examples, not defining 1 port with both)
2.Gotcha. I thought it would close any open ports from other applications for me. It was there "just in case". Deleting now.
3.Copy that.
4.Copy that too.
I got the program sending to the laptop and seeing my messages in hyperterminal there. It was the "double port" deal and not calling the right one to write. Deleted the "instance" one and using "myserialport" to write did it.
This works:
mySerialPort.Write(output)
Now on to try byte send and move on to receive
Thanks for all the help. I hope I can bother you again if I hit any snags on the receive part.
|
|
|
|
|
No problem.
You can't steal a port from another app, as you wouldn't really want other apps to steal yours, would you?
The snag is another app could open a port that you were intending to use, so one typically would open all necessary ports early on.
JDBravo wrote: try byte send
Remember, the first char is the hardest, and you got that working. It will be downhill now, until you may need some tricky receive stuff.
Warning: DataReceived (and most other) events run on a different thread (see here[^] for a test) and you can't touch GUI Controls from there (see here[^] for a solution).
|
|
|
|
|
I will keep that in mind. I'm bookmarking your site. Lots of interesting articles
|
|
|
|
|
Hi Luc,
I'm happy to report I have this thing working both ways with the PCs. I'm sending and receiving bytes and they are changing controls on the application as I wanted. I do have a question, as I copied that part of the code and only understood it well enough to make it work, but I do need more pointers as explanations are not that clear (at least for me) on the tutorials I found (I intend to learn C later--don't like the syntax). The code below works as is. It does what I want and I can have it send/receive data (if required I can modify the chip software as it is easier for me )
I want to make this program able to receive 2 data bytes (or more) instead of just one, using the delegation method (which I copied here and works fine here with one byte at a time). Those comments on the serial declarations and routines are what I understood from the explanations (please correct me if I'm wrong!)
Imports System.Byte
Imports System
Imports System.IO.Ports
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.ComponentModel
Imports System.Threading
Imports Microsoft.Win32
Imports System.Runtime.Remoting.Messaging
Public Class Form1
Dim LEDOUT1, LEDOUT2 As Byte
Dim LEDIN1, LEDIN2 As Byte
Dim ADIN As Integer
Dim LEDMSGOUT As Byte
Dim PWMOUT As Byte
Dim LEDMSGIN As Byte
Dim AD1, AD2 As Byte
Private mySerialPort As New SerialPort
Private comBuffer As Byte()
Private Delegate Sub UpdateFormDelegate()
Private UpdateFormDelegate1 As UpdateFormDelegate
Private Sub mySerialPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
UpdateFormDelegate1 = New UpdateFormDelegate(AddressOf UpdateDisplay)
Dim n As Integer = mySerialPort.BytesToRead
comBuffer = New Byte(n - 1) {}
mySerialPort.Read(comBuffer, 0, n)
Me.Invoke(UpdateFormDelegate1)
End Sub
Private Sub UpdateDisplay()
INCOMING.Text = CStr(comBuffer(0))
If INCOMING.Text = "50" Then
If OvalShape1.BackColor = Color.Gray Then
OvalShape1.BackColor = Color.Red
Else
OvalShape1.BackColor = Color.Gray
End If
End If
If INCOMING.Text = "32" Then
If OvalShape2.BackColor = Color.Gray Then
OvalShape2.BackColor = Color.Red
Else
OvalShape2.BackColor = Color.Gray
End If
End If
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
End
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim OUTPUT(3) As Byte
If LEDOUT1 = 0 Then
LEDOUT1 = 1
Else
LEDOUT1 = 0
End If
LEDMSGOUT = 40 + LEDOUT1 + LEDOUT2
OUTPUT(0) = LEDMSGOUT
OUTPUT(1) = PWMOUT
mySerialPort.Write(OUTPUT, 0, 2)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim OUTPUT(3) As Byte
If LEDOUT2 = 0 Then
LEDOUT2 = 1
Else
LEDOUT2 = 0
End If
LEDMSGOUT = 40 + LEDOUT1 + LEDOUT2
OUTPUT(0) = LEDMSGOUT
OUTPUT(1) = PWMOUT
mySerialPort.Write(OUTPUT, 0, 2)
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler mySerialPort.DataReceived, AddressOf mySerialPort_DataReceived
With mySerialPort
.PortName = "COM1"
.BaudRate = 9600
.DataBits = 8
.Parity = Parity.None
.StopBits = StopBits.One
.Handshake = Handshake.None
End With
Try
mySerialPort.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
Dim OUTPUT(3) As Byte
PWMOUT = TrackBar1.Value
OUTPUT(0) = LEDMSGOUT
OUTPUT(1) = PWMOUT
mySerialPort.Write(OUTPUT, 0, 2)
End Sub
End Class
As I said, it works fine with the laptop but I'd like the ability to receive (at any time, as it is happening here) 2 bytes or more at a time.
|
|
|
|
|
Hi,
that looks pretty good.
Here are some comments on your design and coding style:
1.
if you have independent functions in the peripheral, it would be better to have a "command language" so you can send individual commands, and don't have to repeat values that already are in effect. An example, using ASCII for simplicity could be:
L0 = led off
L1 = led on
M0 = motor off
M1 = motor on
etc.
2.
if you need combinations of data values (your current LEDMSGOUT), you should really isolate that functionality and put it in a separate method, maybe even a separate class. So every time you repeat yourself (as in LEDMSGOUT = 40 + LEDOUT1 + LEDOUT2 ) your reflex should be: this ought to be a method. Reason: less code, better readability, easier to change when the interface is modified, etc.
3.
there is a nice XOR operator, ideal to toggle LED states for instance. (LED = LED Xor 1 )
4.
when combining bits logically (rather than really adding numbers), it is better/cleaner/safer to use the OR operator, hence LEDMSGOUT = 40 Or LEDOUT1 Or LEDOUT2
5.
Why do you use uppercase for comments? IMO it makes them harder to read...
And then some pointers on multi-byte receive:
1. your code is somewhat ready for it, but it probably doesn't work well.
2. you may think of messages, the serial port doesn't care at all, all it knows are individual bytes. For instance, if you send several 10-byte messages and then read the input buffer at arbitrary points in time, you might get 4, then 12, then 3, then ... bytes. That is what makes receiving much harder.
3. the main problem is timing: DataReceived will (or may) fire as soon as one byte is coming in; it does not care about the number of bytes received, and is unaware of message lengths. It may however also be a bit late. Also, your sender in general may insert transmission delays right in the middle of a message when more important things need to be handled first (stepper motor probably has higher priority interrupts).
4. There are a couple of approaches one can take:
4a. by far the easiest is: use textual, not binary data, and define the language as having a message terminator (a special char that won't appear inside any message), then set NewLine to that char, and just do ReadLine (probably in a separate thread or backgroundworker, in a loop; i.e. don't use DataReceived event at all). The obvious special character is \n itself (careful, the default value of SerialPort.NewLine is system dependent, and may well be "\n\r" i.e. CRLF.
4b. a hack, works fine if there is a guaranteed gap in between messages: insert a delay (Thread.Sleep) that is sufficient to receive all bytes of a message, and only then actually read the incoming data. This enforces message alignment, provided you do it right (which includes: don't read more than one message at a time). However it is a hack, once it goes wrong, it may stay out of sync forever.
4c. read whatever is available (as you do now), however inside the event handler, copy it to a message buffer, and only signal the app when a full message is present (That basically is what ReadLine does for text).
4d. what would NOT be good is always handling one character at a time; that would work at low baud rates, it would be too much processor load at high comm rates.
5. you should design and code defensively, i.e. also consider comm problems may occur, such as a character getting lost or damaged. The general approach is to define a "protocol", probably message oriented, probably with message validation (some kind of checksum), and most likely with a mandatory acknowledge/come-again reply.
|
|
|
|
|
Wow! Luc, thanks again. Lots of great advice. I'm in for some modifications to this code. As I said I'm new to VB (about 6 months) and it is a whole different animal than embedded controllers. The comments in caps are a bad habit I picked up in the 8 bit era of computing. Hard to get rid of...
I think the quick solution before polishing the code as you point out is to do 4c. My circuit uses a PIC with internal hardware UART and PWM so it doesn't take much time to push bytes to the internal buffer (200 bytes) or set the duty cycle, so my software will be free to do the actual work (mostly delaying byte output.) I'll keep it at 9600 baud for now. I'll up the speed once the code is polished and convert everything to text values as you recommend. My bytes insistance was just because I'm used to do it that way when I have chips talking to each other and their peripherals (translation: I don't know better!)
I will keep learning more about VB. It is fun despite being huge compared to what I knew about the BASIC language (used to know all instructions of the top of my head.) Lots more going on with .NET and Windows. Thanks for all the help in getting my application going.
Best,
Juan
|
|
|
|
|
Hi Juan,
you're welcome. And good luck with the project.
FWIW: I once did a 9600Bd serial port plus a separate 9600Bd CAN-like protocol on some PICs (16F84 = 64 bytes of RAM, no UART), all four comm channels in software, and without interrupts (too slow!); together with two Macs, they were controlling my digital railroad setup. So, yes I know there is a huge difference between PCs and small embedded systems...
|
|
|
|
|
Hello !
I'm working on vb.net 2010 .I have a form with some labels : Label1,Label2,Label3.....and i want to access a label using name as string.i'm using the code :
For i=1 to 31
DirectCast(Me.Controls.Item("Label" & i) , Label).ForeColor=Red
Next
But this code produce an error : Object reference not set to an instance of an object.
What can i do ?
Thank you.
|
|
|
|
|
Not sure, however I would suggest you try
DirectCast(Me.Controls("Label" & i) , Label).ForeColor=Red
|
|
|
|
|
This error occurs when you are accessing an attribute of an object when the object itself does not exist.
alejx wrote: Me.Controls.Item("Label" & i)
Ensure that the values you are trying to access here exist.
|
|
|
|
|
I would loop through the controls from the forms collection and check each controls type to see if it is a label and then change it color as shown in the code snippet below
For Each Control In Me.Controls
If TypeOf Control Is Label Then
Control.forecolor = Color.Red
End If
Next
or you could do it like this
Dim l As Label = DirectCast(Controls.Item("Label1"), Label)
l.ForeColor = Color.Red
Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
|
|
|
|
|