data still saving on zero - vb.net

in my code the data is saving if no.of days to complete=0.I want it should not happen
in my code a msg comes "time to complete and time to acknowledged can be only be posiitve" but still data saves.i dont want it to be saved !!
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Try
Dim i As Integer
If gvBanckmark.Rows.Count > 0 Then
For i = 0 To gvBanckmark.Rows.Count - 1
Dim lblBenchMarkID As Label = CType(gvBanckmark.Rows(i).FindControl("lblBenchMarkID"), Label)
Dim lblSubCategoryId As Label = CType(gvBanckmark.Rows(i).FindControl("lblSubCategoryId"), Label)
Dim ddlFrequencyTypeAcknowledge As DropDownList = CType(gvBanckmark.Rows(i).FindControl("ddlFrequencyTypeAcknowledge"), DropDownList)
Dim ddlFrequencyTypeComplete As DropDownList = CType(gvBanckmark.Rows(i).FindControl("ddlFrequencyTypeComplete"), DropDownList)
Dim txtTimeToAcknowledge As TextBox = CType(gvBanckmark.Rows(i).FindControl("txtTimeToAcknowledge"), TextBox)
Dim txtTimeToComplete As TextBox = CType(gvBanckmark.Rows(i).FindControl("txtTimeToComplete"), TextBox)
Dim objBenchMark As BO.BenchMark = New BO.BenchMark()
objBenchMark.BuildingID = Convert.ToInt32(ddlBuilding.SelectedValue)
objBenchMark.CategoryID = Convert.ToInt32(ddlCategory.SelectedValue)
objBenchMark.SubCategoryID = Convert.ToInt32(lblSubCategoryId.Text.ToString())
objBenchMark.FrequencyTypeToAcknowledge = ddlFrequencyTypeAcknowledge.SelectedValue.ToString()
objBenchMark.FrequencyTypeToComplete = ddlFrequencyTypeComplete.SelectedValue.ToString()
objBenchMark.TimeToAcknowledge = Convert.ToInt32(txtTimeToAcknowledge.Text.ToString())
objBenchMark.TimeToComplete = Convert.ToInt32(txtTimeToComplete.Text.ToString())
If lblBenchMarkID.Text.ToString() = 0 Then
objBenchMark.BenchMarkID = 0
objBenchMark.CreateByUserId = UserWrapper.GetCurrentUser().ContactID
BO.BenchMark.InsertBechMarkData(objBenchMark)
Else
objBenchMark.BenchMarkID = Convert.ToInt32(lblBenchMarkID.Text.ToString())
objBenchMark.ModifiedByUserId = UserWrapper.GetCurrentUser().ContactID
BO.BenchMark.UpdateBechMarkData(objBenchMark)
End If
Next i
End If
lblError.Visible = True
lblError.Text = "<a cssClass=""messageGood"">Benchmark data has been saved sucessfully.</a>"
Catch ex As Exception
lblError.Text = ex.Message
lblError.Visible = True
End Try
End Sub

Your data is not being saved, but the message telling you the data has been saved is being presented, despite it's saved or not.
Move thses lines inside the if-end if:
lblError.Visible = True
lblError.Text = "<a cssClass=""messageGood"">Benchmark data has been saved sucessfully.</a>"

Related

Highlight a row in Datagridview based on textbox value

