How to use checkbox to select my data - sql

i am using vb.net with microsoft sql
i want to retrieve data where the checkbox is selected how could i perform it?
this the code i currently have
Dim chk As New DataGridViewCheckBoxColumn()
DataGridView1.Columns.Add(chk)
chk.HeaderText = "Select"
chk.Name = "lol"
sql.RunQuery("Select ID,JobPosition,requiredQualification,Salary, description,JobExpYear from vacancy where JobPosition IN (Select JobPosition from employer where EID = '" & ID & "')")
If sql.SQLDS.Tables.Count > 0 Then
DataGridView1.DataSource = sql.SQLDS.Tables(0)
End If
i will have checkbox within my data grid, how do i call it?

I'm not sure if this is what you need, question not clear enough for me. But see if this helps:
Dim condition As String = String.Empty
For Each row As DataGridViewRow In DataGridView1.Rows
condition += DirectCast(row.Cells(0), DataGridViewCheckBoxCell).Selected.ToString + ", "
Next
If Not String.IsNullOrEmpty(condition) Then
'Remove last splitter
condition = condition.Substring(0, condition.Length - 2)
End If

Your question: "i am using vb.net with microsoft sql i want to retrieve data where the checkbox is selected how could i perform it?"
There are a few different ways that this can be accomplished. You can either one, create a function that returns if it's checked or not or create a method that does all of your logic for you, it depends on how your going to use it. According to your query your not getting any information from the DataGridView, you are saying you want to retrieve data if it's checked or not. Another question is what is the purpose of running the same query if you have multiple rows, are you going to be running different queries based on the CheckBox for that row if it's checked?
Example 1 -Create a function to see what the value is
''' <summary>
''' Returns if given column is checked or not
''' </summary>
''' <param name="dGrid"></param>
''' <param name="dRow"></param>
''' <param name="intIndex"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function IsColumnChecked(ByVal dGrid As DataGridView, ByVal dRow As DataGridViewRow, ByVal intIndex As Integer) As Boolean
Dim blnIsChecked As Boolean = False
Try
'What column is the checkboxcolumn and let's make sure its the correct type
If TypeOf (dGrid.Columns(intIndex)) Is DataGridViewCheckBoxColumn Then
If dGrid.RowCount <> 0 Then
If CBool(DirectCast(dRow.Cells(intIndex), DataGridViewCheckBoxCell).Value) Then
blnIsChecked = True
End If
Else
Return blnIsChecked
End If
Else
Return blnIsChecked
End If
Catch ex As Exception
Return blnIsChecked
End Try
Return blnIsChecked
End Function
Example 1 Useage - Check to see if given row is checked or not-
'Example ONLY on a button click...
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If IsColumnChecked(DataGridView1, DataGridView1.CurrentRow, 0) Then
MessageBox.Show("It's Checked!")
Else
MessageBox.Show("Not Checked!")
End If
End Sub
You can also put this in a method to do what you want with other logic, not sure how you are going to use it. This function is good to determine if you want to continue with other things or not and can be used in other areas of your program as well.
Good Luck!

Related

Filtering binding source

This should be easy but I am having a headbanging of a time trying to get this to work! I have done a search and tried all most EVERY SINGLE ONE. Nothing works. I have a datagrid with a binding source. A user will type text into a textbox and the grid is SUPPOSED to change to only show records that contain what user typed in the name. Simple right? NOPE! Not for me! What am I doing wrong? Code below.
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim Found As Boolean = False
Dim StringToSearch As String = ""
Dim ValueToSearchFor As String = "%" & SearchTextBox.Text.Trim.ToLower & "%"
Dim CurrentRowIndex As Integer = 0
Try
If ReferencesGrid.Rows.Count = 0 Then
CurrentRowIndex = 0
Else
CurrentRowIndex = ReferencesGrid.CurrentRow.Index + 1
End If
If CurrentRowIndex > ReferencesGrid.Rows.Count Then
CurrentRowIndex = ReferencesGrid.Rows.Count - 1
End If
If ReferencesGrid.Rows.Count > 0 Then
For Each gRow As DataGridViewRow In ReferencesGrid.Rows
StringToSearch = gRow.Cells(1).Value.ToString.Trim.ToLower
If InStr(1, StringToSearch, LCase(Trim(SearchTextBox.Text)), vbTextCompare) Then
TrainingItemBindingSource.Filter = String.Format("Name LIKE '{0}'", ValueToSearchFor)
Exit For
End If
Next
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
You should get rid of pretty much all that code. If you want to filter the data then just filter the data. There's no conditional statements required and loops required. Just set the Filter property and any records that don't match the filter will be hidden:
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
TrainingItemBindingSource.Filter = $"Name LIKE '%{SearchTextBox.Text.Trim()}%'"
End Sub
As you can see, it is simple. I've no real idea what you were actually trying to achieve with the rest of that code. That will exclude any records where the Name column does not contain the search text.
Note that there is no need to try to force case-insensitivity by using ToLower or the like. Just like in real SQL, comparisons done this way in a DataTable are case-insensitive by default. You have to explicitly set the CaseSensitive property of the DataTable or its parent DataSet to True to make such comparisons case-sensitive.
I should also point out that the ability to filter is predicated on the data source implementing certain interfaces. If the data source is a DataTable then you have those interfaces for free. If you have actually bound to something else, e.g. a List(Of T), then you won't be able to filter this way because the required members do not exist.

