I need code behind version of Image source binding - xaml

code behind.
Class MainWindow
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
Dim myBinding As New Binding
With myBinding
.Source = Image1.Source
.Mode = BindingMode.Default
.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
End With
End Sub
End Class
So, why myBinding is not working in code behind?

In order to have the Binding updated when its source property changes, you need to specify a Path:
Dim myBinding As New Binding
With myBinding
.Source = Image1
.Path = new PropertyPath("Source")
End With
Besides that, setting BindingMode.Default and UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged is pointless. It has no effect on this Binding.

Related

Unable to load data on Select method of Datatable

Trying to populate a set of data from datatable to Combobox on the basis of text entered in Combobox. But getting a System.Data.DataRow error in the Select method of datatable.
Following is the code which binds the datatable on Form Load and rebinds data on the call of Search method.
Note that the search has to be on Tab press not AutoComplete
Imports System.Data.SqlClient
Public Class Form1
Dim connection As SqlConnection = New SqlConnection()
Dim table As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadComboBox()
End Sub
Private Sub LoadComboBox()
Dim adp As SqlDataAdapter = New SqlDataAdapter("select stage from sample", connection)
adp.Fill(table)
ComboBox1.DataSource = New BindingSource(table, Nothing)
ComboBox1.DisplayMember = "stage"
End Sub
Private Sub Search()
Dim filteredTable As New DataTable
Dim filterRow As DataRow()
Dim str As String = ComboBox1.Text.Trim
filterRow = table.Select("stage like '%" & ComboBox1.Text.ToString & "%'")
'**Error in above table(datatable)**
For Each rw As DataRow In filterRow
filteredTable.ImportRow(rw)
Next
ComboBox1.DataSource = New BindingSource(filteredTable, Nothing)
ComboBox1.DisplayMember = "stage"
End Sub
Private Sub ComboBox1_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles ComboBox1.PreviewKeyDown
If e.KeyCode = Keys.Tab Then
Search()
End If
End Sub
End Class
in your binding to combo box you have a data table already why are you using a binding source
why not just say ComboBox1.DataSource = filteredTable
Also i would advice you to use Key Value Pair rather than using Like easier binding
Like is regex search at SQL Server this is killing your Database and you are creating overhead over nothing
Key | Value >>
ID | Name
so taking this from another stack over flow for fast reference
gridview bind dropdownlist to List<keyvaluePair<int, string>>
you can bind a dictionary , datatable , dataview does not matter.
if you want to get text just say your dropdown.text for the ID value dropdown.value if you want to do something later to in the database.
You can make your drop down read only and when user types basically what he is typing is filtering according to what you have binded that way your text search can be made
var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Home");
dictionary.Add(2, "Work");
dictionary.Add(3, "Mobile");
dictionary.Add(4, "Fax");
dropDown.DataTextField = "Value";
dropDown.DataValueField = "Key";
dropDown.DataSource = dictionary; //Dictionary<int, string>
dropDown.DataBind();
Tried it with a bit of Linq.
Private Sub Search()
Dim filteredTable As New DataTable
Dim str As String = ComboBox1.Text.Trim
Dim filterRows = (From row As DataRow In Table.AsEnumerable
Where row.Field(Of String)("Name").Contains(ComboBox1.Text)
Select row.Field(Of String)("Name")).ToList
ComboBox1.DataSource = filterRows
End Sub
Just substitute your column name for "Name"

How to set the public property of a class to an instance of another class?

