Menu
  • HOME
  • TAGS

Error in IComparable and in lambda expression

Tag: vb.net

 Private Sub SetStatusText(ByVal text As String)
        If Me.InvokeRequired Then
            Dim a As Action(Of String) = Function(s) SetStatusText(s)  ' <---- ERROR
            Me.Invoke(a, text)
        Else
            txtStatus.Text = text
        End If
    End Sub

ERROR : Expression does not produce a value. Why that error what getting? I was testing a code and that part is lambda expression.

EDIT: Solved the above error by changing the Function to Sub.

==================================================================================

Public MustInherit Class Particle
    Implements IComparable(Of Particle)      ' <----- ERROR

    '...

    Public Function CompareTo(ByVal other As Particle) As Integer
        If other Is Nothing Then
            Throw New ArgumentNullException("other")
        End If

        If Me Is other OrElse Me.Cost = other.Cost Then
            Return 0
        End If

        If Me.Cost > other.Cost Then
            Return 1
        Else
            Return -1
        End If
    End Function

End Class

ERROR: Class 'Particle' must implement 'Function CompareTo(other As ParticleSwarm.Particle) As Integer' for interface 'System.IComparable(Of Particle)'

Here, Particle and ParticleSwarm are different classes. But why that error is appearing?

Best How To :

Your class must Implement the function like this:

Public MustInherit Class Particle
   Implements IComparable(Of Particle) 

Public Property Cost As Integer

Public Function CompareTo(ByVal other As Particle) As Integer Implements IComparable(Of Particle).CompareTo
  If other Is Nothing Then
    Throw New ArgumentNullException("other")
  End If

  If Me Is other OrElse Me.Cost = other.Cost Then
    Return 0
  End If

  If Me.Cost > other.Cost Then
    Return 1
  Else
    Return -1
  End If
End Function

End Class

Then lets simplify how we delegate to UI:

Private Sub SetStatusText(ByVal text As String)
    Me.Invoke(Sub()
                'we are on the UI thread here
                txtStatus.Text = text 
              End Sub)
End Sub

Check if VB.net dataset table exists

vb.net,if-statement,dataset

If you don't know if the DataSet is initialized: If ds IsNot Nothing Then ' ... ' End If If you don't know if it contains four tables(zero based indices): If ds.Tables.Count >= 4 Then ' ... ' End If So the final super safe version is: If ds IsNot...

Gridview items not populating correctly

asp.net,vb.net

Try this vb code behind, then comment out my test Private Sub BindGrid() Dim dt_SQL_Results As New DataTable '' Commenting out to use test data as I have no access to your database 'Dim da As SqlClient.SqlDataAdapter 'Dim strSQL2 As String 'Dim Response As String = "" 'strSQL2 = "SELECT...

Removing Alert When Using DeleteFile API

vb.net,vba,api,delete

There are several SHFILEOPSTRUCT.fFlags options you'll want to consider. You are asking for FOF_NOCONFIRMATION, &H10. You probably want some more, like FOF_ALLOWUNDO, FOF_SILENT, FOF_NOERRORUI, it isn't clear from the question. Check the docs.

Filtering Last Duplicate Occurrence In A Datatable

c#,vb.net

You can use LINQ: DataTable nonDups = parsedDataset.Tables("Detail").AsEnumerable() .GroupBy(row => row.Field<string>("Authorization_ID")) .OrderBy(grp => grp.Key) .Select(grp => grp.Last()) .CopyToDataTable(); This selects the last row of each dup-group. If you want to order the group use grp.OrderBy....

Convert Double from String

asp.net,vb.net,visual-studio-2012,converter

The result isn't wrong, it only has lower precision than you expected. Floating point numbers have a limited precision by design, and you simply can't expect to get a result that is more precise than its limit. You can use a Decimal to get higher precision. In this case it...

How to get substring date (year) using vb.net?

vb.net

