|
-
Jul 8th, 2019, 01:12 PM
#1
Thread Starter
Addicted Member
Check combobox value is selected
I am trying to check that a selection has been made in a form.
I have tried the following:
Code:
Private Sub cboCSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCSize.SelectedIndexChanged
CSizeValue = CInt(cboCSize.SelectedValue)
If (String.IsNullOrEmpty(cboCSize.SelectedValue)) Then
MessageBox.Show("Please select a value")
Return
End If
End Sub
If nothing is selected, then nothing happens, but if all the selections are made, the messagebox is still displayed.
The values in the combobox are from a dataset and the first value is displayed by default.
This is the only combobox control that causes the program to hang, but I can close the window and at this point the message box is displayed.
I have also tried this:
Code:
Private Sub cboCSize_SelectedValueChanged(sender As Object, e As EventArgs) Handles cboCSize.SelectedValueChanged
Static skip As Boolean = False
If cboCSize.SelectedIndex < 0 Then
If Not skip Then MessageBox.Show("Please select a value")
skip = False
Exit Sub
End If
MessageBox.Show("You have selected " & cboCSize.SelectedItem.ToString)
skip = True
End Sub
and although a message box is displayed the message is as shown below.

Also, when I click the print button nothing happens.
Before I go any further I need to explain the code in more detail.
I am designing a program to enable users to print a greeting that can be used in hand made cards.
The aim of the form's code is to print some text. the one that I am having trouble with is a combobox which selects from a list the size of the card. The displayed item is called Narrative, which is a readable description. This is used in a SQL SELECT command to extract the correct values that dictate the position and orientation of the paper.
The next control is a NumericUpDown control, which allows the user to adjust the position from the top of the sheet.
The next control is a combobox, which chooses the font from the installed fonts.
The next control is a NumericUpDown control, which the user chooses the Font Size.
The last control is another combobox, which inherits the installed system colors.
I did try changing SelectedIndex to both of the following:
SelectedValue - which displayed 2, when I chose the second item.
DisplayMember - which displayed the name of the control 'Narrative', but not the text obtained from the database.
I should add that the only control that stopped the verse from printing was the omission of the selection of the card size, the font defaulted to Ariel and the color to black (first item in list).
The code uses PDFSharp class to print the greeting.
So you can see the whole code here is the code:
Code:
Imports PdfSharp
Imports PdfSharp.Drawing
Imports PdfSharp.Fonts
Imports PdfSharp.PageOrientation
Imports PdfSharp.PageSize
Imports PdfSharp.Pdf
Imports PdfSharp.Internal
Imports PdfSharp.Drawing.Layout
Imports PdfSharp.Forms
Imports System.Data.SqlClient
Enum pageOrientation
Landscape
Portrait
End Enum
Enum pagesize
A4
A5
End Enum
Public Class frmPrintFrm
Private boxX As Double
Private boxY As Double
Private cellw As Double
Private cellh As Double
Private ort As String = Nothing
Private FSize As Integer
Private CFont As String = Nothing
Private TxtColor As String
Private sqlAdaptor As SqlDataAdapter
Private dt As New DataTable
Private CSizeSql As String = Nothing
Private cmd As Object = Nothing
Private CSizeValue As Double
Private Narrative As String = Nothing
Private CID As Integer
Private Y As Double
Private Verse As String
'Private myBrushes As XBrush
Private connectionString As String = "Data Source=DESKTOP-S7FRNAL\SQLEXPRESS;Initial Catalog=Verses_Find;Integrated Security=True"
Private Sub myBase_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Me.TxtColorTableAdapter.Fill(Me.Verses_Find_ColorDataSet.TxtColor)
Me.CSizeTableAdapter.Fill(Me.Verses_FindDataSet5.CSize)
Dim Print As New frmPrintFrm
Me.TopMost = True
Me.WindowState = FormWindowState.Normal
'cboColor.Items.AddRange(myBrushes)
'cboColor.DisplayMember = "Color"
For Each oFont As FontFamily In FontFamily.Families 'This line populates the font combo with the system installed fonts
cboFont.Items.Add(oFont.Name)
Next
'fetch the XKnownColor values into cboColor
Dim knownColours() As XKnownColor = XColorResourceManager.GetKnownColors(includeTransparent:=False)
cboColor.DataSource = knownColours
cboColor.SelectedIndex = 0
End Sub
'Private Sub cboColor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboColor.SelectedIndexChanged
' SelectedBrushByColor = CType(cboColor.SelectedItem, XBrush)
'End Sub
Private Sub btnPaste_Click(sender As Object, e As EventArgs) Handles btnPaste.Click
' Determine if there is any text in the Clipboard to paste into the text box.
If Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) = True Then
' Determine if any text is selected in the text box.
If txbVerse.SelectionLength > 0 Then
' Ask user if they want to paste over currently selected text.
If MessageBox.Show("Do you want to paste over current selection?",
"Cut Example", MessageBoxButtons.YesNo) = DialogResult.No Then
' Move selection to the point after the current selection and paste.
txbVerse.SelectionStart = txbVerse.SelectionStart + txbVerse.SelectionLength
End If
End If
' Paste current text in Clipboard into text box.
txbVerse.Paste()
End If
End Sub
Private Sub cboCSize_Validating(sender As Object, e As CancelEventArgs) Handles cboCSize.Validating
If cboCSize.SelectedIndex < 0 Then
MessageBox.Show("Please select a value")
Exit Sub
End If
MessageBox.Show("You have selected " & cboCSize.SelectedItem.ToString)
' for test only as in real world
' none of this would be of use.
cboCSize.SelectedIndex = -1
End Sub
Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
FSize = CInt(nudFSize.Value)
End Sub
Private Sub cboFont_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboFont.SelectedIndexChanged
CFont = cboFont.Text
End Sub
Private Sub nudTop_ValueChanged_1(sender As Object, e As EventArgs) Handles nudTop.ValueChanged
boxY = CInt(nudTop.Value)
End Sub
Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
Using connection As New SqlConnection(connectionString), da As New SqlDataAdapter("SELECT CID, BoxX, Cellw, Cellh, ort, Narrative FROM CSize WHERE CID = @CID", connection), dt As New DataTable
connection.Open()
da.SelectCommand.Parameters.AddWithValue("@CID", CSizeValue)
da.Fill(dt)
If dt.Rows.Count > 0 Then
Dim row As DataRow = dt.Rows(0)
printIt(row)
End If
End Using
End Sub
Private Sub printIt(row As DataRow)
Dim ID As Double = CDbl(row("CID"))
Dim X As Double = CDbl(row("BoxX")) * 2.83465
Dim W As Double = CDbl(row("Cellw")) * 2.83465
Dim H As Double = CDbl(row("Cellh")) * 2.83465
Dim O As String = CStr(row("ort"))
Dim N As String = CStr(row("Narrative"))
Dim Y As Double
Dim NL As String = CStr(Chr(13) & Chr(10))
Verse = txbVerse.Text
Replace(Verse, NL, " VBCrLf ")
Dim document As PdfDocument
' Create a new PDF document
document = New PdfDocument()
document.Info.Title = "Created with PDFsharp"
' Create an empty page
Dim page As PdfPage = document.AddPage
If O = "L" Then
page.Orientation = CType(pageOrientation.Landscape, PdfSharp.PageOrientation)
page.Width = XUnit.FromMillimeter(297)
page.Height = XUnit.FromMillimeter(210)
Else
page.Orientation = CType(pageOrientation.Portrait, PdfSharp.PageOrientation)
page.Width = XUnit.FromMillimeter(210)
page.Height = XUnit.FromMillimeter(297)
End If
' create the brush
Dim xClr As XColor = XColor.FromKnownColor(CType(cboColor.SelectedItem, XKnownColor))
Dim brush As XSolidBrush = New XSolidBrush(xClr)
' Draw the text
Y = boxY * 2.834665
Dim gfx As XGraphics
gfx = XGraphics.FromPdfPage(page)
Dim tf As XTextFormatter
tf = New XTextFormatter(gfx)
Dim font As XFont = New XFont(CFont, FSize, XFontStyle.Regular)
Dim rect As XRect
rect = New XRect(X, Y, W, H)
gfx.DrawRectangle(XBrushes.SeaShell, rect)
tf.Alignment = XParagraphAlignment.Center
tf.DrawString(Verse, font, brush, rect, XStringFormat.TopLeft)
' Save the document
Dim filename As String = "verse.pdf"
document.Save(filename)
' ...and start a viewer.
Process.Start(filename)
Me.Close()
End Sub
End Class
Has anyone got any suggestions as to how I can test for no selection in the cboCSize combobox?
-
Jul 9th, 2019, 02:52 AM
#2
Re: Check combobox value is selected
not sure if it is this you are looking for..
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ComboBox1.SelectedItem IsNot Nothing Then
MsgBox(ComboBox1.SelectedItem.ToString())
Else
MsgBox("nothing selected ")
End If
End Sub
to hunt a species to extinction is not logical !
since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.
-
Jul 9th, 2019, 03:19 AM
#3
Re: Check combobox value is selected
If it is your intention to force the user to select an item in that control so that it can be used later then you should handle the Validating event. You can perform whatever validation is appropriate, e.g. check that SelectedItem is not Nothing, and then set e.Cancel to True if it fails. If that control receives focus, the user will not be able to move to another control until it passes validation. When it comes time to use the data, you can call ValidateChildren to force the Validating event to be raised on every control, which ensures that even those that don't receive focus will be validated. You can safely use the data if and only if ValidateChildren returns True.
A lot of people seem to have trouble with the various selection-related properties of a ComboBox or ListBox, mainly because they rely on examples and don't bother to read the relevant documentation. Here's a primer:
DataSource: the list or the source of the list containing the items for the control.
DisplayMember: the name of the property or column from which data should be taken to display for each item.
ValueMember: the name of the property or column from which data should be taken for the value of each item.
SelectedItem: the item from the list that is currently selected.
SelectedIndex: the index of the currently selected item in the list.
SelectedValue: the data from the column or property of the SelectedItem specified by the ValueMember, or the SelectedItem if the ValueMember is not set.
Text: the data (as a String) from the column or property of the SelectedItem specified by the DisplayMember, or the result of calling ToString on the SelectedItem if the DisplayMember is not set.
Note that I said that the DatatSource is "the list or the source of the list". The object you assign must implement either IList or IListSource. If it's the former, it is the list and its items are used. If it's the latter, its GetList method is called to get an IList and the items of that are used. If you bind a DataTable, you're binding an IListSource and its GetList method returns its DefaultView, which is a DataView. Each item in a DataView is a DataRowView, which is why this:
vb.net Code:
MessageBox.Show("You have selected " & cboCSize.SelectedItem.ToString)
displays what it does. If you call ToString on a DataRowView then, as for most types, you get the fully-qualified name of the type. If what you actually want is the text displayed in the control, i.e. the value of the field specified by the DisplayMember from the SelectedItem, then you should be using the Text property of the control. The SelectedValue will give you the field value from the column specified by the ValueMember.
If you want to do something when the selection changes, you can handle either SelectedValueChanged, SelectedIndexChanged or SelectionChangeCommitted. The first two are effectively the same if every item has a different value in the column or property specified by the ValueMember. The last one will only be raised when the user makes a selection via the UI, where the other two will be raised as a result of changes in code too. For instance, when you bind data, the first item is selected by default and, if you want no item to be initially selected, you have to explicitly set the SelectedItem to Nothing or the Selected Index to -1. That would cause two SelectedValueChanged and SelectedIndexChanged events to be raised but no SelectionChangeCommitted events.
-
Jul 9th, 2019, 03:22 AM
#4
Re: Check combobox value is selected
BTW, you should pretty much always set the DisplayMember and ValueMember before setting the DataSource. That's because setting the DataSource will cause the Text and SelectedValue to change and then they will have to be changed again when you set the DisplayMember and ValueMember if you do it that way around. If you set those two properties first, no changes need to be made after setting the DataSource. The only exception to this that I'm aware of is when using a CheckedListBox, which I've seen behave oddly if the DataSource is set last.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|