Good Evening.
I have a program in VB.Net that refreshes datagridview after you edit some data my problem here is im populating over 1000 records.
Let say Im editing row 999 and after i click update the data will refresh causing the datagridview to return at the top (The blue highlighter)
My goal here is how can I maintain it to its current position after update?
My solution here is highlight the data where Textbox1 = value
Is this possible like this?
'SAMPLE CODE
Datagridview1.Column(0).value.BlueHighLighter = Textbox1.text
Pls see my code on how i refresh DGV
Dim con11 As MySqlConnection = New MySqlConnection("server=192.168.2.87;userid=root;password=admin1950;database=inventory")
Dim sql1 As MySqlCommand = New MySqlCommand("select PONo,ItemCode,Description,QtyPack,PackUoM,QtyStan,StanUoM,UnitPrice,Total,Remarks,ExpiryDate from Receiving where RINo = '" & Add_Receiving_Items.TextBox1.Text & "';", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
Add_Receiving_Items.DataGridView1.DataSource = ds1.Tables(0)
con1.close()
With Add_Receiving_Items.DataGridView1()
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "PO No"
.Columns(1).HeaderCell.Value = "Item Code"
.Columns(2).HeaderCell.Value = "Description"
.Columns(3).HeaderCell.Value = "Quantity/Pack"
.Columns(4).HeaderCell.Value = "Packaging UoM"
.Columns(5).HeaderCell.Value = "Quantity/Pc"
.Columns(6).HeaderCell.Value = "Standard UoM"
.Columns(7).HeaderCell.Value = "Unit Price"
.Columns(8).HeaderCell.Value = "Total"
.Columns(9).HeaderCell.Value = "Remarks"
.Columns(10).HeaderCell.Value = "Expiry Date"
End With
Add_Receiving_Items.DataGridView1.Columns.Item(0).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(1).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(2).Width = 120
Add_Receiving_Items.DataGridView1.Columns.Item(3).Width = 86
Add_Receiving_Items.DataGridView1.Columns.Item(4).Width = 68
Add_Receiving_Items.DataGridView1.Columns.Item(5).Width = 75
Add_Receiving_Items.DataGridView1.Columns.Item(6).Width = 68
Add_Receiving_Items.DataGridView1.Columns.Item(7).Width = 70
Add_Receiving_Items.DataGridView1.Columns.Item(8).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(9).Width = 105
Add_Receiving_Items.DataGridView1.Columns.Item(10).Width = 63
Add_Receiving_Items.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Add_Receiving_Items.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
With Add_Receiving_Items.DataGridView1
.RowsDefaultCellStyle.BackColor = Color.WhiteSmoke
.AlternatingRowsDefaultCellStyle.BackColor = Color.Lavender
End With
TYSM for future help
Use DataGridView.CurrentRow property. But please be aware that CurrentRow is ReadOnly, you must use CurrentCell
Before refreshing your data store Dim oldIndex = DataGridView.CurrentRow.Index and after the refresh set DataGridView.CurrentCell = DataGridView.Rows(oldIndex).Cells(0)
EDIT:
How to test the Code
Create a form with a Button1 and a DataGridView1 with two columns and paste the following code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i = 1 To 5
DataGridView1.Rows.Add("foo" & i, "bar" & i)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim currentIndex = DataGridView1.CurrentRow.Index
currentIndex += 1
If currentIndex >= DataGridView1.Rows.Count Then currentIndex = 0
DataGridView1.CurrentCell = DataGridView1.Rows(currentIndex).Cells(0)
End Sub
End Class
EDIT:
Dim oldIndex = DataGridView.CurrentRow.Index
'Put your code here on how you refresh your data
DataGridView.CurrentCell = DataGridView.Rows(oldIndex).Cells(0)

Visual Basic - Issue with how the code is being Executed

So I have a button that Scrapes Proxies from Public Websites and adds the proxies to a Listbox but there's an issue, It for some reason shows the Proxies in the Listbox once its Actually finished doing all the "For Each"'s.
It even doesn't show a Progress Bar until everything is Finished which is making it pointless.
Screenshot of what I mean:
(As you can see it only shows the Progress Bar when its finished rather then while its Scraping.)
Is there any workaround for this?
My Code:
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
ScrapeProgress.Visible = True
'Set the Time;
Dim time = TimeOfDay.ToString("h:mm:ss tt")
'Sources;
Dim sources(122) As String
sources(0) = "http://proxy-ip-list.com"
sources(1) = "http://fineproxy.org/eng/?p=6#more-6"
sources(2) = "http://aliveproxy.com/high-anonymity-proxy-list"
sources(3) = "http://aliveproxy.com/anonymous-proxy-list/"
sources(4) = "http://aliveproxy.com/transparent-proxy-list"
sources(5) = "http://aliveproxy.com/socks5-list"
sources(6) = "http://aliveproxy.com/socks4-list"
sources(7) = "http://aliveproxy.com/fastest-proxies/"
sources(8) = "http://atomintersoft.com/anonymous_proxy_list"
sources(9) = "http://atomintersoft.com/high_anonymity_elite_proxy_list"
sources(10) = "http://atomintersoft.com/proxy_list_domain"
sources(11) = "http://atomintersoft.com/proxy_list_port"
sources(12) = "http://atomintersoft.com/transparent_proxy_list"
sources(13) = "http://atomintersoft.com/products/alive-proxy/socks5-list"
sources(14) = "http://best-proxy.com/english/search.php?search=anonymous-and-elite&country=any&type=anonymous-and-elite&port=any&ssl=any"
sources(15) = "http://best-proxy.com/english/search.php?search=anonymous-and-elite&country=any&type=anonymous-and-elite&port=any&ssl=any&p=2"
sources(16) = "http://best-proxy.com/english/search.php?search=anonymous-and-elite&country=any&type=anonymous-and-elite&port=any&ssl=any&p=3"
sources(17) = "http://www.samair.ru/proxy/socks01.htm"
sources(18) = "http://www.samair.ru/proxy/socks02.htm"
sources(19) = "http://www.samair.ru/proxy/socks03.htm"
sources(20) = "http://www.samair.ru/proxy/socks04.htm"
sources(21) = "http://www.samair.ru/proxy/socks05.htm"
sources(22) = "http://www.samair.ru/proxy/proxy-01.htm"
sources(23) = "http://www.samair.ru/proxy/proxy-02.htm"
sources(24) = "http://www.samair.ru/proxy/proxy-03.htm"
sources(25) = "http://www.samair.ru/proxy/proxy-04.htm"
sources(26) = "http://www.samair.ru/proxy/proxy-05.htm"
sources(27) = "http://www.samair.ru/proxy/proxy-06.htm"
sources(28) = "http://www.samair.ru/proxy/proxy-07.htm"
sources(29) = "http://www.samair.ru/proxy/proxy-08.htm"
sources(30) = "http://www.samair.ru/proxy/proxy-09.htm"
sources(31) = "http://www.samair.ru/proxy/proxy-10.htm"
sources(32) = "http://www.samair.ru/proxy/proxy-11.htm"
sources(33) = "http://www.samair.ru/proxy/proxy-12.htm"
sources(34) = "http://www.samair.ru/proxy/proxy-13.htm"
sources(35) = "http://www.samair.ru/proxy/proxy-14.htm"
sources(36) = "http://www.samair.ru/proxy/proxy-15.htm"
sources(37) = "http://www.samair.ru/proxy/proxy-16.htm"
sources(38) = "http://www.samair.ru/proxy/proxy-17.htm"
sources(39) = "http://www.samair.ru/proxy/proxy-18.htm"
sources(40) = "http://www.samair.ru/proxy/proxy-19.htm"
sources(41) = "http://www.samair.ru/proxy/proxy-20.htm"
sources(42) = "http://www.samair.ru/proxy/proxy-21.htm"
sources(43) = "http://www.samair.ru/proxy/proxy-22.htm"
sources(44) = "http://www.samair.ru/proxy/proxy-23.htm"
sources(45) = "http://www.samair.ru/proxy/proxy-24.htm"
sources(46) = "http://www.samair.ru/proxy/proxy-25.htm"
sources(47) = "http://www.samair.ru/proxy/proxy-26.htm"
sources(48) = "http://www.samair.ru/proxy/proxy-27.htm"
sources(49) = "http://www.samair.ru/proxy/proxy-28.htm"
sources(50) = "http://www.samair.ru/proxy/proxy-29.htm"
sources(51) = "http://www.samair.ru/proxy/proxy-30.htm"
sources(52) = "http://nntime.com/proxy-list-01.htm"
sources(53) = "http://nntime.com/proxy-list-02.htm"
sources(54) = "http://nntime.com/proxy-list-03.htm"
sources(55) = "http://nntime.com/proxy-list-04.htm"
sources(56) = "http://nntime.com/proxy-list-05.htm"
sources(57) = "http://nntime.com/proxy-list-06.htm"
sources(58) = "http://nntime.com/proxy-list-07.htm"
sources(59) = "http://nntime.com/proxy-list-08.htm"
sources(60) = "http://nntime.com/proxy-list-09.htm"
sources(61) = "http://nntime.com/proxy-list-10.htm"
sources(62) = "http://nntime.com/proxy-list-11.htm"
sources(63) = "http://nntime.com/proxy-list-12.htm"
sources(64) = "http://nntime.com/proxy-list-13.htm"
sources(65) = "http://nntime.com/proxy-list-14.htm"
sources(66) = "http://nntime.com/proxy-list-15.htm"
sources(67) = "http://nntime.com/proxy-list-16.htm"
sources(68) = "http://nntime.com/proxy-list-17.htm"
sources(69) = "http://nntime.com/proxy-list-18.htm"
sources(70) = "http://nntime.com/proxy-list-19.htm"
sources(71) = "http://nntime.com/proxy-list-20.htm"
sources(72) = "http://nntime.com/proxy-list-21.htm"
sources(73) = "http://nntime.com/proxy-list-22.htm"
sources(74) = "http://nntime.com/proxy-list-23.htm"
sources(75) = "http://nntime.com/proxy-list-24.htm"
sources(76) = "http://nntime.com/proxy-list-25.htm"
sources(77) = "http://nntime.com/proxy-list-26.htm"
sources(78) = "http://nntime.com/proxy-list-27.htm"
sources(79) = "http://nntime.com/proxy-list-28.htm"
sources(80) = "http://nntime.com/proxy-list-29.htm"
sources(81) = "http://nntime.com/proxy-list-30.htm"
sources(82) = "http://proxylistchecker.org/proxylists.php?t=&p=1"
sources(83) = "http://proxylistchecker.org/proxylists.php?t=&p=2"
sources(84) = "http://proxylistchecker.org/proxylists.php?t=&p=3"
sources(85) = "http://proxylistchecker.org/proxylists.php?t=&p=4"
sources(86) = "http://proxylistchecker.org/proxylists.php?t=&p=5"
sources(87) = "http://proxylistchecker.org/proxylists.php?t=&p=6"
sources(88) = "http://proxylistchecker.org/proxylists.php?t=&p=7"
sources(89) = "http://proxylistchecker.org/proxylists.php?t=&p=8"
sources(90) = "http://proxylistchecker.org/proxylists.php?t=&p=9"
sources(91) = "http://proxylistchecker.org/proxylists.php?t=&p=10"
sources(92) = "http://proxylistchecker.org/proxylists.php?t=&p=11"
sources(93) = "http://proxylistchecker.org/proxylists.php?t=&p=12"
sources(94) = "http://proxylistchecker.org/proxylists.php?t=&p=13"
sources(95) = "http://proxylistchecker.org/proxylists.php?t=&p=14"
sources(96) = "http://proxylistchecker.org/proxylists.php?t=&p=15"
sources(97) = "http://txt.proxyspy.net/proxy.txt"
sources(98) = "http://www.getproxy.jp/en/default/1"
sources(99) = "http://www.getproxy.jp/en/default/2"
sources(100) = "http://www.getproxy.jp/en/default/3"
sources(101) = "http://www.getproxy.jp/en/default/4"
sources(102) = "http://www.getproxy.jp/en/default/5"
sources(103) = "http://www.ip-adress.com/proxy_list/?k=time&d=desc"
sources(104) = "http://www.my-proxy.com/free-proxy-list.html"
sources(105) = "http://www.my-proxy.com/free-proxy-list-2.html"
sources(106) = "http://www.my-proxy.com/free-proxy-list-3.html"
sources(107) = "http://www.my-proxy.com/free-proxy-list-4.html"
sources(108) = "http://www.my-proxy.com/free-proxy-list-5.html"
sources(109) = "http://www.my-proxy.com/free-proxy-list-6.html"
sources(110) = "http://www.my-proxy.com/free-proxy-list-7.html"
sources(111) = "http://www.my-proxy.com/free-proxy-list-8.html"
sources(112) = "http://www.my-proxy.com/free-proxy-list-9.html"
sources(113) = "http://www.my-proxy.com/free-proxy-list-10.html"
sources(114) = "http://sslproxies24.blogspot.com/feeds/posts/default"
sources(115) = "http://proxyserverlist-24.blogspot.com/feeds/posts/default"
sources(116) = "http://newfreshproxies24.blogspot.com/feeds/posts/default"
sources(117) = "http://socksproxylist24.blogspot.com/feeds/posts/default"
sources(118) = "http://vip-socks24.blogspot.com/feeds/posts/default"
sources(119) = "http://irc-proxies24.blogspot.com/feeds/posts/default"
sources(120) = "http://www.socks24.org/feeds/posts/default"
sources(121) = "http://www.getproxy.jp/en/"
sources(122) = "http://www.getproxy.jp/en/fastest"
'Add the Copyright Holder to the top of the List;
ListBox1.Items.Add("Proxies Scraped using a Test Build Program by ShinyMK")
'Foreach Source, Do the following Code;
For Each element As String In sources
'Set the Status Label to "Scraping";
ToolStripStatusLabel3.Text = "Scraping"
'Connect to the Proxy Source;
Dim source As Net.HttpWebRequest = Net.WebRequest.Create(element)
Try
'Prepare the Response;
Dim response As Net.HttpWebResponse = source.GetResponse
'Load the HTML;
Dim reader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
Dim html As String = reader.ReadToEnd
'Regex;
Dim expression As New Regex("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,4}")
'Set the Matches variable to the Matched Sections of the HTML source;
Dim matches As MatchCollection = expression.Matches(html)
'Add the proxies to the ListBox;
For Each proxy As Match In matches
'If the ListBox doesn't already contain the Proxy, Add It;
If Not ListBox1.Items.Contains(proxy.ToString) Then
'Add the Proxy;
ListBox1.Items.Add(proxy.ToString)
'Add 1 to the "Count" label's value;
ToolStripStatusLabel5.Text += 1
End If
Next
'Add the Time and Success message for each Successful Scraped Source;
ListBox2.Items.Add("[" + time + "] Success: " + element)
Catch ex As Exception
ListBox2.Items.Add("[" + time + "] ERROR Scraping from " + element + " - " + ex.Message)
End Try
Next
'Re-Enable the Button and set the Status Lable to "Idle";
Button1.Enabled = True
ToolStripStatusLabel3.Text = "Idle"
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If ListBox1.Items.Count = (0) Then
MessageBox.Show("No Proxies Scraped.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'defining a streamwriter
Dim S_W As IO.StreamWriter
'converting listbox items to string
Dim itms() As String = {ListBox1.Items.ToString}
''defining a savefiledialog
Dim save As New SaveFileDialog
Dim it As Integer
save.FileName = "SSLPro.xyz " + TimeOfDay.ToString("h.mm.ss tt")
save.Filter = "Text (*.txt)|*.txt|All Files (*.*)|*.*"
save.CheckPathExists = True
save.ShowDialog(Me)
S_W = New IO.StreamWriter(save.FileName)
For it = 0 To ListBox1.Items.Count - 1
S_W.WriteLine(ListBox1.Items.Item(it))
Next
S_W.Close()
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ListBox1.Items.Clear()
ListBox2.Items.Clear()
ToolStripStatusLabel5.Text = "0"
End Sub
End Class
To allow your UI thread to refresh and show the information while you’re iterating through the proxies you need to use a separate thread to do the job.
You can use the .NET control Backgroundworker to do this. With this control you can start a thread to do the job and this thread can inform the UI thread of the state of the operation using the events of the Brackgroundworker, then the UI thread can update the UI accordingly.
Here you can find some examples of how to use a backgroundworker.
A basic sample of this could be something like:
Imports System.ComponentModel
Public Class Form1
Private ListOfProcessedElements as List(of integer)
Private Sub backgroundWorker1_DoWork(ByVal sender As System.Object,ByVal e As DoWorkEventArgs) Handles backgroundWorker1.DoWork
'Here you do your worker
'Add an element to the list of Processed elements
ListOfProcessedElements.add(ANY_NUMBER)
worker.ReportProgress(i * 10)
End Sub
' This event handler updates the progress.
Private Sub backgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As ProgressChangedEventArgs) Handles backgroundWorker1.ProgressChanged
'Here you can access to the shared variable ListOfProcessedElements and do whatever you want in the UI
End Sub
' This event handler deals with the results of the background operation.
Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As RunWorkerCompletedEventArgs) Handles backgroundWorker1.RunWorkerCompleted
End Sub
End Class