Don't use string methods for this, use DateTime.TryParseExact: Dim str = "12/23/2015 12:00:00 AM" Dim dt As DateTime If DateTime.TryParseExact(str, "MM'/'dd'/'yyyy hh:mm:ss tt", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dt) Then Dim yearOnly As String = dt.ToString("yy") ' 15 End If Update: with CultureInfo.InvariantCulture and this format you don't even need to use TryParseExact,...

Regex to check if string is alphanumeric separated by commas or a single alphanumeric string

regex,vb.net

^\d{1,2}[A-Z]?(?:,\d{1,2}[A-Z]?)*$ Try this.See demo. https://regex101.com/r/hI0qP0/25...

Vb.NET Architecture with Option Strict On

vb.net,strict

Try using Generics. Public Interface ICell(Of T) Property Value As T End Interface Public Class cell(Of T) Implements ICell(Of T) Public Property Value As T Implements ICell(Of T).Value Public id As Long Public Formula As String Public ix As Integer Public lev As Integer End Class Then both of these...

Visual Basic Datagrid View change row colour

vb.net,datagridview,datagrid

Is it possible that your datagridview isn't loaded fully when you try to recolor the rows? Since you are setting the datasource, you should put your code that affects the grid after you can make sure that it is finished loading. The column widths change because it is not dependent...

Generic Interface missing implementation

vb.net,interface,implements,generic-interface

You need to indicate on the declaration of the Number function that it is the implementation of the Number Function defined in the Interface Interface IBuilder(Of T) Function Number(ByVal literal As String) As T End Interface Class BracketsBuilder Implements IBuilder(Of String) Public Function Number(number__1 As String) As String Implements IBuilder(Of...

How to pass all value of ListBox Control to a function?

vb.net,listbox

You're passing the contents of a ListBox to a method that is just displaying them in a MsgBox(). There are two approaches you can do to accomplish what I think you're wanting. You can pass ListBox.Items to the method and iterate through each item concatenating them into a single String...

Database only adds (x) amount of rows before error system resources exceeded

database,vb.net,ms-access

You should change your code to something like the following. Note that Everything that returns an object like OleDbConnection, OleDbCommand, or OleDbDataReader is wrapped in a Using block. These objects all implement the IDisposable interface, which means they should be cleaned up as soon as you're done with them. Also...

How to create a top-level folder in my Outlook using vb.net - VB.NET, Outlook 2013

vb.net,outlook,outlook-addin

Top folders (root nodes in the navigation pane) are store. If you need to add a new store in the profile you can use the AddStoreEx method of the Namesapace class which adds a Personal Folders file (.pst) in the specified format to the current profile. See How to: Add...

Comparing arrays with numbers in vb.net

arrays,vb.net

There are a few basic ways of checking for a value in an integer array. The first is to manually search by looping through each value in the array, which may be what you want if you need to do complicated comparisons. Second is the .Contains() method. It is simpler...

Automapper AfterMap function initialising classes

.net,vb.net,automapper

The objects have values in them because they are called after Mapping.Map function is called and that's where actual object with values is passed and then AfterMap function is called and that's how it has the values in it.

Set Label From Thread

vb.net,multithreading,winforms

The reason is that you are referring to the default instance in your second code snippet. Default instances are thread-specific so that second code snippet will create a new instance of the Form1 type rather then use the existing instance. Your Class1 needs a reference to the original instance of...

How to execute four queries once and then check success or failure?

vb.net,windows,visual-studio-2010,ms-access

There a number of other problems with the code (sql injection, sharing a connection among several commands), but here's a step in the right direction: Try conn.Open() cmdfoods.ExecuteNonQuery() cmdservices.ExecuteNonQuery() cmdreservations.ExecuteNonQuery() bill.ExecuteNonQuery() success = True Catch success = False Finally conn.Close() End Try A more-complete solution: Private Function save_to_data() Dim sql...

Invoke form showdialog is not modal

vb.net,multithreading,invoke

in the showDialog, you can set the parent form which causes the child to become modal: Public Class MainForm Dim frm2 As Form2 Private Sub MainForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load frm2 = New Form2() Dim frmHandle As IntPtr = frm2.Handle frm2.Button1.Text = "test" System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf DoSomething), 0)...

