Visual Basic.NET

93K

Solutions

24K

Contributors

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to  Visual Basic pre-2002, it is not the same technology,

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi

I have an ASP.net button that runs code that checks the cell backcolors.
The problem is that none of the cell colors are detected as blue because they were cleared on a postback before
the code runs. How do I run the VB.net code before the colors are cleared?
    Protected Sub btnSaveChanges_Click(sender As Object, e As EventArgs) Handles btnSaveChanges.Click

        Try

            Me.lblSaveChangesError.Text = ""
            Dim oDateList As String = TryCast(Session("oDateList"), String)
            Dim arrDates As Object = Split(oDateList, ",")
            Dim oNumberDays As Integer = UBound(arrDates) + 1
            Dim oTextColumnName As String
            Dim oColumnIndex As Integer
            Dim oCellValue As String
            Dim oToolTip As String
            Dim T As TextBox
            Dim oBackColor As System.Drawing.Color

            For r As Integer = 0 To Me.GridView1.Rows.Count - 1
                For d As Integer = 1 To oNumberDays
                    oColumnIndex = d + 1 'First column index is 2
                    oBackColor = Me.GridView1.Rows(r).Cells(oColumnIndex).BackColor
                    If oBackColor = System.Drawing.Color.Blue Then
                        'so if cell ccolor is blue....
                        oTextColumnName = "D" & CStr(d)
                        T = Me.GridView1.Rows(r).FindControl(oTextColumnName)
                        oCellValue = T.Text
                        oToolTip = T.ToolTip

                   

Open in new window

0
OWASP Proactive Controls
LVL 13
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

In my ASP.net GridView I previously used the following code to make cells clickable.
How can I use similar code to  change the cells color on mouseout

    Private Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowCreated


        If e.Row.RowType = DataControlRowType.DataRow Then
            'Following link shows how cells are made clickable
            '//https://stackoverflow.com/questions/31202877/get-clicked-cell-index-in-gridview-not-datagridview-asp-net
            For i As Integer = 0 To e.Row.Cells.Count - 1
                Dim cell As TableCell = e.Row.Cells(i)
                cell.Attributes("onmouseover") = "this.style.cursor='pointer';this.style.textDecoration='underline';"
                cell.Attributes("onmouseout") = "this.style.textDecoration='none';"
                'cell.ToolTip = "You can click this cell"
                cell.Attributes("onclick") = String.Format("document.getElementById('{0}').value = {1}; {2}", SelectedGridCellIndex.ClientID, i, Page.ClientScript.GetPostBackClientHyperlink(CType(sender, GridView), String.Format("Select${0}", e.Row.RowIndex)))
            Next
        End If


    End Sub

Open in new window

0
Hi

I use the following VB.net code to populate textbox cells in my ASP.net GridView columns.
I also need to store a unique ID value for each cell. I am currently using the ToolTip to do this
Is there another way that I can embed my ID value in each cell?

    Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound

        Dim oColIndex As Integer
        Dim oDate As String
        Dim oEachDate As Date
        Dim oTemplateColumn As String
        Dim oDateList As String = TryCast(Session("oDateList"), String)
       Dim oLineID_PlusDate As String 'this is eg Line ID 19 apr 2019
        Dim arrDates As Object = Split(oDateList, ",")
        For i As Integer = 0 To UBound(arrDates)
            oColIndex = i + 2
            oTemplateColumn = "D" & CStr(i + 1)
            oEachDate = CDate(arrDates(i))
            oDate = oEachDate.ToString("dd MMM yyyy")
            Me.GridView1.Columns(oColIndex).Visible = True
            If e.Row.RowType = DataControlRowType.Header Then
                Me.GridView1.Columns(oColIndex).HeaderText = oDate
            End If

            'Me.GridView1.Columns(2).Visible = True
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim D1 As TextBox = CType(e.Row.FindControl(oTemplateColumn), TextBox)
                If Not IsDBNull(e.Row.DataItem(oDate)) Then
                    D1.Text = e.Row.DataItem(oDate)
                End If
 …
0
Hi.  I am trying to change the header text of template columns in a GridView in ASP.net using the following VB.net code but for some reason the
headers are not changing

    Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
        For i As Integer = 0 To UBound(arrDates)
            oColIndex = i + 2
            oTemplateColumn = "D" & CStr(i + 1)
            oEachDate = CDate(arrDates(i))
            oDate = oEachDate.ToString("dd MMM yyyy")
            Me.GridView1.Columns(oColIndex).Visible = True
            If e.Row.RowType = DataControlRowType.Header Then
                Me.GridView1.Columns(oColIndex).HeaderText = oDate
            End If
        End if