I'm trying to access a WCF WebService using VB.Net. So far I've succesfully set up the connected service via WSDL and exposed the methods and classes from the service.
The error I'm stuck at is
BC30311 - The value of type 'CatalogItemUpdateCommand' cannot be converted to 'CatalogItemUpdateCommand()'.
I have a class CatalogUpdateRequest, with a public property Items() set to another class, named CatalogItemUpdateCommand.
The code for CatalogItemUpdateCommand class:
Partial Public Class CatalogItemUpdateCommand
Inherits Object
Implements System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged
Private CatalogItemCodeField As String
Private PriceField As Decimal
Public Property CatalogItemCode() As String
Get
Return Me.CatalogItemCodeField
End Get
Set
If (Object.ReferenceEquals(Me.CatalogItemCodeField, value) <> true) Then
Me.CatalogItemCodeField = value
Me.RaisePropertyChanged("CatalogItemCode")
End If
End Set
End Property
Public Property Price() As Decimal
Get
Return Me.PriceField
End Get
Set
If (Me.PriceField.Equals(value) <> true) Then
Me.PriceField = value
Me.RaisePropertyChanged("Price")
End If
End Set
End Property
The code for CatalogUpdateRequest class:
Partial Public Class CatalogUpdateRequest
Inherits Object
Implements System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged
Private ItemsField() As SEAP.CatalogItemUpdateCommand
Public Property Items() As SEAP.CatalogItemUpdateCommand()
Get
Return Me.ItemsField
End Get
Set
If (Object.ReferenceEquals(Me.ItemsField, Value) <> True) Then
Me.ItemsField = Value
Me.RaisePropertyChanged("Items")
End If
End Set
End Property
The code to call the service:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim items_to_update As CatalogItemUpdateCommand = New CatalogItemUpdateCommand
Dim items_update_request As CatalogUpdateRequest = New CatalogUpdateRequest With {.Items = items_to_update}
Dim final_update_request As Catalog_UpdateItemsRequest = New Catalog_UpdateItemsRequest(request:=items_update_request)
Try
'Assign values to parameters
items_to_update.CatalogItemCode = "00011587"
items_to_update.InStock = "true"
items_to_update.Price = 7.53
items_to_update.DoUpdatePrice = "true"
items_to_update.DoUpdateStock = "true"
items_to_update.DoPublish = "true"
items_to_update.DoProcessPublish = "true"
'Call the Catalog_UpdateItems method from the interface
seapclient.Catalog_UpdateItems(final_update_request)
Catch wex As WebException
End Try
End Sub
This line generates the error mentioned above:
Dim items_update_request As CatalogUpdateRequest = New CatalogUpdateRequest With {.Items = items_to_update}
I get the same error if I state:
items_update_request.Items = items_to_update
inside the Try... End Try block
BC30311 - The value of type 'CatalogItemUpdateCommand' cannot be converted to 'CatalogItemUpdateCommand()'.
It seems to be a declaration issue. Any suggestions?
Later edit: Thanks, guys, declaring ar array() seemed to have done the trick!
New code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim items_to_update(1) As CatalogItemUpdateCommand
Dim items_update_request As CatalogUpdateRequest = New CatalogUpdateRequest() ' With {.Items = items_to_update}
Dim final_update_request As Catalog_UpdateItemsRequest = New Catalog_UpdateItemsRequest()
Dim update_response As Catalog_UpdateItemsResponse
Dim update_result As CatalogImportResponse
Try
'Assign values to parameters
items_to_update(0) = New CatalogItemUpdateCommand With {.CatalogItemCode = "00011587", .Price = 7.54, .DoUpdatePrice = "true", .InStock = "true", .DoPublish = "true", .DoProcessPublish = "true"}
'
items_update_request.Items = items_to_update
final_update_request.request = items_update_request
'Call the Catalog_UpdateItems method from the interface
update_response = seapclient.Catalog_UpdateItems(final_update_request)
txtResponse.Text = "Status: " & update_response.Catalog_UpdateItemsResult.Status.ToString & "Updated: " & update_response.Catalog_UpdateItemsResult.Updated.ToString() & "Failed: " & update_response.Catalog_UpdateItemsResult.Failed.ToString()
Catch wex As WebException
End Try
End Sub
Moving on to assigning values to array from SQL Database, keep in touch...

Resize ToolStrip Button Image programatically at startup via toolstrip.ImageScalingSize