Display DataGridView values in text boxes based on matching values - vb.net

I have an SQL query that returns 2 columns of values:
country | number
NA | 1
IN | 2
CN | 3
DE | 4
And so on.
I am trying to do one of the following:
Assign these values to variables I can copy to an excel workbook
Or just use the DGV as a medium to copy values to text boxes.
For example, I have a form with country labels and textboxes next to them. I would want to click a button and have the data copied to the matching text box.
DGV number value where DGV row value = CN would be 3 and that value would be copied to the CN value text box.
If you are only using the DGV as a medium, but not actually displaying it, use a dictionary instead. Output the SQLDataReader using the SQLcommand(cmd) with the country code being the key and the number being the value. Then its as simple as:
Dim dc As Dictionary(Of String, String) = New Dictionary(Of String, String)
Dim cmd As SqlCommand = "your query string"
cmd.Connection.ConnectionString = "your con string"
Using sqlrdr As SqlDataReader = cmd.ExecuteReader()
While (sqlrdr.Read())
dc.Add(sqlrdr(0), sqlrdr(1))
End While
End Using
Then just output to the textbox:
txtNA.Text = dc.Item("NA")
If the countries are fixed as your question refers, then you could use something like this:
First, use the names of the countries to name the TextBoxes (txtNA, txtIN, txtCN,...)
Then you can put this code:
Try
For i = 0 To DataGridView1.RowCount - 1
Me.Controls("txt" & DataGridView1.Rows(i).Cells(0).Value.ToString).Text = _
DataGridView1.Rows(i).Cells(1).Value.ToString()
Next
Catch
End Try
The following will not work 'as is' if using classes via dragging tables from the data source window in the ide. We would need to cast objects not to a DataTable but to the class definition in a TableAdapter, DataSet and BindingSource.
Here is a method which reads from SQL-Server database table, places data into a DataTable, data table become the data source for a BindingSource which becomes the data source for the DataGridView. Using a BindingSource we now use the BindingSource to access row data rather than the DataGridView and it's always best to go to the data source rather than the user interface.
BindingSource.Current is a DataRowView, drill down to Row property then field language extension method to get strongly typed data for the current row if there is a current row as you will note I am using two forms of assertions, first, do we have a data source and is the data source populated then we see if there is indeed a current row.
From here we can set variable, properties or control text to the field values of the current row.
Note in form load I seek a specific country (totally optional) and then if found go to that row.
Least but not last, I like using xml literals when doing SQL in code so there is no string concatenation and we can format the statement nicely.
Public Class Form1
''' <summary>
''' Permits obtaining row data in DataGridView
''' </summary>
''' <remarks></remarks>
Dim bsCountries As New BindingSource
Public Property Country As String
Public Property CountryNumber As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
Using cn As New SqlClient.SqlConnection With
{
.ConnectionString = My.Settings.KarenDevConnectionString
}
Using cmd As New SqlClient.SqlCommand With {.Connection = cn}
' xml literal to make command text
cmd.CommandText =
<SQL>
SELECT [ID],[Country],[Number]
FROM [Countries]
</SQL>.Value
cn.Open()
dt.Load(cmd.ExecuteReader)
dt.Columns("ID").ColumnMapping = MappingType.Hidden
bsCountries.DataSource = dt
DataGridView1.DataSource = bsCountries
' let's try and move to a country
Dim index As Integer = bsCountries.Find("Country", "CN")
If index > -1 Then
bsCountries.Position = index
End If
End Using
End Using
End Sub
''' <summary>
''' Put field values into TextBoxes
''' </summary>
''' <remarks></remarks>
Private Sub DoWork()
If bsCountries.DataSource IsNot Nothing Then
If bsCountries.Current IsNot Nothing Then
Dim row As DataRow = CType(bsCountries.Current, DataRowView).Row
TextBox1.Text = row.Field(Of String)("Country")
TextBox2.Text = row.Field(Of Integer)("Number").ToString
' we can also do this
Me.Country = row.Field(Of String)("Country")
Me.CountryNumber = row.Field(Of Integer)("Number")
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DoWork()
End Sub
End Class