Ebd Sub

Open in new window

0
Hi
I have the following two ASP.net GridVidew template columns
The first binds to EmloyeeName but the second has to bind to various
other columns. What VB.net code would I use to bind that column programatically?

              <asp:TemplateField HeaderText="Employee Name" Visible="true">
                           <ItemTemplate>
                                <asp:Label ID="lblEmployeeName" runat="server" Text='<%# Bind("EmployeeName")%>' Visible="true"></asp:Label>
                           </ItemTemplate>
                      </asp:TemplateField>
                      <asp:TemplateField HeaderText="T2" Visible="true">
                           <ItemTemplate>
                                <asp:Textbox ID="T2" runat="server"  Visible="true" Width="10"></asp:Textbox>
                           </ItemTemplate>
                      </asp:TemplateField>

Open in new window

0
HI

I am using the following VB.net code to add an identity column. How do I set it as the primary key too?

            Dim dtNew As New DataTable()
            'Add columns to DataTable.
            '------------ ID Column -------------
            dtNew.Columns.Add("ID")
            'Set AutoIncrement True for the First Column.
            dtNew.Columns("ID").AutoIncrement = True
            'Set the Starting or Seed value.
            dtNew.Columns("ID").AutoIncrementSeed = 1

Open in new window

0
Hi. In my ASP.net project I need to add a handler as follows.  Where should I put this? In the page load event?

' Hook up RowIslandDataBound event
AddHandler Me.WebHierarchicalDataGrid1.RowIslandDataBound, AddressOf WebHierarchicalDataGrid1_RowIslandDataBound
Protected Sub WebHierarchicalDataGrid1_RowIslandDataBound(ByVal sender As Object, ByVal e As RowIslandEventArgs) Handles WebHierarchicalDataGrid1.RowIslandDataBound
   If e.RowIsland.DataMember = "SqlDataSource1_DefaultView" Then
      ' Access a PARENT cell value
      Dim cellValue As String = e.RowIsland.Rows(0).Items(1).Value.ToString()
   End If
End Sub

Open in new window

0
Hello,

I have a warning like below. Each excel cells has an small green sign at their top left corner.
When clicking on it it shows Numbers stored as text.


problem1.jpgproblem2.jpg
I didn't want to get this warning and small green signs and keep all of them as text how can i do it ?

My code is also like below.

        Public Shared Function WriteCheckSheetDgvToExcel(ByVal objSheet As Excel.IXLWorksheet, ByVal dgv As DataGridView) As Boolean
            Try
                For colHeader As Integer = 1 To dgv.ColumnCount Step 1
                    objSheet.Cell(1, colHeader).Value = dgv.Columns(colHeader - 1).HeaderText
                Next
                For col As Integer = 0 To dgv.ColumnCount - 1 Step 1
                    For row = 0 To dgv.Rows.Count - 1
                        objSheet.Cell(row + 2, col + 1).SetValue(Convert.ToString(dgv.Rows(row).Cells(col).Value)).SetDataType(Excel.XLDataType.Text)
                        If dgv.Rows(row).Cells(col).GetType = GetType(DataGridViewComboBoxCell) Then
                            Dim cboCell As New DataGridViewComboBoxCell
                            cboCell = CType(dgv.Rows(row).Cells(col), DataGridViewComboBoxCell)
                            If cboCell.Items.Count > 1 Then
                                objSheet.Cell(row + 2, col + 1).DataValidation.List(ComboboxItemsToList(cboCell), True)
                            End If
                        End If
                    

Open in new window

0
I've a below code to filtering my files but it's a bit hard way because i declare it in if end if loop and other variables which using it cannot seee it i wonder is there any possible way to simplify this;

Any help would be grateful. Thank you.

                If My.Settings.user_build__list_prt = False Then

                    Dim getHp = From group In subvarGroupList
                                Where group.fullName.EndsWith(My.Settings.str_elem__subvar_grpname_hp) AndAlso Path.GetFileNameWithoutExtension(group.origin).StartsWith("prt_") = My.Settings.user_build__list_prt
                                Select group
                Else
                    Dim getHp = From group In subvarGroupList
                                Where group.fullName.EndsWith(My.Settings.str_elem__subvar_grpname_hp)
                                Select group
                End If

Open in new window

