Winforms Visibility issues on Dynamically Loaded UserControls? - winforms

So I have a program that dynamically loads in usercontrols depending on certain criteria, The problem I'm having is that my validation is only truly working on the first textbox loaded.
The following code is ran for each usercontrol loaded:
Try
TextBox = DirectCast(flpRepeatConts.Controls(Count).Controls("tbAnswerText"), Telerik.WinControls.UI.RadTextBox) ' Control(1) = TextBox Answer
LabelAnsID = DirectCast(flpRepeatConts.Controls(Count).Controls("lblQID"), RadLabel)
LabelMinHolder = DirectCast(flpRepeatConts.Controls(Count).Controls("lblMinTextHolder"), RadLabel)
lblValidationText = DirectCast(flpRepeatConts.Controls(Count).Controls("lblValidationText"), RadLabel)
If TextBox.Text.Length >= LabelMinHolder.Text And TextBox.Text.Length <= TextBox.MaxLength Then
'Good to go.
lblValidationText.Visible = False
Else
'Too little/not enough text
If LabelMinHolder.Text = TextBox.MaxLength Then
lblValidationText.Text = String.Format("Text must be exactly {0} Characters! ({1} of {0})", LabelMinHolder.Text, TextBox.Text.Length)
Else
lblValidationText.Text = String.Format("Text must be between {0} and {1} Characters!", LabelMinHolder.Text, TextBox.MaxLength)
End If
inError = True
lblValidationText.Visible = True
End If
Catch ex As Exception
'Exception Handling Here
End Try
Count += 1
The true issue here is that labels past the first one will never show (unless there's atleast one character in its respective textbox, in which case the error message does show). I'm stumped and was hoping another set of eyes would see something I don't. I've set breakpoints and stepped through this and the text and visibility are in fact being set, they just don't take effect.

Related

Using checkboxes to create an array

A background to why im trying to do this.
I am creating a program for work, this is one of many way of doing this process, where users select test that they have carried out, around 50 possible test using a userform that I've made. From the selection it runs through each userform based off which checkboxes were ticked, without the need to choose another test.
i.e. if they select 1,2,5 then the program will eventually load UserForm1 -> UserForm2 -> NOT UserForm3 -> NOT UserForm4 -> UseeForm5
The idea is that the user selects the options they want then based off the options selected create an array of either 0 if they didn't select the option or (1,2,3,4...) if they did, this number depends upon which checkbox was selected. i.e CheckBox1 = 1 CheckBox2 = 2 etc.
From this array I think i'll be able to select the correct userform using the .find feature in excel with a for loop.
But I have an issue when I run my code below,
Sub List_Create()
Dim tests(5) As Integer
If CheckBox1.Value = True Then
tests(0) = 1
Else: tests(0) = 0
End If
If CheckBox2.Value = True Then
tests(1) = 2
Else: tests(1) = 0
End If
If CheckBox3.Value = True Then
tests(2) = 3
Else: tests(2)= 0
End If
If CheckBox4.Value = True Then
tests(3) = 4
Else: tests(3) = 0
End If
If CheckBox5.Value = True Then
tests(4) = 5
Else: tests(4) = 0
End If
End Sub
I get a
runtime 424 error object required.
Which when debugged is on the line If CheckBox1.Value = True Then
Where have i gone wrong with my code? Is this possible, im not sure if it is?
You need to explicitly reference the userform to evaluate the checkbox value.
If userformX.CheckBox1.Value = True Then

why is the index of the one-dimensional array changing this way?

I'm a beginner and I'm encountering a problem with an index of a one-dimensional array of strings (m_nameList in the code) that I'm struggling to understand. I have one method (in a class of a Windows Form Application that is not the MainForm) that returns FALSE if a string of the array at a certain index is empty, and viceversa. It looks like this:
Public Function IsReserved(index As Integer) As Boolean
Dim reserved As Boolean = False
If (Not String.IsNullOrEmpty(m_nameList(index))) Then
reserved = True
Else
reserved = False
End If
Return reserved
End Function
I have also a method on the MainForm that calls for it, and if the first method returns true then the second one displays a dialog box, otherwise it doesn't (lstResults is a listbox that has for items the strings of the array):
Private Function CheckIfSeatIsAlreadyReserved() As Boolean
Dim reserved As Boolean = m_seatMngr.IsReserved(lstResults.SelectedIndex)
If (reserved) Then
Dim msgBox As Integer = MessageBox.Show("The seat is already reserved. Would you like to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If (msgBox = DialogResult.Yes) Then
Return True
Else
Return False
End If
Else
Return True
End If
End Function
The problem I find is: if as in the code of the first method above I don't initialize index to any value, the second method will work perfectly, but I'll get a runtime error if I don't select any item on the listBox (and therefore index = -1). On the other hand, if I initialize index to 0 or to m_nameList.Length, then the program won't have any problems if I don't select any item on the ListBox and it will nicely display a warning message I wrote for that case, BUT the second method will behave in a weird way: it will find ALL the strings of the array full even if I only "write" the first one, or it will find ALL the strings empty if I "write" any string that it's not the first one (by writing I mean that I call for a method that puts my input as the text of the string selected). Any idea on why this happens and how I can fix it? Thank you so much.
I will get to the answer below, follow the logic, lets look at your first method. You can refactor it to
Public Function IsReserved(index As Integer) As Boolean
Return Not String.IsNullOrEmpty(m_nameList(index))
End Function
Everything else is called "noise". But as Fabio pointed, what if index is bad? Lets add useful code
Public Function IsReserved(index As Integer) As Boolean
If index < 0 OrElse index > m_nameList.Length - 1 Then
Throw New ArgumentOutOfRangeException(". . . . .")
End If
Return Not String.IsNullOrEmpty(m_nameList(index))
End Function
If you get this exception, your program has a bug - and you know to fix the consumer of this function.
And now lets get to your message
second method will behave in a weird way: it will find ALL the strings of the array full even if I only "write" the first one, or it will find ALL the strings empty if I "write" any string
Most likely reason why it happens - simply because you create condition when you send same value over and over again. Therefore result is same. And this is most likely a bug
If (reserved) Then
. . . . . .
Else
Return True ' <---- BUG ALLERT
End If
And two more things, your second method can shrink down to 1 line too.
Private Function CheckIfSeatIsAlreadyReserved() As Boolean
Return m_seatMngr.IsReserved(lstResults.SelectedIndex) AndAlso _
DialogResult.Yes = MessageBox.Show("The seat is already reserved. Would you like to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
End Function
And, if you do some sort of reservation, array is not really good idea. How about Dictionary(Of String, Boolean)? Your theater or airplane has bunch of seats and you pre-load your dictionary with those
d.Add("1A", False)
d.Add("1B", False)
d.Add("1C", False)
d.Add("1D", False)
d.Add("1E", False)
d.Add("1F", False)
This is your whole airplane row. Now you can do much more with it

Using Variables as module/array names

My ultimate goal is to load a comboBox with elements from different arrays (vba coded). I have 8 different arrays and 6 option buttons. The first 2 optionButtons are grouped to eliminate 4 arrays which leaves the last 4 grouped optionButtons to determine the actual input for the combo box.
It works like this:
'first grouped option buttons
maleOptionButton
femaleOptionButton
'second grouped option buttons
basketballOptionButton
footballOptionButton
soccerOptionButton
hockeyOptionButton
The array's as you can guess are filled with student names that play the sports. So when the user clicks the first grouped buttons of Male/Female the click even does nothing.. however when they click the second group of option buttons of sports, it calls the same sub procedure within a module that has IF's and Else Ifs to determine the combination of buttons that were selected.
sub maleInitArray()
'declaration section:
Public maleSoccerArray(1 to 6) as string
'sub section
dim mike as student 'calls the class student
set mike = new student
with mike
.name = "Michael"
.age = 14
.so on and so on = something
end with
maleSoccerArray(1) = mike.name
End Sub
What I'm trying to do is this:
dim i as integer
dim l as integer
dim gender as string
dim sport as string
if inputForm.soccerOptionButton.value = true then
if inputForm.maleOptionButton.value = true then
gender = "male"
sport = "maleSoccerArray"
call male.maleInitArray ' inits the array thats hard coded.
else
gender = "female"
sport = "femaleSoccerArray"
call female.femaleInitArray
Else If...
' the list goes on to assign variables depending on the combo boxes.
' doesn't work, but it beats using this every time
l = UBound(sport) ' Doesn't recognize "sport" as an Array
for i = 1 to l
' .AddItem(gender.sport(i)) will not work as well.
inputForm.studentComboBox.AddItem(gender.sport(i))
next i
Seems as though UBound(variable) and AddItem(Variable.Variable)
will not work...
I found a few things so far, but none of them have worked.. such as the application.run method and assigning the actual "male.maleSoccerArray" method.
Any help would be greatly appreciated.. thanks

get_by_id() not returning values

I am writing an application that shows the user a number of elements, where he has to select a few of them to process. When he does so, the application queries the DB for the rest of the data on these elements, and stacks them with their full data on the next page.
I made an HTML form loop with a checkbox next to each element, and then in Python I check for this checkbox's value to get the data.
Even when I'm just trying to query the data, ndb doesn't return anything.
pitemkeys are the ids for the elements to be queried. inpochecks is the checkbox variable.
preqitems is the dict to save the items after getting the data.
The next page queries nothing and is blank.
The comments are my original intended code, which produced lots of errors because of not querying anything.
request_code = self.request.get_all('rcode')
pitemkeys = self.request.get_all('pitemkey')
inpochecks = self.request.get_all('inpo')
preqitems = {}
#idx = 0
#for ix, pitemkey in enumerate(pitemkeys):
# if inpochecks[ix] == 'on':
# preqitems[idx] = Preqitems.get_by_id(pitemkey)
# preqitems[idx].rcode = request_code[ix]
# idx += 1
for ix, pitemkey in enumerate(pitemkeys):
preqitems[ix] = Preqitems.get_by_id(pitemkey)
#preqitems[ix].rcode = request_code[ix]
Update: When trying
preqitems = ndb.get_multi([ndb.Key(Preqitems, k) for k in pitemkeys])
preqitems returns a list full of None values, as if the db couldn't find data for these keys.. I checked the keys and for some reason they are in unicode format, could that be the reason? They look like so.
[u'T-SQ-00301-0002-0001', u'U-T-MT-00334-0007-0002', u'U-T-MT-00334-0008-0001']
Probably you need to do: int(pitemkey) or str(pitemkey), depending if you are using integer or string id

Non-cell array with uigetfile in Matlab

My code has 2 parts. First part is an automatic file opening programmed like this :
fichierref = 'H:\MATLAB\Archive_08112012';
files = dir(fullfile(fichierref, '*.txt'));
numberOfFiles = numel(files);
delimiterIn = ' ';
headerlinesIn = 11;
for d = 1:numberOfFiles
filenames(d) = cellstr(files(d).name);
end
for i=1:numberOfFiles
data = importdata(fullfile(fichierref,filenames{i}),delimiterIn,headerlinesIn);
end
Later on, I want the user to select his files for analysis. There's a problem with this though. I typed the lines as follow :
reference = warndlg('Choose the files from which you want to know the magnetic field');
uiwait(reference);
filenames = uigetfile('./*.txt','MultiSelect', 'on');
numberOfFiles = numel(filenames);
delimiterIn = ' ';
headerlinesIn = 11;
It's giving me the following error, after I press OK on the prompt:
Cell contents reference from a non-cell array object.
Error in FreqVSChampB_no_spec (line 149)
data=importdata(filenames{1},delimiterIn,headerlinesIn);
I didn't get the chance to select any text document. Anyone has an idea why it's doing that?
uigetfile is a bit of an annoying when used with `MultiSelect': when you select multiple files the output is returned as a cell array (of strings). However, when only one file is selected the output is of type string (not a cell array with a single cell, as one would have expected).
So, in order to fix this:
filenames = uigetfile('./*.txt','MultiSelect', 'on');
if ~iscell(filenames) && ischar( a )
filenames = {filenames}; % force it to be a cell array of strings
end
% continue your code here treating filenames as cell array of strings.
EDIT:
As pointed out by #Sam one MUST verify that the user did not press 'cancel' on the UI (by checking that filenames is a string).

Resources