Convert date to string format

vb.net,converter

Your approach doesn't work because you are using ToString on a DataColumn which has no such overload like DateTime. That doesn't work anyway. The only way with the DataTable was if you'd add another string-column with the appropriate format in each row. You should instead use the DataGridViewColumn's DefaultCellStyle: InvestorGridView.Columns(1).DefaultCellStyle.Format...

Getting value of Date Time Picker and using BETWEEN for filtering date in Ms Access database

vb.net,ms-access,oledb

Change ..."WHERE today BETWEEN '" & fromdatestring & "' AND '" & todatestring & "'"... To ..."WHERE today >= #" & fromdatestring & "# AND today <= #" & todatestring & "#"... Please note that MS-Access uses #-Delimiters for Date-Values (afaik), this could also be a problem in your query....

vb.net AES decryption returns “data is incomplete block”

vb.net,encryption,cryptography,aes

Despite all comments, I still lack understanding of your intentions. Therefore, the sample code below may not provide what you exactly want, but at least should give an idea how to employ cryptographic functions. Particularly, the most notable difference from your approach is that the encryption key and initialization vector...

VB.net: How to define a namespace where the first segment is NOT the file name?

vb.net

Remove the Root namespace from the project properties: ...

Hashing Password in ASP.NET and Resolving it In SQL Procedure

asp.net,vb.net,stored-procedures,hash,password-protection