0
Hello I'm using below code to get checked items but it gives "Object reference not set to instance of object" error. Does anyone knows how can i fix that?

            Try
                If BuildSetLabelID.ShowDialog() = DialogResult.OK Then
                    Dim id As String = BuildSetLabelID.cboSetID.SelectedItem.ToString
                    For Each i As ListViewItem In BuildSetLabelID.lstDataGridViews.CheckedItems
                        MsgBox(i.Name)
                    Next
                 End If
            Catch ex As Exception
                Tools.OutputLog.Print(Tools.OutputLog.Type.ERR, ex.Message)
            End Try

Open in new window


and this is entire class of dialog

Public Class BuildSetLabelID
    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.Close()
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click

        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub DialogLoad(sender As Object, e As EventArgs) Handles MyBase.Load
        lstDataGridViews.Clear()
        FindDataGridViews(GUI.pnlModuleBuildContent)
    End Sub
    Private Sub FindDataGridViews(ByVal control As Control)
        If control.HasChildren Then
            For Each childControl As Control In 

Open in new window

0
CompTIA Cloud+
LVL 13
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Within a VB.net program, I want to check if a user is in a group.  The code I have only works if I am joined to the domain (see below). I either need to modify this code to accept credentials (username/password) or I need different code.  I tried many different versions of code (most using LDAP), but can't get anything to work running from a PC that is not yet joined to the domain.
    Public Function IsInGroup2(ByVal objectName As String, groupName As String) As Boolean
        Try
            Return New WindowsPrincipal(New WindowsIdentity(objectName)).IsInRole(groupName)
        Catch ex As Exception
        End Try
        Return False
    End Function

Open in new window

0
Hi

I have a datatable that I need to extract a value from.
If I used SQL the query would be "Select WorkType From Employee Hours Where LineID = 12"

What VB.net code would I use to extract this value from a datatable called "dt".

Thanks
0
I want to add printing barcode functionality in my windows form, can anyone help me finding a free control to perform the basic functions of creating barcode in my forms.
All what I need is to show the barcode into a picturebox for given code, the barcode type is not important.... just basic functionality
I am using vb.net.

If you can provide me with code to build this functionality myself.... That is really appreciated. Thanks for the help
0
Hi

I am getting the error below in trying to get a GridView cell and row index using the following. I got this from the post https://forums.asp.net/t/1639326.aspx?Gridview+Cell+Click+Event+Get+Row+Column+Index
1. Javascript
// Javascript - get cell and row index
function cellClicked(row, column)
{
         document.getElementById('<% = hfAction.ClientID %>').value = "CellClick";
         document.getElementById('<% = hfRow.ClientID %>').value = row;
         document.getElementById('<% = hfColumn.ClientID %>').value = column;
         form1.submit();
}

Open in new window


2. VB.net
    Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound


        If e.Row.RowType = DataControlRowType.DataRow Then
            '//Following code used to change row color on mouseover
            'e.Row.Attributes.Add("onmouseover", "this.originalcolor=this.style.backgroundColor;" & " this.style.backgroundColor='#ccdfdf';")
            'e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalcolor;")
            For columnIndex As Integer = 1 To e.Row.Cells.Count - 1
                '//https://forums.asp.net/t/1639326.aspx?Gridview+Cell+Click+Event+Get+Row+Column+Index
                e.Row.Cells(columnIndex).Attributes.Add("onclick", String.Format("cellClicked({0},{1});", e.Row.RowIndex, columnIndex))
                e.Row.Cells(columnIndex).Attributes.Add("onclick", "alert(""CellClicked"");")
            Next

        End If

    End Sub

Open in new window



Open in new window

0
Hi. I am fairly new to JavaScript. How do I step through JavaScript and put line breaks in.
My code resides in an ASP.net VB.net web app

<script type="text/javascript">
        //variable that will store the id of the last clicked row
        var previousRow;
        
        function ChangeRowColor(row)
        {
            //If last clicked row and the current clicked row are same
            if (previousRow == row)
                return;//do nothing
            //If there is row clicked earlier
            else if (previousRow != null)
                //change the color of the previous row back to white
                document.getElementById(previousRow).style.backgroundColor = "#ffffff";
            
            //change the color of the current row to light yellow
 
            document.getElementById(row).style.backgroundColor = "#ffffda";            
            //assign the current row id to the previous row id 
            //for next row to be clicked
            previousRow = row;
        }
     </script>

Open in new window

0
Hi,

I am programming in Visual Studio 2015 a Visual Basic project.

