Find and highlight the max value in from multiple column in VB.net - vb.net

Hi i need anyone to help me,
I need to highlight the highest value from multiple column in table
For Ex:-
I have try out some coding..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UIUtility = New UIUtility()
Dim dtStartProcessTime As DateTime
Dim dtEndProcessTime As DateTime
Dim dtStartQueryTime As DateTime
Dim dtEndQueryTime As DateTime
Dim tsQueryTime As TimeSpan
Dim tsProcessTime As TimeSpan
Dim strCassList As String = ""
Dim dtDefectInfo As New DataTable
Dim dtDefectList As New DataTable
Dim dtResult As New DataTable
Dim dtSelectDefectInfo As New DataTable
Dim strCass_id As String = ""
Dim dtDisplay As New DataTable
Try
dtStartProcessTime = Now
Me.Title = "Shipping Cassettes List"
Dim sEvent_date As String = Request.QueryString("Event_date").Trim()
Dim sRecipe As String = Request.QueryString("recipe").Trim()
Dim sOperation As String = Request.QueryString("operation").Trim()
Dim sEquipment As String = Request.QueryString("equipment").Trim()
lblStatus.Text = "Event_date:" + sEvent_date + _
"<br>Recipe:" + sRecipe + _
"<br>Operation:" + sOperation + _
"<br>Equipment:" + sEquipment + _
"<br><br>"
Dim dtCass As DataTable
Dim drNew As DataRow
Dim SelectDefectInfo As DataRow()
dtStartQueryTime = Now
dtCass = UIUtility.RetrieveShipCassette(sEvent_date, sRecipe, sOperation, sEquipment)
If dtCass.Rows.Count > 0 Then
strCassList = UIUtility.ReturnStringFromdt(dtCass, "shipping_cass_id")
dtDefectInfo = UIUtility.RetrieveDefectInfo(strCassList)
dtDefectList = UIUtility.dtView(dtDefectInfo, "defect")
dtResult.Columns.Add("cass_id", Type.GetType("System.String"))
For i = 0 To dtDefectList.Rows.Count - 1
If Not (dtDefectList.Rows(i).Item("defect").ToString().Equals("NON")) Then
dtResult.Columns.Add(dtDefectList.Rows(i).Item("defect"), Type.GetType("System.Int32")).DefaultValue = 0
End If
Next
For i = 0 To dtCass.Rows.Count - 1
drNew = dtResult.NewRow
strCass_id = dtCass.Rows(i).Item("shipping_cass_id")
drNew("cass_id") = dtCass.Rows(i).Item("cass_id")
SelectDefectInfo = dtDefectInfo.Select("dest_cass_id = '" + strCass_id + "'")
dtSelectDefectInfo = New DataTable
If SelectDefectInfo.Count > 0 Then
dtSelectDefectInfo = SelectDefectInfo.CopyToDataTable
For j = 0 To dtSelectDefectInfo.Rows.Count - 1
If Not (dtSelectDefectInfo.Rows(j).Item("defect").ToString().Trim().Equals("NON")) Then
drNew(dtSelectDefectInfo.Rows(j).Item("defect").ToString()) = dtSelectDefectInfo.Rows(j).Item("defect_count").ToString()
End If
Next
End If
dtResult.Rows.Add(drNew)
Next
End If
dtEndQueryTime = Now
tsQueryTime = dtEndQueryTime.Subtract(dtStartQueryTime)
'For i As Integer = 0 To dtCass.Rows.Count - 1
' drDisplay = dtDisplay.NewRow
' drDisplay("cass_id") = dtCass.Rows(i)("cass_id").ToString()
' dtDisplay.Rows.Add(drDisplay)
' 'dtCass.Rows(i).Item(
'Next
'e.Row.BorderWidth = 2
dgSummary.DataSource = Nothing
dgSummary.DataSource = dtResult
dgSummary.DataBind()
lblStatus.Text += "Total " + dtResult.Rows.Count.ToString + " rows of data found."
dtEndProcessTime = Now
tsProcessTime = dtEndProcessTime.Subtract(dtStartProcessTime)
lblProcessingTime.Text = "Processing Time: " + tsProcessTime.TotalSeconds.ToString + " Secs (Query Time: " + tsQueryTime.TotalSeconds.ToString + " Secs)"
For Each r As GridViewRow In dtResult.Rows()
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Text, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Text = max Then
r.Cells(i).BackColor = Drawing.Color.Orange
Exit For
End If
Next
Next
Catch ex As Exception
lblMessage.Text = "An error occured:" + ex.Message + " Please contact your administrator."
MyLog.WriteToLog(Me.GetType().Name(), System.Reflection.MethodInfo.GetCurrentMethod().Name, "Exception occured." & vbCrLf & "Error Message:" & ex.Message & vbCrLf & " StackTrace:" & ex.StackTrace)
End Try
End Sub
Protected Sub dgSummary_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgSummary.RowDataBound
Dim cass_id As String = ""
'Dim dtResult As New DataTable
'Dim DataGridView1 As New DataTable
Dim dtCass As New DataTable
If e.Row.RowType = DataControlRowType.DataRow Then
cass_id = e.Row.Cells(0).Text.Trim
If Not e.Row.Cells(0).Text.Trim.Equals("") Then
e.Row.Cells(0).Attributes.Add("Title", "Click and view the cassette details")
e.Row.Cells(0).Attributes("onmouseover") = "this.style.color='DodgerBlue';this.style.cursor='hand';"
e.Row.Cells(0).Attributes("onmouseout") = "this.style.color='Black';"
e.Row.Cells(0).Attributes("onClick") = _
String.Format("window.open('{0}','_blank','scrollbars=yes,status=yes,location=yes,toolbar=yes,menubar=yes,resizable=Yes')", _
ResolveUrl(System.Configuration.ConfigurationManager.AppSettings("SFEHReportLink_SSL") + cass_id))
e.Row.Cells(0).Style("cursor") = "pointer"
End If
End Sub
Maybe theres any coding that more easier than this since i have 17items
Thank you so much for you guys help.
After i add the new code, i got this error,
new error

maybe this example can help you
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
For Each r As DataGridViewRow In DataGridView1.Rows
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Value, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Value = max Then
r.Cells(i).Style.BackColor = Color.Orange
Exit For
End If
Next
Next
End Sub

Related

VB report error System.InvalidCastException: Operator '+' is not defined for type 'Double' and type 'DBNull'

Error: error line 369
Line 367: For intTeller = 0 To tblData.Rows.Count - 1
Line 368: With tblData.Rows(intTeller)
Line 369: .Item("Projected") = .Item("Sales") + .Item("ShippedNotInvoiced") + .Item("OpenOrdersCurrentPeriod")
Line 370: End With
Line 371: Next
Code
Imports System.Data.SqlClient
Partial Class Sales
Inherits System.Web.UI.Page
Dim tblData As New Data.DataTable
Private Sub DataGridToExcel(ByRef grdExport As GridView, ByRef pResponse As Web.HttpResponse, ByVal pFileName As String)
Try
Dim intTeller As Integer = 0
Dim strTemp As String
pResponse.Clear()
pResponse.AddHeader("content-disposition", "attachment;filename=" & pFileName)
pResponse.Buffer = True
pResponse.ContentType = "application/vnd.ms-excel"
pResponse.Charset = ""
Dim stringWrite As New System.IO.StringWriter
Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
grdExport.RenderControl(htmlWrite)
strTemp = stringWrite.ToString
strTemp.Replace(",", "")
strTemp.Replace(".", "")
pResponse.Write(strTemp)
pResponse.End()
Catch ex As Exception
'Me.lblError.Text = ex.Message
End Try
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
Private Sub sExportGrid()
DataGridToExcel(Me.grdSalesLines, Response, "Sales " & Format(Now, "yyyyMM") & ".xls")
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
sCreateTable()
sFillPeriods()
sRefreshData(Format(Now, "yyyyMM"), Format(DateAdd(DateInterval.Year, -1, Now), "yyyyMM"))
End If
End Sub
Private Sub sFillPeriods()
Dim conMain As New SqlConnection(sGetConnectionString)
Dim comMain As SqlCommand
Dim drMain As SqlDataReader
Dim strSQL As String = "SELECT DISTINCT Period FROM [SR_SalesOverviewCompany] Order by Period DESC"
conMain.Open()
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
Me.cmbPeriods.Items.Clear()
Me.cmbPeriods.Items.Add("Current Period")
Me.cmbPeriods.Items.Add("Year To Date")
If drMain.HasRows Then
While drMain.Read
If Not IsDBNull(drMain.Item("Period")) Then
Me.cmbPeriods.Items.Add(drMain.Item("Period"))
End If
End While
End If
End Sub
Private Function sGetConnectionString() As String
Dim conString = ConfigurationManager.ConnectionStrings("STOKVIS LIVEConnectionString")
Dim strConnString As String = conString.ConnectionString
Return strConnString
End Function
Protected Sub grdSalesLines_DataBound(sender As Object, e As System.EventArgs) Handles grdSalesLines.DataBound
If Me.cmbPeriods.SelectedItem.Text <> "Current Period" Then
grdSalesLines.Columns(3).Visible = False
grdSalesLines.Columns(4).Visible = False
grdSalesLines.Columns(5).Visible = False
grdSalesLines.Columns(7).Visible = False
Else
grdSalesLines.Columns(3).Visible = True
grdSalesLines.Columns(4).Visible = True
grdSalesLines.Columns(5).Visible = True
grdSalesLines.Columns(7).Visible = True
End If
End Sub
Protected Sub grdSalesLines_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdSalesLines.RowCommand
Dim intRow As Integer = CInt(e.CommandArgument)
Response.Redirect("SalesDetails.aspx?p=" & Me.cmbPeriods.SelectedItem.Text & "&s=" & grdSalesLines.Rows(intRow).Cells(1).Text)
End Sub
Protected Sub grdSalesLines_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdSalesLines.RowDataBound
Dim intCounter As Integer
If e.Row.Cells(1).Text = "Total" Then
For intCounter = 0 To e.Row.Cells.Count - 1
With e.Row.Cells(intCounter)
.ForeColor = Drawing.Color.White
.BackColor = Drawing.Color.DarkBlue
.Font.Bold = True
End With
Next
End If
End Sub
Private Sub sCreateTable()
tblData.Columns.Clear()
tblData.Columns.Add(New Data.DataColumn("Code", System.Type.GetType("System.String")))
tblData.Columns.Add(New Data.DataColumn("Salesperson", System.Type.GetType("System.String")))
tblData.Columns.Add(New Data.DataColumn("OpenOrders", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("OpenOrdersCurrentPeriod", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("ShippedNotInvoiced", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("Sales", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("Projected", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("Budget", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("PreviousYear", System.Type.GetType("System.Double")))
End Sub
Protected Sub btnRefresh_Click(sender As Object, e As System.EventArgs) Handles btnRefresh.Click
If Me.cmbPeriods.SelectedItem.Text = "Current Period" Then
sRefreshData(Format(Now, "yyyyMM"), Format(DateAdd(DateInterval.Year, -1, Now), "yyyyMM"))
Else
sRefreshData(Me.cmbPeriods.SelectedItem.Text, "")
End If
End Sub
Protected Sub btnExcel_Click(sender As Object, e As System.EventArgs) Handles btnExport.Click
sExportGrid()
End Sub
Protected Sub cmbPeriods_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles cmbPeriods.SelectedIndexChanged
sCreateTable()
If Me.cmbPeriods.SelectedItem.Text = "Current Period" Then
sRefreshData(Format(Now, "yyyyMM"), Format(DateAdd(DateInterval.Year, -1, Now), "yyyyMM"))
Else
sRefreshData(Me.cmbPeriods.SelectedItem.Text, "")
End If
End Sub
Private Sub sRefreshData(pPeriod As String, pPreviousYearPeriod As String)
Dim conMain As New SqlConnection(sGetConnectionString)
Dim comMain As SqlCommand
Dim drMain As SqlDataReader
Dim dtRow As Data.DataRow
Dim strSQL As String
Dim intTeller As Integer
Dim blnYearToDate As Boolean = False
sCreateTable()
If pPeriod = "Year To Date" Then
pPeriod = ""
blnYearToDate = True
End If
strSQL = "SELECT code, Name from SR_SalesPerson"
conMain.Open()
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
dtRow = tblData.NewRow()
dtRow.Item("Code") = drMain.Item("Code")
dtRow.Item("SalesPerson") = drMain.Item("Name")
dtRow.Item("OpenOrders") = 0
dtRow.Item("OpenOrdersCurrentPeriod") = 0
dtRow.Item("ShippedNotInvoiced") = 0
dtRow.Item("Sales") = 0
dtRow.Item("Projected") = 0
dtRow.Item("Budget") = 0
dtRow.Item("PreviousYear") = 0
tblData.Rows.Add(dtRow)
End While
dtRow = tblData.NewRow()
dtRow.Item("Code") = "Total"
dtRow.Item("SalesPerson") = ""
dtRow.Item("OpenOrders") = 0
dtRow.Item("OpenOrdersCurrentPeriod") = 0
dtRow.Item("ShippedNotInvoiced") = 0
dtRow.Item("Sales") = 0
dtRow.Item("Projected") = 0
dtRow.Item("Budget") = 0
dtRow.Item("PreviousYear") = 0
tblData.Rows.Add(dtRow)
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_SalesOpenOrdersShippedNotInvoiced"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("Code") Then
tblData.Rows(intTeller).Item("ShippedNotInvoiced") = drMain.Item("AmountRest")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_SalesOpenOrdersPerSalesperson"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("Code") Then
tblData.Rows(intTeller).Item("OpenOrders") = drMain.Item("OpenOrders")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_SalesOpenOrdersPerSalesPersonPerPeriod WHERE Period='" & pPeriod & "'"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("SalesPerson Code") Then
tblData.Rows(intTeller).Item("OpenOrdersCurrentPeriod") = drMain.Item("AmountRest")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_BudgetPerSalesPersonPerPeriod WHERE strPeriod='" & pPeriod & "'"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("strCode") Then
tblData.Rows(intTeller).Item("Budget") = drMain.Item("dblSales")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_HistSalesPerSalesPersonPerPeriod WHERE strPeriod='" & pPreviousYearPeriod & "'"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("strCode") Then
tblData.Rows(intTeller).Item("PreviousYear") = drMain.Item("dblSales")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
If blnYearToDate Then
strSQL = "SELECT Salesperson, SUM(Sales) AS Sales, SUM([Cost of Sales]) AS [Cost of Sales], SUM(Margin) AS Margin, SUM(Margin) / SUM(Sales) AS SalesPercent, Code " & _
"FROM dbo.SR_SalesPerSalesperson " & _
"WHERE (Period LIKE '" & Now.Year & "%') " & _
"GROUP BY Salesperson, Code"
Else
strSQL = "SELECT * FROM SR_SalesPerSalesperson WHERE Period='" & pPeriod & "'"
End If
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("Code") Then
tblData.Rows(intTeller).Item("Sales") = drMain.Item("Sales")
End If
Next
End While
End If
For intTeller = 0 To tblData.Rows.Count - 1
With tblData.Rows(intTeller)
.Item("Projected") = .Item("Sales") + .Item("ShippedNotInvoiced") + .Item("OpenOrdersCurrentPeriod")
End With
Next
Dim intLastRow As Integer = tblData.Rows.Count - 1
For intTeller = 0 To tblData.Rows.Count - 2
With tblData.Rows(intTeller)
tblData.Rows(intLastRow).Item("Sales") += fCheckValue(.Item("Sales"))
tblData.Rows(intLastRow).Item("OpenOrders") += fCheckValue(.Item("OpenOrders"))
tblData.Rows(intLastRow).Item("OpenOrdersCurrentPeriod") += fCheckValue(.Item("OpenOrdersCurrentPeriod"))
tblData.Rows(intLastRow).Item("ShippedNotInvoiced") += fCheckValue(.Item("ShippedNotInvoiced"))
tblData.Rows(intLastRow).Item("Projected") += fCheckValue(.Item("Projected"))
tblData.Rows(intLastRow).Item("Budget") += fCheckValue(.Item("Budget"))
tblData.Rows(intLastRow).Item("PreviousYear") += fCheckValue(.Item("PreviousYear"))
End With
Next
Me.grdSalesLines.DataSource = tblData
Me.grdSalesLines.DataBind()
Try
drMain.Close()
comMain.Dispose()
conMain.Close()
Catch ex As Exception
End Try
End Sub
Private Function fCheckValue(pField As Object) As Double
Dim dblValue As Double = 0
If IsDBNull(pField) Then
dblValue = 0
Else
dblValue = CDbl(pField)
End If
Return dblValue
End Function
End Class
First, it might be useful to have a helper function such as the following:
Private Function GetNullableValue(Of T)(ByVal dataRow As DataRow, ByVal columnName As String, ByVal defaultIfNull As T) As T
If Not IsDBNull(dataRow.Item(columnName)) Then
Return CType(dataRow.Item(columnName), T)
End If
Return CType(defaultIfNull, T)
End Function
To check for DBNull, you could then modify your code as follows:
For intTeller = 0 To tblData.Rows.Count - 1
Dim row As DataRow = tblData.Rows(intTeller)
With row
.Item("Projected") = GetNullableValue(row, "Sales", 0) + GetNullableValue(row, "ShippedNotInvoiced", 0) + GetNullableValue(row, "OpenOrdersCurrentPeriod", 0)
End With
Next
NOTE: The above should side-step the exception. However, the fact that one of these columns is null may be indicative of another problem - e.g. perhaps there are problems with the query or the data

Operator '+' is not defined for type 'Decimal' and type 'DBNull'

im working to show the data in my datagrid,and show the total of items brought in textbox2,but this error "Operator '+' is not defined for type 'Decimal' and type 'DBNull'." what is the problem? please help me i need to finish this so badly. :(
Private Sub dailySales_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Connect()
DataGridView1.DataSource = dtb
dtb.Columns.Add("Transaction Code")
dtb.Columns.Add("Transaction Date ")
dtb.Columns.Add("Item Code")
dtb.Columns.Add("Item")
dtb.Columns.Add("Description")
dtb.Columns.Add("Quantity")
dtb.Columns.Add("Price")
dtb.Columns.Add("Total")
display()
con.Close()
total()
TextBox1.Text = DataGridView1.RowCount()
Me.DataGridView1.DefaultCellStyle.Font = New Font("Cambria", 10)
Me.DataGridView1.ColumnHeadersDefaultCellStyle.Font = New Font("Cambria", 12)
Me.DataGridView1.DefaultCellStyle.SelectionBackColor = Color.FromArgb(129, 207, 224)
Dim i As Integer
For i = 0 To DataGridView1.Columns.Count - 1
DataGridView1.Columns.Item(i).SortMode = DataGridViewColumnSortMode.Programmatic
Next
End Sub
Sub total()
Dim sum As Decimal = 0
For x = 0 To DataGridView1.Rows.Count - 1
sum =sum + DataGridView1.Rows(x).Cells(7).Value
Next
TextBox2.Text = sum
End Sub
Sub display()
con.Connect()
Label6.Text = Date.Now.ToString("dd MMMM yyyy")
Dim da = Label6.Text
Dim sc = " where lower(tns_date) like lower('%" & da & "%') "
Dim sql = "select * from tns " & sc & " order by tns_code desc"
odr = con.Retrieve(sql)
dtb.Clear()
While (odr.Read)
Dim ic = odr.GetOracleValue(0)
Dim itn = odr.GetOracleValue(1)
Dim de = odr.GetOracleValue(2)
Dim ca = odr.GetOracleValue(3)
Dim pr = odr.GetOracleValue(4)
Dim st = odr.GetOracleValue(5)
Dim sst = odr.GetOracleValue(6)
dtb.Rows.Add(ic, itn, de, ca, pr, st, sst)
End While
con.Close()
End Sub
Test like this.
Sub total()
Dim sum As Decimal = 0
For x = 0 To DataGridView1.Rows.Count - 1
If Not isDBNull(DataGridView1.Rows(x).Cells(7).Value) then sum =sum + DataGridView1.Rows(x).Cells(7).Value
Next
TextBox2.Text = sum
End Sub

treeview disappeared when i reopen the form

I would like to ask for your help. I am stuck to this for more than two days, I've searched the net but unfortunately got no answer.
I have a program in vb 2008 and a database (SQL Server 2008). I have this form which contains treeview. The items display is selected from the database. When i run the program and open the form the treeview items displayed (at first), but when i closed the form and try to open it again the treeview disappear. I dont know why :( . Why is it disappearing? Can somebody help me please. Thank you.
Below is my code....
#form_load
Private Sub frmProfile_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call conecDB()
Call initCMD()
FillTable()
CreateTree() 'create the treeview node
findNode() 'find and checked the selected nodes that was given to the profile
End Sub
'the functions
Private Sub FillTable()
'tv1.Nodes.Clear()
dtable.Columns.Add("ID", GetType(Integer))
dtable.Columns.Add("NAME", GetType(String))
dtable.Columns.Add("PARENT", GetType(Integer))
dtable.Columns.Add("LEVEL", GetType(Integer))
qSQL = "select mod_id,name,parent,level,sort,mnu_name from module where status='A' and parent!=-1"
With comDB
.CommandText = qSQL
rdDB = .ExecuteReader
End With
Do While rdDB.Read
dtable.Rows.Add(rdDB!mod_id, rdDB!name.ToString(), rdDB!parent)
My.Application.DoEvents()
Loop
For i = 0 To dtable.Rows.Count - 1
Dim ID1 As String = dtable.Rows(i).Item("ID").ToString
dtable.Rows(i).Item("LEVEL") = FindLevel(ID1, 0)
Next
rdDB.Close()
End Sub
Private Function FindLevel(ByVal ID As String, ByRef Level As Integer) As Integer
For i = 0 To dtable.Rows.Count - 1
Dim ID1 As String = dtable.Rows(i).Item("ID").ToString
Dim Parent1 As String = dtable.Rows(i).Item("PARENT").ToString
If ID = ID1 Then
If Parent1 = 0 Then
Return Level
Else
Level += 1
FindLevel(Parent1, Level)
End If
End If
Next
Return Level
End Function
Private Sub CreateTree()
tv1.Nodes.Clear()
Dim MaxLevel1 As Integer = CInt(dtable.Compute("MAX(LEVEL)", ""))
Dim i, j As Integer
For i = 0 To MaxLevel1
Dim Rows1() As DataRow = dtable.Select("LEVEL = " & i)
For j = 0 To Rows1.Count - 1
Dim ID1 As String = Rows1(j).Item("ID").ToString
Dim Name1 As String = Rows1(j).Item("NAME").ToString
'Dim mName As String = Rows1(j).Item("mNAME").ToString
Dim Parent1 As String = Rows1(j).Item("PARENT").ToString
If Parent1 = 0 Then
tv1.Nodes.Add(ID1, Name1)
Else
Dim TreeNodes1() As TreeNode = tv1.Nodes.Find(Parent1, True)
If TreeNodes1.Length > 0 Then
TreeNodes1(0).Nodes.Add(ID1, Name1)
End If
End If
Next
Next
End Sub
Private Sub findNode()
Dim rName As String = String.Empty
Dim b As Boolean = True
qSQL = "select access_id,mnu_name from profile_details where prof_id=" & lblPID.Text & ""
With comDB
.CommandText = qSQL
rdDB = .ExecuteReader
End With
Do While rdDB.Read
rName = rdDB!access_id.ToString()
Try
Dim arr As TreeNode() = tv1.Nodes.Find(rName, b)
For i = 0 To arr.Length - 1
tv1.SelectedNode = arr(i)
tv1.SelectedNode.Checked = True
Next
Catch
MsgBox(Err)
End Try
Loop
rdDB.Close()
End Sub

How to generate all combinations of partitioning a string in VB.Net

Given a string, how do you generate all partitions of it (shown as smaller strings separated by commas)?
Also, what is the total number of partitions for a string of length n?
The following will give the result, but is not good on long strings.
String: CODE
C,O,D,E
C,O,DE
C,OD,E
C,ODE
CO,D,E
CO,DE
COD,E
String: PEACE
P,E,A,C,E
P,E,A,CE
P,E,AC,E
P,E,ACE
P,EA,C,E
P,EA,CE
P,EAC,E
PE,A,C,E
PE,A,CE
PE,AC,E
PE,ACE
PEA,C,E
PEA,CE
Sub getAllComb()
oriStr = TextBox1.Text
Dim tmp = ""
Dim k = 0
For i = 0 To oriStr.Length
For j = 1 To 3
'tmp = Mid(oriStr, i, j)
Try
tmp1(k) = oriStr.Substring(i, j)
k = k + 1
'tmp = oriStr.Substring(i, j)
'Debug.Print(tmp)
Catch ex As Exception
'Debug.Print("Error>>>>" + ex.Message)
Exit For
End Try
Next
Next
tmp = ""
For i = 0 To k
Debug.Print(i.ToString + "<i " + tmp1(i))
tmp = tmp & tmp1(i) & vbCrLf
Next
'MessageBox.Show(tmp)
Dim tmpAll1 = ""
tmpAll1 = addFunclen4(k)
MessageBox.Show(tmpAll1)
Debug.Print(tmpAll1)
TextBox1.Text = oriStr & vbCrLf & vbCrLf & tmpAll1
End Sub
Function addFunclen4(k As Integer) As String
Dim retVal = ""
Dim tmp = ""
Dim tmpAll = ""
Dim tmpStr = ""
Dim tmpAll1 = ""
For i = 0 To k
For i1 = 0 To k
For i2 = 0 To k
For i3 = 0 To k
For i4 = 0 To k
tmp = Form1.tmp1(i) + Form1.tmp1(i1) + Form1.tmp1(i2) + Form1.tmp1(i3) + Form1.tmp1(i4)
If Form1.tmp1(i) <> "" Then
If tmp = Form1.oriStr Then
tmpStr = Form1.tmp1(i) + "," + Form1.tmp1(i1) + "," + Form1.tmp1(i2) + "," + Form1.tmp1(i3) + "," + Form1.tmp1(i4)
Do While tmpStr.Contains(",,") = True
tmpStr = Replace(tmpStr, ",,", ",")
Loop
If Mid(tmpStr, tmpStr.Length, 1) = "," Then
tmpStr = Mid(tmpStr, 1, tmpStr.Length - 1)
End If
If tmpAll1.Contains(tmpStr) = False Then
tmpAll1 = tmpAll1 + tmpStr + vbCrLf
End If
End If
End If
Next
Next
Next
Next
Next
retVal = tmpAll1
Return retVal
End Function
I reckon [2^(n-1) - 1] in total:
(n-1) positions to put a comma, 2 "states" (comma or not comma), -1 for the trivial case with no commas.
A simpler algorithm would be to iterate through the number of cases and use the binary representation to determine whether to put a comma in each position.
For example (simple form with TextBox, Button and ListBox):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Return
End If
For i = 1 To Math.Pow(2, s.Length - 1) - 1
Dim result As String = s(0)
For j = 1 To s.Length - 1
result = result & CommaOrNot(i, j) & s(j)
Next
ListBox1.Items.Add(result)
Next
End Sub
Private Function CommaOrNot(i As Integer, j As Integer) As String
If (i And Math.Pow(2, j - 1)) = Math.Pow(2, j - 1) Then
Return ","
Else
Return ""
End If
End Function
I really liked Fruitbat's approach. Here's an alternate version using a slightly different mechanism for the representation of the binary number and how to determine if the comma should be included or not:
Public Class Form1
Private combinations As List(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Exit Sub
End If
Button1.Enabled = False
ListBox1.DataSource = Nothing
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...")
BackgroundWorker1.RunWorkerAsync(s)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim s As String = e.Argument
Dim combinations As New List(Of String)
Dim binary() As Char
Dim values() As Char = s.ToCharArray
Dim max As Integer = Convert.ToInt32(New String("1", s.Length - 1), 2)
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To max
sb.Clear()
binary = Convert.ToString(i, 2).PadLeft(values.Length, "0").ToCharArray
For j As Integer = 0 To values.Length - 1
sb.Append(If(binary(j) = "0", "", ","))
sb.Append(values(j))
Next
combinations.Add(sb.ToString)
Next
e.Result = combinations
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
combinations = e.Result
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...Done!")
ListBox1.Items.Add("Adding Results...one moment please!")
Application.DoEvents()
ListBox1.DataSource = Nothing
ListBox1.DataSource = combinations
Button1.Enabled = True
MessageBox.Show("Done!")
End Sub
End Class

vb.net - Why do I get this error when trying to bubble sort a csv file?

I have a csv file which I'm trying to sort by data (numerical form)
The csv file:
date, name, phone number, instructor name
1308290930,jim,041231232,sushi
123123423,jeremy,12312312,albert
The error I get is: Conversion from string "jeremy" to type 'double'is not valid
Even though no where in my code I mention double...
My code:
Public Class Form2
Dim currentRow As String()
Dim count As Integer
Dim one As Integer
Dim two As Integer
Dim three As Integer
Dim four As Integer
'concatenation / and operator
'casting
Dim catchit(100) As String
Dim count2 As Integer
Dim arrayone(4) As Decimal
Dim arraytwo(4) As String
Dim arraythree(4) As Decimal
Dim arrayfour(4) As String
Dim array(4) As String
Dim bigstring As String
Dim builder As Integer
Dim twodata As Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("D:\completerecord.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
Dim count As Integer
Dim currentField As String
count = 0
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField In currentRow
' makes one array to contain a record for each peice of text in the file
'MsgBox(currentField) '- test of Field Data
' builds a big string with new line-breaks for each line in the file
bigstring = bigstring & currentField + Environment.NewLine
'build two arrays for the two columns of data
If (count Mod 2 = 1) Then
arraytwo(two) = currentField
two = two + 1
'MsgBox(currentField)
ElseIf (count Mod 2 = 0) Then
arrayone(one) = currentField
one = one + 1
ElseIf (count Mod 2 = 2) Then
arraythree(three) = currentField
three = three + 1
ElseIf (count Mod 2 = 3) Then
arrayfour(four) = currentField
four = four + 1
End If
count = count + 1
'MsgBox(count)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error Occured, Please contact Admin.")
End Try
End While
End Using
RichTextBox1.Text = bigstring
' MsgBox("test")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NoMoreSwaps As Boolean
Dim counter As Integer
Dim Temp As Integer
Dim Temp2 As String
Dim listcount As Integer
Dim builder As Integer
Dim bigString2 As String = ""
listcount = UBound(arraytwo)
'MsgBox(listcount)
builder = 0
'bigString2 = ""
counter = 0
Try
'this should sort the arrays using a Bubble Sort
Do Until NoMoreSwaps = True
NoMoreSwaps = True
For counter = 0 To (listcount - 1)
If arraytwo(counter) > arraytwo(counter + 1) Then
NoMoreSwaps = False
If arraytwo(counter + 1) > 0 Then
Temp = arraytwo(counter)
Temp2 = arrayone(counter)
arraytwo(counter) = arraytwo(counter + 1)
arrayone(counter) = arrayone(counter + 1)
arraytwo(counter + 1) = Temp
arrayone(counter + 1) = Temp2
End If
End If
Next
If listcount > -1 Then
listcount = listcount - 1
End If
Loop
'now we need to output arrays to the richtextbox first we will build a new string
'and we can save it to a new sorted file
Dim FILE_NAME As String = "D:\sorted.txt"
'Location of file^ that the new data will be saved to
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
'If D:\sorted.txt exists then enable it to be written to
While builder < listcount
bigString2 = bigString2 & arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine
objWriter.Write(arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine)
builder = builder + 1
End While
RichTextBox2.Text = bigString2
objWriter.Close()
MsgBox("Text written to log file")
Else
MsgBox("File Does Not Exist")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I think in this line is the problem
arrayone(one) = currentField
Here it trys to cast the string to a double. You have to use something like this:
arrayone(one) = Double.Parse(currentField)
or to have it a saver way:
Dim dbl As Double
If Double.TryParse(currentField, dbl) Then
arrayone(one) = dbl
Else
arrayone(one) = 0.0
End If