So I've read around this and will provide relevant properties at the end.
I'm looking to store a custom ToolStrip button image size in my.settings and load them at startup, changing them to a user set size.. The code I run at startup is:
Dim tss As New List(Of ToolStrip)
tss = GetAllControls(Me).OfType(Of ToolStrip)().ToList
For Each ts In tss
ts.BackColor = My.Settings.ToolStripBGColor
ts.ImageScalingSize = New Size(My.Settings.ToolStripImgScalingSize, My.Settings.ToolStripImgScalingSize)
ts.ResumeLayout()
ts.Invalidate()
ts.Refresh()
Next
ToolStripContainer.Invalidate()
ToolStripContainer.Refresh()
This does change the properties of all of the ToolStips. However, the images initially display at the default 16x16 UNTIL I drag them into another area of the ToolStripContainer. It then resizes correctly. This tends to imply to me that it's something to so with the draw of these containers/controls (hence the blanket bombing of .invalidate, .resumelayout and .refresh!)
Regarding proprieties, the relevant ones within designer view:
ToolStripButton
.autosize = true
.imagescaling = SizeToFit
ToolStrip
.autosize = true
.imagesclaing = 16,16 (later modified by code)
ToolStripContainer
couldn't see any that would effect this!??
This is one of those where you go round in circles for half a day over what essentially could be due to a janky aspect of .net! Could be me though...
Getting this to work with AutoSize=True is always a bit confusing. I've found that if you set it to False with layout suspended and then set it to True with layout enabled, that you can get the desired effect.
That description is probably clear as mud, so here is the code pattern.
With ToolStrip1
.SuspendLayout()
.AutoSize = False
.ImageScalingSize = New Size(40, 40)
.ResumeLayout()
.AutoSize = True
End With
Imports System.Drawing : Imports Microsoft.VisualBasic
Imports Microsoft.Win32 : Imports System
Imports System.IO : Imports System.Windows.Forms
Public Class Form1
Inherits Form
Private toolStripItem1 As ToolStripButton
Private toolStrip1 As ToolStrip
Public Sub New()
toolStrip1 = New System.Windows.Forms.ToolStrip()
toolStrip1.Size = New System.Drawing.Size(580,40)
toolStrip1.BackColor = System.Drawing.Color.MistyRose
toolStrip1.AutoSize = True
toolStripItem1 = New System.Windows.Forms.ToolStripButton()
toolStrip1.SuspendLayout()
Me.SuspendLayout()
toolStrip1.Items.AddRange(New System.Windows.Forms.ToolStripButton() _
{toolStripItem1})
toolStrip1.Location = New System.Drawing.Point(0, 0)
toolStrip1.Name = "toolStrip1"
toolStripItem1.AutoSize = False
toolStripItem1.Size = New System.Drawing.Size(110,95)
toolStripItem1.BackgroundImage = Image.FromFile("D:\Book4\Resources\icos\CUT.png")
toolStripItem1.Name = "toolStripItem1"
toolStripItem1.Text = "Cut"
toolStripItem1.Font = New System.Drawing.Font("Segoe UI", 16.0!, _
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, _
CType(0, Byte))
toolStripItem1.TextAlign = System.Drawing.ContentAlignment.TopCenter
AddHandler Me.toolStripItem1.Click, New System.EventHandler _
(AddressOf Me.toolStripItem1_Click)
Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(1500,900)
Me.BackColor = ColorTranslator.FromHtml("#808080")
Me.Controls.Add(Me.toolStrip1)
Me.Name = "Form1"
toolStrip1.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Public Sub Form1_Loaded(sender As Object, e As EventArgs) _
Handles MyBase.Load
Try
Dim ico As New System.Drawing.Icon("D:\Resources\icos\kvr.ico")
Me.Icon = ico
Catch ex As Exception
End Try
End Sub
Public Shared Sub Main()
Dim form1 As Form1 = New Form1()
form1.ShowDialog()
End Sub
Private Sub toolStripItem1_Click(ByVal sender As Object,ByVal e As EventArgs)
System.Windows.Forms.MessageBox.Show("Successfully enlarged ToolStripButtonImage size")
End Sub
End Class

Using Generic List(Of Form), Trouble gathering Object's Name Property