Goal is to write errors to event log. I have tried several examples like mentioned in:
https://support.microsoft.com/nl-nl/help/301279/how-to-write-to-an-event-log-by-using-visual-basic-net-or-visual-basic

It is not working like I expect it to work allready at the start.

Dim sSource As String
Dim sLog As String
Dim sEvent As String
Dim sMachine as String

sSource = "My Application"
sLog = "Application"
sEvent = "Error description"
sMachine = environment.machinename.tostring

If Not EventLog.SourceExists(sSource, sMachine) Then
            EventLog.CreateEventSource(sSource, sLog, sMachine)
End If

Open in new window


When firing this code I get the error:

Unkonown error: 5
The source was not found, but some or all event logs could not be searched. To create the source, you need permission to read all event logs to make sure that the new source name is unique. The inaccessable logs: Security.

This happens immidiately when code reaches:
If Not EventLog.SourceExists(sSource, sMachine) Then

Open in new window


Anybody any idea how to fix this? Lots of articles on the internet but all regarding older versions of Visual Studio.

The exact code now is:
[code]Sub log_event(ByRef sEvent As String)

        Dim aLog As EventLog
        Dim myLog As New EventLog
        

Open in new window

0
I have a slideshow app that when a button is pressed it will cycle through  5 images.
I would like to be able to remove the need for a button and the slideshow just to start when the app is loaded.

Please see my code bellow:
ImageSlideshow.xaml
<Page
    x:Class="TimerInWindowsStoreApps.ImageSlideShow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TimerInWindowsStoreApps"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid x:Name="LayoutRoot" Background="Black">
        <Grid Margin="0,50">
            <Grid.RowDefinitions>
                <RowDefinition Height="410"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
            </Grid.RowDefinitions>
            <StackPanel Grid.Row="0" Margin="0,0,0,10" Grid.RowSpan="2">
                <Border BorderBrush="Black" Grid.Row="0" BorderThickness="1" Width="1080">
                    <Image x:Name="ImageSource" AutomationProperties.Name="ImageSource" VerticalAlignment="Center" Stretch="Fill" Height="auto" Width="auto">
                    </Image>
                </Border>
            </StackPanel>
            <Grid x:Name="Input" Grid.Row="1" Margin="0,10,0,0" VerticalAlignment="Top" HorizontalAlignment="Center">
                <StackPanel 

Open in new window

0
I am developing an electronic medical record (EMR) system.

I am designing and implementing the backend APIs using WCF.

Now, I have two system actors: secretary and doctor.

I designed the services according to the actor he/she is concerned.

[ServiceContract]
public interface ISecretaryService
{
}

[ServiceContract]
public interface IDoctorService : ISecretaryService
{
//the doctor has the functions of secretary in case she was absent!
}

Open in new window


The problem is I have duplicate code which is the implementation of the ISecretary contract in doctor service.
0
ASP.NET + JavaScript + Client Side CustomValidators - I Have Question  

I have a ASP.Net standard Web Form working on validation - www.enflow.com/CC/P1/EE.aspx

Click The Other Button and a text box will appear... do not put any text into that textbox

Now Click Submit Button and you will CORRECTLY get a Validation Summary Msg saying missing text for the Describe Other textbox

But if you put text into that textbox and click submit button again then you will keep getting the same validation error...

I think i am missing something simple in JScript ClientSide Validation Call or ??


Here is JScript for Client JS Call...
      function valOther(sender, args) {
          if (document.getElementById("<%=Other.ClientID %>").checked == true) {
              if (document.getElementById("<%=MoreOther.ClientID %>").value === null) {
                  args.IsValid = true;
              } else {
                  args.IsValid = false;
              }
          }
      }

Open in new window

Here is All the Code In this Webform
<%@ Page Language="VB" AutoEventWireup="false" Debug="true" MaintainScrollPositionOnPostback="true" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Web.UI.Page" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.data.OleDb" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>

<%@ Register Assembly="System.Web, Version=2.0.0.0, Culture=neutral, 

Open in new window

0
Become a Certified Penetration Testing Engineer
LVL 13
Become a Certified Penetration Testing Engineer

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

I am capturing a string of data that has some no printable characters from a COM bus. I capture them with a string variable and then display them inside my listbox window.

I put breakpoints on the string variable after a capture the complete data from the COM bus and I see the non-printables in the watch window. However I don't see the non printable inside the listbox control.

Any ideas would be appreciated

Thanks in advance.
0
Hi,

I'm using below code for running some procedures and also i would like to show them their status in my data grid view as below.