Pass integer value from one form to another in VB.NET

I'm writing a program that has two forms. One form gets the user to enter multiple values, and then does some calculations. Then it passes that information to another form However I can't figure out how to do it. Here is a relevant part of my code. To head some confusion, I am trying to pass 11 values, also initially, form 2 is not shown, and then when the values are passed from form 1 to form 2, then form 1 goes away and form 2 is the only one that shown
NOTE: This is not all my code, I don't believe all my code is required (I have 1000 lines right now) However this is the code with the information I want to be passed to the other form.
A lot of people are apparently saying that this is a duplicate of another question, however that question, he seems to already know how to pass the variables, but is just having issues with it (and even with looking at his, i cant figure it out)
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
'declarations
Dim intNormal As Integer
Dim intChildren As Integer
Dim intBonanza As Integer
Dim intDiamond As Integer
Dim intPictureFrame As Integer
Dim intKite As Integer
Dim intCrazyT As Integer
Dim intLetterX As Integer
Dim int2PostageStamp As Integer
Dim intPick7 As Integer
Dim intJackpot As Integer
Validate()
If txtNormal1.Enabled = False Then
intNormal = intNormInput
Else
intNormal = CalcNormalBooks()
End If
If txtChildren1.Enabled = False Then
intChildren = intChildInput
Else
intChildren = calcChildrensBooks()
End If
If txtBonanza1.Enabled = False Then
intBonanza = intBonInput
Else
intBonanza = calcBonanza()
End If
If txtSpecial1.Enabled = False Then
intSpecial = intSpeInput
Else
intSpecial = calcSpecialBooks(intSpecial)
End If
If txtDiamond1.Enabled = False Then
intDiamond = intDiaInput
Else
intDiamond = calcDiamond(intSpecial)
End If
If txtPictureFrame1.Enabled = False Then
intPictureFrame = intPicInput
Else
intPictureFrame = calcPictureFrame(intSpecial)
End If
If txtKite1.Enabled = False Then
intKite = intKiteInput
Else
intKite = calcKite(intSpecial)
End If
If txtCrazyT1.Enabled = False Then
intCrazyT = intCrazyInput
Else
intCrazyT = calcCrazyT(intSpecial)
End If
If txtLetterX1.Enabled = False Then
intLetterX = intLettInput
Else
intLetterX = calcLetterX(intSpecial)
End If
If txt2PostageStamp1.Enabled = False Then
int2PostageStamp = intPostInput
Else
int2PostageStamp = CalcPostageStamp(intSpecial)
End If
If txtPick71.Enabled = False Then
intPick7 = intPickInput
Else
intPick7 = calcPick7(intSpecial)
End If
If txtJackpot1.Enabled = False Then
intJackpot = intJackInput
Else
intJackpot = calcJackpot()
End If
End Sub
Since I had almost the same requiremnt lately here is my solution:
Custom Event which fires when your 2nd Form is closing
Public Event HotKeyFormClosed As EventHandler(Of HotKeyFormClosedEventArgs)
Custom EventArgs class where you store your values you want to pass to Main Form
Public Class HotKeyFormClosedEventArgs
Inherits EventArgs
'Your properties here
Public Sub New(...) 'your params here
MyBase.New()
'set your properties here
End Sub
End Class
On 2nd Form handle FormClosed event and pass your values to EventArgs
Private Sub HotKey_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs)
RaiseEvent HotKeyFormClosed(Me, New HotKeyFormClosedEventArgs(...)) 'your params here
End Sub
On Main Form handle your custom event (here HotKeyFormClosed) and extract its values
AddHandler frmHotKey.HotKeyFormClosed, AddressOf HotKey_FormClosed;
...
Private Sub HotKey_FormClosed(sender As Object, e As HotKeyFormClosedEventArgs)
'Do stuff with values from e
End If
I have chosen the Event approach since it decouples the two forms from another.
One could easily duplicate the information on both forms, make them public and access it directly thru an object instance.
But I like the observable approach from the events more due to it gives mor flexibility (additonal forms using the same events etc.)
P.S.: I wrote my code in c# and blind entered the VB code here so be gracious.
The values/variables that a method expects to receive (specified in the method's signature) are called Parameters.
The values sent to a method when the method is called are called Arguments.
As long as the arguments used when calling a method match the parameters for that method, those values can be passed.
For example (and I'll try to apply this to your context), if you want to create an instance of a form that takes certain values, you can specify those parameters in the form's New event, like so:
Public Sub New(someInt As Integer)
'do something with someInt here
End Sub
Then when you call this method you'd pass it the arguments, like so:
Dim myInt As Integer = 10
Dim newForm As myForm = New myForm(myInt)
When I say the arguments need to match the parameters, that means the number of values, the order of those values, and the value types must be the same (or in the case of numbers the parameter's type must be the same or larger than the argument's type).
As long as that is true, then it shouldn't really matter how you pass these - you could pass 11 individual arguments, you just have to make sure you are matching the argument to the parameter.
Hope that helps!

Show calendar in Ultragrid Column Filter

I have an UltraGrid in which I have many columns of which 2 columns are DateTime style. Now when I use the filter of that columns it shows all the DateTime values as a text in a dropdown. But I need that as a calendar in order to make the filter easy. It is enough to show just a calendar when clicking the filter.
I have tried some code but it doesn't work.
//Code:
Private Sub grdResult_BeforeRowFilterDropDown(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.BeforeRowFilterDropDownEventArgs) Handles grdResult.BeforeRowFilterDropDown
e.Cancel = True
UltraCalendarCombo1.Visible = True
UltraCalendarCombo1.Location = New Point(grdResult.Rows.FilterRow.Cells(e.Column).GetUIElement().Rect.Location.X, grdResult.Rows.FilterRow.Cells(e.Column).GetUIElement().Rect.Location.Y - 2)
UltraCalendarCombo1.Size = New System.Drawing.Size(grdResult.Rows.FilterRow.Cells(e.Column).GetUIElement().Rect.Size.Width, grdResult.Rows.FilterRow.Cells(e.Column).GetUIElement().Rect.Size.Height)
' UltraCalendarCombo1.DroppedDown = True
End Sub
The above event will fire when the filter dropdown is clicked.
private sub applyCustomeViewSettings(byval gridFormat as GridFormat)
....
...
For Each ColumnFormat In gridFormat.ColumnFormats
For Each column In Me.grdResult.DisplayLayout.Bands(0).Columns
If column.Key.ToUpper = ColumnFormat.ColumnKey.ToUpper Then
If column.Key.ToUpper = "PCSSTDT" Then
column.Header.Caption = IIf(ColumnFormat.Caption = "", ColumnFormat.ColumnKey, ColumnFormat.Caption)
column.Hidden = ColumnFormat.Hidden
'column.AllowRowFiltering = IIf(ColumnFormat.AllowRowFiltering = False, ColumnFormat.AllowRowFiltering, DefaultableBoolean.True) 'CType(ColumnFormat.AllowRowFiltering, DefaultableBoolean)
column.Width = ColumnFormat.Width
column.Header.VisiblePosition = ColumnFormat.VisiblePosition
column.Format = ColumnFormat.Format
column.SortIndicator = ColumnFormat.SortIndicator
' column.Style = ColumnStyle.Date
'column.EditorComponent = UltraCalendarCombo1
column.FilterOperandStyle = FilterOperandStyle.Default
Else
column.Header.Caption = IIf(ColumnFormat.Caption = "", ColumnFormat.ColumnKey, ColumnFormat.Caption)
column.Hidden = ColumnFormat.Hidden
column.AllowRowFiltering = IIf(ColumnFormat.AllowRowFiltering = False, ColumnFormat.AllowRowFiltering, DefaultableBoolean.True) 'CType(ColumnFormat.AllowRowFiltering, DefaultableBoolean)
column.Width = ColumnFormat.Width
column.Header.VisiblePosition = ColumnFormat.VisiblePosition
column.Format = ColumnFormat.Format
column.SortIndicator = ColumnFormat.SortIndicator
column.Style = ColumnFormat.Style
End If
End If
Next
....
...
End Sub
The above method makes the grid changes(apply settings) to show the filter as calendar.
But this doesn't work and showing me the same normal grid.
How can I achieve this?
I have managed to show a MonthCalendar when you press the icon to filter a DateTime column in an UltraWinGrid.
When the MonthCalendar is dispayed you could select a specific date using the familiar interface provided by this standard WinForm control. After selecting the date you could use the value to apply programmatically a filter condition to the UltraWinGrid column.
To reach this result you first need to add a reference to the Infragistics4.Win.SupportsDialog.v11.2 assembly where you can find the UltraGridFilterUIProvider class
Now, in your form where you need the filtering to appear, add this code: (it is just an example because I haven't your datasource and thus I have a prebuilt one with just one datetime column)
Imports Infragistics.Win.UltraWinGrid
Imports Infragistics.Win.SupportDialogs.FilterUIProvider
Public Class Form1
' This is the key object that let us customize '
' the Filter for the UltraWinGrid'
Dim _filterUIProvider as UltraGridFilterUIProvider
' In the InitializeLayout event we substitute the normal
' filter handler with the custom filter'
Private Sub UltraGrid1_InitializeLayout(sender As Object, e As Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs) Handles UltraGrid1.InitializeLayout
e.Layout.Override.AllowRowFiltering = Infragistics.Win.DefaultableBoolean.True
_filterUIProvider = New UltraGridFilterUIProvider()
' Comment out the following line to test the default
' **Excel Filter Style Interface** '
AddHandler _filterUIProvider.BeforeMenuPopulate, AddressOf _filterUIProvider_BeforeMenuPopulate
e.Layout.Override.FilterUIProvider = _filterUIProvider
End Sub
' Before the UltraGridFilterUIProvider shows its standard form interface
' we start a custom form used to apply our filtering logic '
' and block the display of the UltraGridFilterUIProvider interface '
Private Sub _filterUIProvider_BeforeMenuPopulate(sender As Object, e As Infragistics.Win.SupportDialogs.FilterUIProvider.BeforeMenuPopulateEventArgs)
' A custom form with the MonthCalendar and 3 buttons '
' to handle the filter logic '
Using fDate = new FormDate()
' Open our custom form with the monthcalendar
if (DialogResult.OK = fDate.ShowDialog())
' We need a nullable date to allow the removing of the filter'
Dim dtFilter As DateTime? = fDate.SelectedDate
if (dtFilter.HasValue)
' Apply programmatically a filtercondition to the column
' In this case I have only one column. so I use the index 0
' in your case this should change to reflect your column index
Dim fc = new FilterCondition(FilterComparisionOperator.Equals, dtFilter.Value)
ultraGrid1.DisplayLayout.Bands(0).ColumnFilters(0).FilterConditions.Add(fc)
Else
ultraGrid1.DisplayLayout.Bands(0).ColumnFilters.ClearAllFilters()
End If
End If
End Using
e.Handled = true ' Stop the standard interface'
End Sub
End Class
Now we need only a simple form called FormDate that contains a MonthCalendar and three buttons (Set, Clear, Cancel) that return (Set) a Date to set the filter, (Clear) a null value to remove previous filter and a cancel button to abort the processing
Here the code for the form, the design is trivial
Public Class FormDate
Public Property SelectedDate As DateTime?
Private Sub FormDate_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.SelectedDate = Nothing
End Sub
Private Sub cmdSet_Click(sender As Object, e As EventArgs) Handles cmdSet.Click
'This button has DialogResult=OK'
Me.SelectedDate = monthCalendar1.SelectionStart
End Sub
Private Sub cmdClear_Click(sender As Object, e As EventArgs) Handles cmdClear.Click
'This button has DialogResult=OK'
Me.SelectedDate = Nothing
End Sub
End Class
This could resolve your problem, however, I have discoverd what seems to be a bug in UltraGridFilterUIProvider. When I call the e.Handled=True my expected result is the filter to not show anything but, instead a small window still appears and I have to press Escape to hide it. I have not found any way to automatically hide it.
It seems to be a problem to signal to the Infragistics team.
I suggest you also to test the Excel Style Filter Interface provided automatically by the UltraGridFilterUIProvider. This interface has a lot of options and is much more preferable to the standard UI filter. To test this interface you should only comment out the AddHandler line above
EDIT Following the comment from #Alhalama I have tried to use the BeforeRowFilterDropDown event and the result are better (well it is perfect now). So I have commented out the line with the AddHandler, removed the code for the BeforeMenuPopulate and added the code for the BeforeRowFilterDropDown
Private Sub UltraGrid1_BeforeRowFilterDropDown(sender As Object, e As BeforeRowFilterDropDownEventArgs) Handles UltraGrid1.BeforeRowFilterDropDown
If e.Column.Key = "DateRequest" Then
Using fDate = New FormDate()
If DialogResult.OK = fDate.ShowDialog() Then
Dim dtFilter As DateTime? = fDate.SelectedDate
If (dtFilter.HasValue) Then
Dim fc As FilterCondition = New FilterCondition(FilterComparisionOperator.Equals, dtFilter.Value)
UltraGrid1.DisplayLayout.Bands(0).ColumnFilters(0).FilterConditions.Add(fc)
Else
UltraGrid1.DisplayLayout.Bands(0).ColumnFilters.ClearAllFilters()
End If
End If
End Using
e.Cancel = True
End If
End Sub
Now, when I try to open the filter for the column named DateRequest I open immediately the FormDate and at the end I set the Cancel property of the BeforeRowFilterDropDownEventArgs to true to avoid further processing of the filter dialog. This seems to be perfect...... Great credit for this to Mr. Alhalama. If you wish I think you should post your own answer because your suggestion really makes the difference.

Can I create a property of a property?

So I recently grasped the concept of using classes in my Visual Basic programming, and I found it tremendously helpful. In my current project, I have several groups boxes of check boxes (each check box denotes a "Behavior") and in each group box, there is always one check box that has a textbox control instead of a label (to allow the user to specify an "Other" behavior). It is that user-generated label that is giving me trouble...
I created a class called "Behaviors" that basically does the following:
getChecked > This method gets each checked checkbox and adds it to
the BehaviorCollection for a given Form.
behaviorCollection > represents the collection of checked
checkboxes.
getOtherChecked > does the same as "getChecked" except with the
"Other Behavior" checkboxes.
otherBehaviorCollection > represents the collection of checked
"Other" checkboxes.
The issue is that for each checked "Other Behaviors" checkbox, I need to store the value of its corresponding textbox. I would like to set my getOtherChecked() method to do this, so that in the end, I would be able to something like this...
Dim myBoxes as new Behaviors
Dim cBox as Checkbox
Dim cBoxLabel as String
myBoxes.getOtherChecked(myUserForm) 'This would get each checked "Other Behaviors" checkbox object, and also somehow add another property to it called "LinkedTextboxLabel" that would be assigned the value of the corresponding textbox.
cBox = myBoxes.otherBehaviorCollection.item(0) 'Assign a checkbox from my "Other Behaviors" collection to a variable.
cBoxLabel = cBox.LinkedTextboxLabel 'Assign the user-inputted value of the linked textbox to a variable.
So basically how could/should I add a custom-property to a collection item or checkbox?
I thought about just adding the names of the controls to a temporary DataTable or SQL table, so that each row would have the name of a checkbox in one column and its corresponding textbox value in the next, but I am hoping there is a more commonly used and accepted method.
Thank you in advance!
You could add a property for the text associated with the "Other Behaviors" checkbox.
EDIT: You might be trying to generalize your data too far, because the "Other behaviors" is a special case and deserves separate consideration.
If you have a look at what the following code (in a new Windows Forms project) creates, it might give you ideas:
Public Class Form1
''' <summary>
''' A behaviour domain and its characteristics, with one user-defined entry.
''' </summary>
''' <remarks></remarks>
Public Class BehavioursSectionDescriptor
Property BehaviourTypeName As String
Property BehaviourNames As List(Of String)
Property CustomBehaviours As String
End Class
''' <summary>
''' Return a GroupBox containing CheckBoxes and one Checkbox with a TextBox adjacent to it.
''' </summary>
''' <param name="behaviourSet"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function GetBehaviourGroupPanel(behaviourSet As BehavioursSectionDescriptor) As GroupBox
Dim gb As New GroupBox
gb.Text = behaviourSet.BehaviourTypeName
Dim fixedBehaviourNames As List(Of String) = behaviourSet.BehaviourNames
Dim customBehavioursValue As String = behaviourSet.CustomBehaviours
Dim cbVertSeparation As Integer = 4
Dim gbPadding As Integer = 20
Dim cb As New CheckBox
Dim yLoc As Integer = gbPadding
For i = 0 To fixedBehaviourNames.Count - 1
cb = New CheckBox
cb.Location = New Point(gbPadding, yLoc)
cb.Text = fixedBehaviourNames(i)
' you can use the .Tag Object of a Control to store information
cb.Tag = behaviourSet.BehaviourTypeName & "-Cb-" & i.ToString()
gb.Controls.Add(cb)
yLoc += cb.Height + cbVertSeparation
Next
cb = New CheckBox
cb.Text = ""
cb.Location = New Point(gbPadding, yLoc)
cb.Tag = behaviourSet.BehaviourTypeName & "-Custom behaviours"
gb.Controls.Add(cb)
Dim tb As New TextBox
tb.Location = New Point(gbPadding + 18, yLoc)
tb.Width = 100
tb.Text = customBehavioursValue
gb.Controls.Add(tb)
' make sure the textbox appears in front of the checkbox's label area
tb.BringToFront()
gb.Size = New Size(160, yLoc + gbPadding * 2)
Return gb
End Function
Private Function GetTestData() As List(Of BehavioursSectionDescriptor)
Dim bsds = New List(Of BehavioursSectionDescriptor)
bsds.Add(New BehavioursSectionDescriptor With {.BehaviourTypeName = "In water", _
.BehaviourNames = New List(Of String) From {"Floats", "Spins"}, _
.CustomBehaviours = "Paddles"})
bsds.Add(New BehavioursSectionDescriptor With {.BehaviourTypeName = "Under light", _
.BehaviourNames = New List(Of String) From {"Shines", "Glows", "Reflects"}, _
.CustomBehaviours = "Iridesces"})
bsds.Add(New BehavioursSectionDescriptor With {.BehaviourTypeName = "Near food", _
.BehaviourNames = New List(Of String) From {"Sniffs", "Looks"}, _
.CustomBehaviours = ""})
Return bsds
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim bsds As List(Of BehavioursSectionDescriptor) = GetTestData()
Dim gbs As New List(Of GroupBox)
Dim xLoc As Integer = 20
Dim yLoc As Integer = 20
' make some GroupBoxes to present the data input fields
For i = 0 To bsds.Count - 1
Dim gb = GetBehaviourGroupPanel(bsds(i))
gb.Location = New Point(xLoc, yLoc)
gb.Dock = DockStyle.None
yLoc += gb.Height + 30
Me.Controls.Add(gb)
Next
' size the form to fit the content
Me.Size = New Size(240, yLoc + 40)
End Sub
End Class
I know it doesn't answer the question of adding a property to a property, but could you create a class for the Other checkbox and override it's capabilities? Then you could add checkboxes and OtherCheckBoxes to your generic collection? for instance, (by no means complete, but you should get the idea)
EDIT: Changed code to show Shadows
Public Class OptionalCheckbox : Inherits CheckBox
Private mOptionalText As String
Public Shadows Property Text() As String
Get
Return mOptionalText
End Get
Set(value As String)
mOptionalText = value
MyBase.Text = value
End Set
End Property
End Class
For each item, if you were to retrieve .Text, you would either get your textbox value or your checkbox label (if it was a normal checkbox)
And how to utilize in other parts of your code. Again, this is just more of an example. You would still need to work with the textbox that is assigned to the OtherCheckBox to get it to write the text to that, as well as read from that into the .Text property of the Class.
Dim newCheckBoxCollection As New Collection
Dim cBox As New CheckBox
cBox.Text = "Standard Value Here"
'other properties of the checkbox can be modified here
newCheckBoxCollection.Add(cBox)
Dim cOBox As New OptionalCheckbox
cOBox.Text = "Optional Text Here"
'other properties of the checkbox can be modified here
newCheckBoxCollection.Add(cOBox)
For Each cb As CheckBox In newCheckBoxCollection
Me.FlowLayoutPanel1.Controls.Add(cb)
Next
If you are trying to just save the data into something like a DataTable or SQL table the code would be a bit of an overkill. I suggest you use a stream reader/writer and try checking the values that way as the code would be a lot more simple.