I have been very interested as of late in interfaces and the ability to further customize them beyond using them in their default state.
I have been researching IList(of T) specifically. The advantages of using generic lists as opposed to ArrayLists has astounded me. Here is a picture of a test. This is the site that goes into further explanation about the Test.
So, naturally I wanted to experiment. When I first iterate through the list with the ForNext method the code works fine. The second time I can't access the name of the Form in the list because it is disposed. Anyone have any insight how I can access the forms properties in the list.
Public Class frmMain
Dim Cabinet As List(Of Form) = New List(Of Form)
Dim FormA As New Form1
Dim FormB As New Form2
Dim FormC As New Form3
Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles _Me.Load
Cabinet.Add(FormA)
Cabinet.Add(FormB)
Cabinet.Add(FormC)
End Sub
Sub displayForm(ByVal aForm As Form)
Dim myFormName As String = ""
Stopwatch.Start()
If aForm.IsDisposed = False Then
aForm.Show()
Else
myFormName = aForm.(How do I access this objects Name?)
aForm = New Form '<----- I would rather simply use aForm = New(aForm)
aForm.Name = myFormName
aForm.Show()
End If
Stopwatch.Stop()
Dim RealResult As Decimal = (Stopwatch.ElapsedMilliseconds / 1000)
Debug.WriteLine(RealResult)
Stopwatch.Reset()
End Sub
Private Sub btnForEach_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnForEach.Click
'Dim instance as List
'Dim action as Action(of T)
'instance.ForEach(action)
'action = delegate to a method that performs an action on the object passeed to it
Cabinet.ForEach(AddressOf displayForm)
End Sub
I really don't understand why if VB knows that this is a Generic list, which means it is knowledgable of the list's type, and the objects are all constrained to be forms; why I can't call a constructor on an item in the list. Ex. aForm = New aForm or aForm = New Cabinet.aForm
Tear this one open for me somebody. Thanks.
You can't construct a new instance of "aForm" because its isn't a type, it is an instance of type Form.
If you wanted to prevent the ObjectDisposedException, you could hide the form instead of closing it. Place the following code in each forms code behind:
Public Class Form1
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim form = CType(sender, Form)
form.Visible = False
e.Cancel = True
End Sub
End Class
This is a bit hacky, however, but then you wouldn't need the code in the Else block.
Edit
You could try this instead:
Private Sub displayForm(ByVal aForm As Form)
Dim indexOfCab As Integer = Cabinet.IndexOf(aForm)
If indexOfCab <> -1 Then
If aForm.IsDisposed Then
aForm = CreateForm(aForm.GetType())
Cabinet(indexOfCab) = aForm
End If
aForm.Show()
End If
End Sub
Private Shared Function CreateForm(formType As Type) As Form
Return CType(Activator.CreateInstance(formType), Form)
End Function
You wouldn't need that big Select statement.
This is the only way I have been able to get it to work. I feel it is extremely inefficient however, and hope someone can set me on a path to a better way to do this. The below is what I'm trying to achieve.
Sub displayForm(ByVal aForm As Form)
Dim myFormName As String = ""
If Cabinet.Contains(aForm) Then
Dim indexOfCab As Integer = Cabinet.IndexOf(aForm)
Dim ObjForm As Form = Cabinet.Item(indexOfCab)
If aForm.IsDisposed Then
Select Case indexOfCab
Case 0
aForm = Nothing
aForm = New Form1
Cabinet.Item(indexOfCab) = aForm
Cabinet.Item(indexOfCab).Show()
Case 1
aForm = Nothing
aForm = New Form2
Cabinet.Item(indexOfCab) = aForm
aForm.Show()
Case 2
aForm = Nothing
aForm = New Form3
Cabinet.Item(indexOfCab) = aForm
Cabinet.Item(indexOfCab).Show()
End Select
Else
Cabinet.Item(indexOfCab).Show()
End If
End If
End Sub

DigitalPersona Serialization

Meet a little problem here which i do not know where the wrong the code
Private Sub SimpleButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton1.Click
Dim str As New MemoryStream
Dim Serializetemplate As New DPFP.Template
Serializetemplate.Serialize(str)
Dim serializedTemplate As Byte() = str.ToArray()
'save to database
opencon1()
Dim cmd As MySql.Data.MySqlClient.MySqlCommand
cmd = New MySql.Data.MySqlClient.MySqlCommand
cmd.Parameters.AddWithValue("?imagedata", serializedTemplate)
cmd.Parameters.AddWithValue("?userid", txtEmpid.Text)
cmd.CommandText = "UPDATE master SET fp1=?imagedata WHERE userid=?userid"
cmd.CommandType = CommandType.Text
cmd.Connection = con1
cmd.ExecuteNonQuery()
End Sub
I get an error at Serializetemplate.Serialize(str) with the error message Bad Serialization
Anyone ever meet this error and solve it?
Joseph I'm not very good with VB but as far as I can see you're declaring a new DPFP.Template and then serializing it into your memory stream. Why are you doing this?
Given that you're enrolling or verifying the SDK'll give you the template on the event handler
private void Enrolled(object Control, int Finger, DPFP.Template Template, ref DPFP.Gui.EventHandlerStatus Status)
{
if (Status == DPFP.Gui.EventHandlerStatus.Success)
{
// Here you can use the template as Template.Bytes
}
}
The template is already serialized as byte[].
I think that given that you just create the template (blank) then when you try to serialize it throws the exception.