But i'd like to know that is there any way to simplify these code or you think it's the best approach i can?

Especially i mean this type of blocks(i take one of them as an example from bigger code block)

          If nodeForceOut.Checked = True Then
                Dim rowIndex As Integer = FindRowDgv(nodeForceOut.Text)
                Try
                    StyleStatus(rowIndex, "Performing", Color.Yellow)
                    ForceOut.MeasureForceMarker()
                    ForceOut.ListForceOutputs()
                    StyleStatus(rowIndex, "Finished", Color.Green)
                Catch ex As Exception
                    StyleStatus(rowIndex, "Error Occured", Color.Red)
                    Tools.OutputLog.Print(Tools.OutputLog.Type.ERR, ex.Message)
                End Try
            End If

Open in new window


Any help would be grateful. Thank you.

        Public Shared Sub Run(ByVal mdl As IScrModel)
            If mdl Is Nothing Then
                Throw New ArgumentNullException(NameOf(mdl))
            End If

            Dim tView As TreeView = GUI.treCheckListMain
            Dim dgView As DataGridView = GUI.dgvCheckInfo
            dgView.Rows.Clear()

            For Each nodeParent As TreeNode In tView.Nodes
                If nodeParent.Checked Then
                    dgView.Rows.Add(nodeParent.Text, "In queue")

Open in new window

0
Create Session id after my save button click.
I'm trying to simply create a session id after my save button event. After i save my data, i'd like to have my session be the primary key of Table2 which is titled POMONTHID, so it's not visible in any of the code behind or stored procedure.

My original SQL Stored Procedure to insert my data is
ALTER PROCEDURE [dbo].[ReturnIDwithOutput]
	@Suppint Varchar(50),
	@VendorCode Varchar(10),
	@classgroupAllocID Varchar(10),
	@Season Varchar(4),
	@quarter Varchar(50),
	@Month Varchar(50),
	@DateAllocated Date,
	@StyleCreated Varchar(5),
	@EDIT BIT,
	@Category VARCHAR(50),
	@POID INT OUTPUT
	
AS
BEGIN
	SET NOCOUNT ON;
	--DECLARE @POID INT;
	INSERT INTO [dbo].[Table1] (Suppint,VendorCode,classgroupAllocID,Season,[quarter],CreateDate)
	VALUES (@Suppint,@VendorCode,@classgroupAllocID,@Season,@quarter,GETDATE());
	SET @POID = SCOPE_IDENTITY();
	
	INSERT INTO [dbo].[Table2](POID,[Month],DateAllocated,StyleCreated,EDIT,Category,CreateDate) VALUES (@POID,@Month,@DateAllocated,@StyleCreated,@EDIT,@Category,GetDATE());

END

Open in new window


the code behind to call the stored procedure from ASP objects is here:
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click

        Dim strConnString As String = ConfigurationManager.ConnectionStrings("connstring").ConnectionString
            Dim con As New SqlConnection(strConnString)
            Dim cmd As New SqlCommand()

            cmd.CommandType =

Open in new window

0
Hi,

I have a Microsoft Access database for projects and i added a Lookup&Relationship oclumn to my access database and i typed the values i wanted like an example below.
000495.jpg000496.jpg
But when i binding this datasource in my tool and insert combobox and set DisplayMember this column. I couldnt be able to see items in my combobox items collection.

I thought i'm making mistakes in this topic, any experts can help me where i am wrong ?

thanks.
0
Hi,

I'm using COM-interface enginnering software in my tool and getting some output channels from the program, and i'm listing them in datagridview in my tool.(Like Force, Torque, Displacement, Stifness etc. information ). Datagridview's column header text information comes from tool.

I'm trying to add their units to Column's Tag property, because in next steps i'd like to compare Newton, velocity, torque values in some tolerances,


So how is it possible to tag columns according to their header text keywords.

For example if column name contains Force, Newton, Output Force this column's tag will be "N", or Torque, Moment this column's tag will be "Nm", or Velocity, Speed etc. this column's tag will be "m/s".

How is it possible to do that? Any help would be grateful.

Thank you.
0
Hi Experts,

I'm using Visual Studio 2013 (yes, am roaming with the dinosaurs!) for VB development.

I would like to know the line count for each function and sub, broken down by module.
It would also be nice to be able to sort the results by line count.

Is there a free or inexpensive tool that will do this?

Regards,
Leigh
0

Visual Basic.NET

93K

Solutions

24K

Contributors

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to  Visual Basic pre-2002, it is not the same technology,