dynamic table and button creation in asp.net

I have created a dynamic table using for loop condition.In which it has a button while i click a specific button it should open a file.But in my coding it is opening a file button in the last row.
If Not IsPostBack Then
txtlogsdate.Text = FormatDate(Now)
End If
Try
trViewlogs.Visible = True
lbllogs.Visible = False
lbllogname.Visible = True
RT1.Visible = False
pb.Visible = False
Dim d1 As DateTime = txtlogsdate.Text
Dim dd As String = d1.ToString("dd")
Dim mm As String = d1.ToString("MM")
Dim yy As String = d1.ToString("yy")
Dim d2 As String = yy & "" & mm & "" & dd
Dim di As DirectoryInfo = New DirectoryInfo(Server.MapPath("~\logs"))
Dim files As FileInfo() = di.GetFiles("*.log")
Dim tab As New Table()
tab.CellPadding = 0
tab.CellSpacing = 0
tab.BorderStyle = BorderStyle.Double
tab.Attributes.Add("style", "margin-left: 0.5px; width: 800px;")
Dim row As New TableRow()
Dim headerCell1 As New TableHeaderCell()
headerCell1.Text = "Logs"
headerCell1.Attributes.Add("style", "margin-left: 0.5px; height: 20px;")
headerCell1.BackColor = System.Drawing.Color.CornflowerBlue
headerCell1.ForeColor = System.Drawing.Color.White
row.Controls.Add(headerCell1)
tab.Controls.Add(row)
Dim headerCell2 = New TableHeaderCell()
headerCell2.Attributes.Add("style", "margin-left: 0.5px; height: 20px;")
headerCell2.BackColor = System.Drawing.Color.CornflowerBlue
headerCell2.ForeColor = System.Drawing.Color.White
headerCell2.Text = "Download"
row.Controls.Add(headerCell2)
tab.Controls.Add(row)
For i As Integer = 0 To files.Length - 1
Dim a As String = files(i).ToString.Replace("Event-", "")
Dim c As String = a.Substring(0, 6)
Dim sw As String
If d2 = c Then
sw = My.Computer.FileSystem.ReadAllText(_
GetWebSitePhysicalRoot & "\logs\" & files(i).ToString)
lbllogname.Text = files(i).ToString
lbllogname.Visible = False
row = New TableRow()
If i Mod 2 = 0 Then
row.BackColor = System.Drawing.Color.White
Else
row.BackColor = System.Drawing.Color.AliceBlue
End If
Dim cell As New TableCell()
cell.Text = lbllogname.Text
'cell.Width = New Unit("1000px")
cell.HorizontalAlign = HorizontalAlign.Center
row.Controls.Add(cell)
Dim cell2 As New TableCell()
Dim bt As New Button
bt.BorderStyle = BorderStyle.Solid
bt.Text = files(i).ToString
AddHandler bt.Click, AddressOf bt_Click
cell2.HorizontalAlign = HorizontalAlign.Center
cell2.Controls.Add(bt)
row.Controls.Add(cell2)
tab.Controls.Add(row)
Panel1.Controls.Add(tab)
End If
Next i
If lbllogname.Text = "" Then
lbllogname.Text = "No Logs to Display !"
End If
Session("pageurl") = ""
Session("pagecount") = ""
ib.SetInfo("Reports > View Logs", Infobar.InfoTypes.Caption)
Dim mi As Integer = GetQueryStringToInt("menuindex", 1)
If Not IsPostBack Then
leftmenu1.AddItem("View Logs", _
GetWebSiteUrlRoot & "/staff_rpt.aspx?rpt=logs&page=1&menuindex=" & mi)
End If
Catch ex As Exception
WriteLog(LogWriter.EventType.eError, ex.StackTrace.ToString)
End Try
Protected Sub bt_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs
Dim a As String
a = lbllogname.Text
Response.ContentType = "text/plain"
Response.AppendHeader("Content-Disposition", "attachment; filename=" & a)
Response.TransmitFile(Server.MapPath("~/logs/" & a))
Response.End()
End Sub
To use the dynamic table structure you have built in your code, then you need to uniquely name each button in each row; otherwise the button click handler (bt_Click) cannot figure out the correct row to open the file in, because they are all called the same and will use the last one.
Since you want a table structure, then I suggest you use the GridView server control, as it will provide similar output, but provide the ability to use templating to name the controls of each row the same, but allow for you to differentiate individual rows when a click event happens.

Creating a DataGridView Programatically and add clickable cells

Evening
I am struggling to achieve what I have set out todo! In a nutshell I am working with the Google Drive API to create an app in VB.net that allows you to view / download files etc.
Basically I am planning on using a couple of different api's for the different cloud provider s I have. The stage I have got to is that I have my collection of files and there various properties in a list. On load I am checking to see if a google account has been added to my program and if so creating a new tabpage on a tabcontrol, I then create the datagridview and add it to the collection on the new tab page. This works fine and displays all my data as is.
What I am trying to achieve is adding a clickable link to my download column instead of displaying the url. I have been trying to manipulate the code found here C# DataGridViewLinkCell Display after converting it to vb.net. This is basically what I have ended up with:
If My.Settings.GoogleClientID <> "" Then
Dim GD As New Properties.GDrive
GD.APIClientID = My.Settings.GoogleClientID
GD.APIClientSecret = My.Settings.GoogleClientSecret
clsDrive.GD = GD
clsDrive.GetSpace()
clsDrive.RefreshFiles()
Dim GoogleDriveTab As New TabPage
GoogleDriveTab.Text = "Google Drive"
tc_CloudManager.TabPages.Add(GoogleDriveTab)
Dim GoogleDriveDGV As New DataGridView
GoogleDriveDGV.Name = "GoogleDriveDGV"
GoogleDriveDGV.Dock = DockStyle.Fill
GoogleDriveDGV.Columns.Add("FileTitle", "File Title")
GoogleDriveDGV.Columns.Add("FileExtension", "File Extension")
GoogleDriveDGV.Columns.Add("FileSize", "File Size")
Dim dgvlc As New DataGridViewLinkColumn()
dgvlc.ActiveLinkColor = Color.Blue
dgvlc.HeaderText = "Download"
GoogleDriveDGV.Columns.Add(dgvlc)
GoogleDriveDGV.RowHeadersVisible = False
Dim c As New customcolumn()
GoogleDriveDGV.Columns.Add(c)
For i As Integer = 0 To GoogleDriveDGV.Columns.Count - 1
GoogleDriveDGV.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next
Try
For Each DriveFile In GD.DriveFiles
Dim row As DataGridViewRow = DirectCast(GoogleDriveDGV.Rows(0).Clone, DataGridViewRow)
Dim title As String = DriveFile.Title
If title.Length > 60 Then
title = title.Substring(0, 60)
End If
Dim fs As Integer = DriveFile.FileSize
Dim fsf As String
If fs > 1048576 Then
fsf = Math.Round(fs / 1048576, 2) & " MB"
Else
fsf = fs & " Bytes"
End If
Dim fe As String
If DriveFile.FileExtension = "" Then
fe = "Folder"
Else
fe = DriveFile.FileExtension
End If
row.Cells(0).Value = title
row.Cells(1).Value = fe
row.Cells(2).Value = fsf
row.Cells(3).Value = "Download File"
DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(3, DriveFile.DownloadUrl)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
GoogleDriveTab.Controls.Add(GoogleDriveDGV)
End If
End Sub
Class customcolumn
Inherits System.Windows.Forms.DataGridViewLinkColumn
Public urls As New Dictionary(Of Integer, String)()
End Class
Private Sub GoogleDriveDGV_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
For Each url As KeyValuePair(Of Integer, String) In DirectCast(GoogleDriveDGV.Columns(e.ColumnIndex), customcolumn).urls
If url.Key = e.RowIndex Then
Process.Start(url.Value)
Exit For
End If
Next
End Sub
I have two problems that I cant figure out:
1) GoogleDriveDGV is not declared here : For Each url As KeyValuePair(Of Integer, String) In DirectCast(GoogleDriveDGV.Columns(e.ColumnIndex), customcolumn).urls
2) If I comment out the GoogleDriveDGV_CellContentClick sub and just try to populate the datagridview I get System.InvalidCastException: Unable to cast object of type 'System.Windows.Forms.DataGridViewLinkColumn' to type 'customcolumn' here DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(3, DriveFile.DownloadUrl)
Can anyone let me know if what I am trying to achieve is possible and any hints?
Update!!!
I now have this:
If My.Settings.GoogleClientID <> "" Then
Dim GD As New Properties.GDrive
GD.APIClientID = My.Settings.GoogleClientID
GD.APIClientSecret = My.Settings.GoogleClientSecret
clsDrive.GD = GD
clsDrive.GetSpace()
clsDrive.RefreshFiles()
Dim GoogleDriveTab As New TabPage
GoogleDriveTab.Text = "Google Drive"
tc_CloudManager.TabPages.Add(GoogleDriveTab)
Dim GoogleDriveDGV As New DataGridView
GoogleDriveDGV.Name = "GoogleDriveDGV"
GoogleDriveDGV.Dock = DockStyle.Fill
GoogleDriveDGV.Columns.Add("FileTitle", "File Title")
GoogleDriveDGV.Columns.Add("FileExtension", "File Extension")
GoogleDriveDGV.Columns.Add("FileSize", "File Size")
Dim c As New customcolumn()
GoogleDriveDGV.Columns.Add(c)
GoogleDriveDGV.RowHeadersVisible = False
For i As Integer = 0 To GoogleDriveDGV.Columns.Count - 1
GoogleDriveDGV.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next
Dim trow As Integer = 0
Try
For Each DriveFile In GD.DriveFiles
Dim row As DataGridViewRow = DirectCast(GoogleDriveDGV.Rows(0).Clone, DataGridViewRow)
Dim title As String = DriveFile.Title
If title.Length > 60 Then
title = title.Substring(0, 60)
End If
Dim fs As Integer = DriveFile.FileSize
Dim fsf As String
If fs > 1048576 Then
fsf = Math.Round(fs / 1048576, 2) & " MB"
Else
fsf = fs & " Bytes"
End If
Dim fe As String
If DriveFile.FileExtension = "" Then
fe = "Folder"
Else
fe = DriveFile.FileExtension
End If
row.Cells(0).Value = title
row.Cells(1).Value = fe
row.Cells(2).Value = fsf
row.Cells(3).Value = "Download"
DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(trow, DriveFile.DownloadUrl)
GoogleDriveDGV.Rows.Add(row)
trow = trow + 1
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
GoogleDriveTab.Controls.Add(GoogleDriveDGV)
End If
End Sub
Class customcolumn
Inherits System.Windows.Forms.DataGridViewLinkColumn
Public urls As New Dictionary(Of Integer, String)()
End Class
'Private Sub GoogleDriveDGV_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
' For Each url As KeyValuePair(Of Integer, String) In DirectCast(GoogleDriveDGV.Columns(e.ColumnIndex), customcolumn).urls
' If url.Key = e.RowIndex Then
' Process.Start(url.Value)
' Exit For
' End If
' Next
'End Sub
Which is almost there, I now have the datagridview filled with the items and a download link, just cant work out how to solve issue 1 above :-(
Would you believe it I worked it out :-)
Basically I needed to add a handler.
Full code:
Private Sub CloudManager_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Settings.GoogleClientID <> "" Then
Dim GD As New Properties.GDrive
GD.APIClientID = My.Settings.GoogleClientID
GD.APIClientSecret = My.Settings.GoogleClientSecret
clsDrive.GD = GD
clsDrive.GetSpace()
clsDrive.RefreshFiles()
Dim GoogleDriveTab As New TabPage
GoogleDriveTab.Text = "Google Drive"
tc_CloudManager.TabPages.Add(GoogleDriveTab)
Dim GoogleDriveDGV As New DataGridView
GoogleDriveDGV.Name = "GoogleDriveDGV"
GoogleDriveDGV.Dock = DockStyle.Fill
GoogleDriveDGV.Columns.Add("FileTitle", "File Title")
GoogleDriveDGV.Columns.Add("FileExtension", "File Extension")
GoogleDriveDGV.Columns.Add("FileSize", "File Size")
Dim c As New customcolumn()
GoogleDriveDGV.Columns.Add(c)
AddHandler GoogleDriveDGV.CellContentClick, AddressOf GoogleDriveDGV_CellContentClick
GoogleDriveDGV.RowHeadersVisible = False
For i As Integer = 0 To GoogleDriveDGV.Columns.Count - 1
GoogleDriveDGV.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next
Dim trow As Integer = 0
Try
For Each DriveFile In GD.DriveFiles
Dim row As DataGridViewRow = DirectCast(GoogleDriveDGV.Rows(0).Clone, DataGridViewRow)
Dim title As String = DriveFile.Title
If title.Length > 60 Then
title = title.Substring(0, 60)
End If
Dim fs As Integer = DriveFile.FileSize
Dim fsf As String
If fs > 1048576 Then
fsf = Math.Round(fs / 1048576, 2) & " MB"
Else
fsf = fs & " Bytes"
End If
Dim fe As String
If DriveFile.FileExtension = "" Then
fe = "Folder"
Else
fe = DriveFile.FileExtension
End If
row.Cells(0).Value = title
row.Cells(1).Value = fe
row.Cells(2).Value = fsf
row.Cells(3).Value = "Download"
DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(trow, DriveFile.DownloadUrl)
GoogleDriveDGV.Rows.Add(row)
trow = trow + 1
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
GoogleDriveTab.Controls.Add(GoogleDriveDGV)
End If
End Sub
Class customcolumn
Inherits System.Windows.Forms.DataGridViewLinkColumn
Public urls As New Dictionary(Of Integer, String)()
End Class
Private Sub GoogleDriveDGV_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
For Each url As KeyValuePair(Of Integer, String) In DirectCast(sender.Columns(e.ColumnIndex), customcolumn).urls
If url.Key = e.RowIndex Then
Process.Start(url.Value)
Exit For
End If
Next
End Sub
End Class