A very simple aproach is to use a MD5 hash. public class MD5 { public static string Hash(string message) { // step 1, calculate MD5 hash from input System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(message); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder...

check if a list contains all the element in an array using linq

vb.net,linq

You can use Enumerable.All: dim linqMeddata = From m In medicineDataList Where keys.All(Function(k) m.MedicineData.Contains(k)) Order By m.MedicineName Ascending Select m ...

Retrieve full path of FTP file on drag & drop?

vb.net,ftp

If the data dropped contains a UniformResourceLocator format, you can get the entire URL from that, for example: Private Sub Form1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop If e.Data.GetDataPresent("UniformResourceLocator") Then Dim URL As String = New IO.StreamReader(CType(e.Data.GetData("UniformResourceLocator"), IO.MemoryStream)).ReadToEnd End If End Sub It first checks to see if a...

Syntax error in Insert query in Mysql in VB.Net

mysql,vb.net

you miss the closing parenthesis for the values list: Dim cmd1 As New OdbcCommand("insert into party values('" + pcode_txt.Text + "','" + Trim(UCase(name_txt.Text)) + "','" + Trim(UCase(addr_txt.Text)) + "','" + phone_txt.Text + "','" + combo_route.SelectedItem + "','" + combo_area.SelectedItem + "')", con) My answer is perfectly fit to your question...

WPF style info from external text file

wpf,vb.net,styles

just hold the color values in a config file simple text file will suffice. though you can use VisualStudio Resource file.. file will contain lines in each: item_enum_name item_type item_value for example: main_screen_bg_color Color Black company_logo URI \logos\logo1.jpg and so on.. just load the file parse it and use bind...

Can't output Guid Hashcode

sql,vb.net,guid,hashcode

Well, are you looking for a hashcode like this? "OZVV5TpP4U6wJthaCORZEQ" Then this answer might be useful: Guid g = Guid.NewGuid(); string GuidString = Convert.ToBase64String(g.ToByteArray()); GuidString = GuidString.Replace("=",""); GuidString = GuidString.Replace("+",""); Extracted from here. On the linked post there are many other useful answers. Please take a look! Other useful links:...

How to implement an interface defined in VB.net in VC++/CLI?

c++,vb.net,visual-c++

Looks like you just forgot get(). Proper syntax is: .h file: public ref class ThirdPartyInterfacingBar : Bar { public: property array<Quux^>^ Quuxes { virtual array<Quux^>^ get(); } }; .cpp file: array<Quux^>^ ThirdPartyInterfacingBar::Quuxes::get() { return delegateGetQuuxes(); } ...

Scraping Javascript webpage (script error occurred)

javascript,html,vb.net,web,scrape

You can use WebBrowser.ScriptErrorsSuppressed = true; property. Details: https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed%28v=vs.110%29.aspx...

VBMath using / equivalent in C# [closed]

c#,vb.net

You need to add Microsoft.VisualBasic as a reference to your Project. In your Project in the Solution Explorer right-click References and select "Add Reference". Search for "Microsoft.VisualBasic" in the Framework Tab.

.NET use IIF to assign value to different variables

.net,vb.net,conditional,variable-assignment,iif

What you're asking to do would have been possible in a language that supports pointer types (such as C/C++, or C# in unsafe mode) with dereferencing; VB.NET doesn't do that. The best you got to leverage is local variables, reference types, and (perhaps) ByRef. If it's a Class, its instantiation...

Connecting to database using Windows Athentication

sql-server,vb.net,authentication,connection-string

You need to add Integrated Security=SSPI and remove username and password from the connection string. Dim ConnectionString As String = "Data Source=Server;Initial Catalog=m2mdata02;Integrated Security=SSPI;" ...

Get XML node value when previous node value conditions are true (without looping)

xml,vb.net,linq-to-xml

UPDATE Using an XDocument vs an XmlDocument, I believe this does what you're asking without using loops. This is dependent on the elements being in the order of <PhoneType> <PhonePrimaryYN> <PhoneNumber> string xml = "<?xml version=\"1.0\"?>" + "<Root>" + " <PhoneType dataType=\"string\">" + " <Value>CELL</Value>" + " </PhoneType>" + "...

How do I prevent MySQL Database Injection Attacks using vb.net?

mysql,.net,database,vb.net,sql-injection

MySQLCon.Open() Dim SQLADD As String = "INSERT INTO members(member,gamertag,role) VALUES(@memberToAdd, @memberGamingTag, @memberRole)" COMMAND = New MySqlCommand(SQLADD, MySQLCon) COMMAND.Parameters.AddWithValue("@memberToAdd", memberToAdd.Text) COMMAND.Parameters.AddWithValue("@memberGamingTag", membersGamertag.Text) COMMAND.Parameters.AddWithValue("@memberRole", membersRole.Text) COMMAND.ExecuteNonQuery() memberToAdd.Text = "" membersGamertag.Text = "" membersRole.Text = "" MySQLCon.Close() MySQLCon.Dispose() You don't need to use...

VB.Net DateTime conversion

jquery,vb.net,datetime

System.Globalization.DateTimeFormatInfo.InvariantInfo doesn't contain format pattern dd-MM-yyyy(26-06-2015) From MSDN about InvariantCulture The InvariantCulture property can be used to persist data in a culture-independent format. This provides a known format that does not change For using invariant format in converting string to DateTime your string value must be formatted with one of...

Improve DataGridView rows managing

.net,vb.net,winforms,datagridview,datatable

what can I do to manage a DataSource instead of directlly manage the rows collection of the control A Class and a collection are pretty easy to implement as a DataSource and will also it will be pretty easy to modify your MoveUp/Dn methods for it. Class DGVItem Public Property...

NullReference Error while assiging values of Modeltype in MVC View (Razor)

vb.net,razor,model-view-controller,model

You need to pass the model instance to the view: Function Details() As ActionResult Dim employee As Employee employee = New Employee employee.EmployeeID = 101 Return View(employee) End Function ...

ZipEntry() and converting persian filenames

vb.net,persian,sharpziplib

Try setting IsUnicodeText to true: 'VB.NET Dim newEntry = New ZipEntry(entryName) With { _ Key .DateTime = DateTime.Now, _ Key .Size = size, _ Key .IsUnicodeText = True _ } //C# var newEntry = new ZipEntry(entryName) { DateTime = DateTime.Now, Size = size, IsUnicodeText = true }; ...

How do I use VB.NET to send an email from an Outlook account?

vb.net,email

change the smtpserver from smtp.outlook.com to smtp-mail.outlook.com web.config settings <mailSettings> <smtp deliveryMethod="Network" from="[email protected]"> <network host="smtp-mail.outlook.com" userName="[email protected]" password="passwordhere" port="587" enableSsl="true"/> </smtp> </mailSettings> ...

How to make existing forms deriven from a base form in VB.net

vb.net,inheritance

Since you want to change existing forms to inherit another base class you need to change each form that you want to take effect and change what they inherit. Go to each of your forms designer code class. Inside towards the top you will see the inherits statment. Change what...

Formatting a drive in Visual Basic?

vb.net,format,drive

The problem is that Process.Start does not take command line arguments in the first parameter. Use the overload that allows command line arguments. For example: Process.Start("format.com", "H:"); ...

Where to store an mp4 file in my project?

.net,vb.net,visual-studio,mp4

Try going Project>"Project Name" Properties>Resources>Add Resource>Add Existing File This should add the file into your resources folder. You can then access any file by going My.Resources.Name_Of_Resource...

Return index of word in string

arrays,vb.net,vbscript

Looking at your desired output it seems you want to get the index of word in your string. You can do this by splitting the string to array and then finding the item in an array using method Array.FindIndex: Dim animals = "cat, dog, bird" ' Split string to array...

Use String to find my.resources

vb.net

The Designer creates property getters and setters for the images etc you add to Resources. So, for an image named dicedark1.jpg, it creates: Friend ReadOnly Property diceDark1() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("diceDark1", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property You can see these in Resources.Designer.vb. So...

Get List of Elements in Tree with specific Field Value

vb.net,linq,properties,interface

If i have understood it correctly you want to get all selected parents and all selected children. You could use a recursive method: Public ReadOnly Property checkedList As List(Of TreeSelectorAttributes) Get Return rootList.Where(Function(t) t.SelectedInTreeSelector). SelectMany(Function(root) GetSelectedChildren(root)). ToList() End Get End Property Function GetSelectedChildren(root As TreeSelectorAttributes, Optional includeRoot As Boolean =...

how can i use parameters to avoid sql attacks

sql,vb.net

I think the only solution is create a new function and gradually migrate to it. Public Function ExecuteQueryReturnDS(ByVal cmdQuery As SqlCommand) As DataSet Try Dim ds As New DataSet Using sqlCon As New SqlConnection(connStr) cmdQuery.Connection = sqlCon Dim sqlAda As New SqlDataAdapter(cmdQuery) sqlAda.Fill(ds) End Using Return ds Catch ex As...

Custom drawing using System.Windows.Forms.BorderStyle?

c#,.net,vb.net,winforms,custom-controls

If you want to get results that reliably look like the BorderStyles on the machine you should make use of the methods of the ControlPaint object. For testing let's do it ouside of a Paint event: Panel somePanel = panel1; using (Graphics G = somePanel.CreateGraphics()) { G.FillRectangle(SystemBrushes.Window, new Rectangle(11, 11,...

Filter bind source

c#,regex,vb.net

You need to build your query to look like this: Name LIKE '%tom%' AND Name LIKE '%jack%' .... So take your input, split it up, project it to a new string and join them all together with AND: bndSourceGrid.Filter = string.Join(" AND ", cboName.Text .Split(' ') .Select(s => string.Format("Name LIKE...

Outlook 2013 Cannot create ActiveX component from ASP.NET Application

asp.net,vb.net,outlook,office-interop

No Office app (including Outlook) can run in a service (such as IIS). Your options are Extended MAPI (C++ or Delphi only), Redemption (which wraps Extended MAPI and can be accessed from any language, including C#), EWS (Exchange only) or straight SMTP.