loop data in datalist

How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.
Protected Sub DataList2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList2.ItemDataBound
For Each li As DataListItem In DataList2.Items
Dim labelasd As Label = DirectCast(e.Item.FindControl("**Label8**"), Label)
Dim reviewid As Integer = labelasd.Text
Dim connectionString As String = _
ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "Select Count(reviewYes) AS Expr1 From ProductReviewHelp Where ProductReviewID = " & reviewid & ""
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim countofreview As Integer = 0
Dim reviewcountboolean As Boolean
If (reader.Read()) Then
If (IsDBNull(reader.GetValue(0)) = False) Then
countofreview = reader.GetValue(0)
End If
End If
If countofreview = 0 Then
reviewcountboolean = False
Else
reviewcountboolean = True
End If
If (reviewcountboolean = True) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "Hello"
ElseIf (reviewcountboolean = False) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "No"
End If
Next
End Sub
How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.
You are looping on your DataList2 items but, at every loop, you update the label7 with the logic of the current item, effectively removing the result of the previous loop. This means that, when you reach the last item, the Label7 will reflect the string "Hello" or "No" depending on the logic applied to the last item in your loop.
Apart from this logical error, you have also numerous errors in the code shown.
The connection is never closed.
You use string concatenation instead of parameters.
You use ExecuteReader when in this case an ExecuteScalar is better
suited.
You can iterate through then using a loop here is an example
Try
readFromDL1 = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
readFromQ = DirectCast(SqlDataSource7.Select(DataSourceSelectArguments.Empty), DataView)
Catch ex As Exception
End Try
'End
'datalist1
i = 0
_rowCount = DataList1.Items.Count
If _rowCount > 0 Then
_getCall = DataList1.Items.Item(i).FindControl("lnkEdit")
End If
For Each readr As DataRowView In readFromQ
findQNumber = readr(1).ToString()
For Each readfdlr1 As DataRowView In readFromDL1
findQNumber1 = readfdlr1(1).ToString
Try
indexofitems = DataList1.Items.Item(i1).ItemIndex
If findQNumber.ToString = findQNumber1.ToString Then
_getCall = DataList1.Items.Item(indexofitems).FindControl("lnkEdit")
_getCall.Text = "Called"
_getCall.Enabled = False
_getCall.ForeColor = Drawing.Color.Red
_getCall.BackColor = Drawing.Color.Yellow
End If
i1 = i1 + 1
Catch e As Exception
End Try
Next
i1 = 0
i = i + 1