I am dynamically building a datatable and binding it to a gridview in a VB codebehind. I transform the gridview cell data into LinkButton controls to allow that data to be clicked for updates.
I am using AjaxControlToolkit to present a modal popup to collect data updates. Once those updates are completed, I rebuild the datatable and databind the gridview. In Gridview.RowCreated, I repeat the creation of the LinkButton controls on postback.
When the page is presented following an update, when I click on a LinkButton the postback happens but RowCommand is not fired. While debugging, I notice that when this occurs, Page.FindControl() cannot locate the targeted LinkButton control.
The page is returned without firing the RowCommand event to trigger the display of the modal popup. If I simply press the LinkButton a second time, the LinkButton control can be found using Page.FindControl() and RowCommand fires as desired.
What am I missing? Thanks much for any ideas to resolve this issue. I have struggled with this all day and I'm running out of ideas.
Thank you!
Here is requested code:
<asp:GridView ID="CustomeGridview" GridLines="Vertical" Width="100%" runat="server"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" AutoGenerateColumns="true" ForeColor="Black" ShowHeader="False" Font-Names="Verdana"
Font-Size="11px" OnRowCommand="CustomeGridview_RowCommand"
OnRowDataBound="CustomeGridview_RowDataBound">
<FooterStyle BackColor="#CCCCCC" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.CacheControl = "no-cache"
Response.Expires = -1
Response.AddHeader("Pragma", "no-cache")
If Page.IsPostBack = False Then
ViewState("Left") = 3
ViewState("Right") = 6
generateManualDt()
Else
Dim controlName As String = Request.Params.Get("__EVENTTARGET")
Dim ctl As Control = Page.FindControl(controlName)
End If
Page_Header_Label.Text = "Action Qualification Matrix - " & Session("CurrentServiceName")
FormatColumns()
End Sub
Public Sub generateManualDt()
Dim ManualDt As DataTable = BuildMainDataTable()
ViewState("ManualDt") = ManualDt
CustomeGridview.DataSource = ManualDt
CustomeGridview.DataBind()
SetJumpScrollButtons()
End Sub
Protected Sub CustomeGridview_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles CustomeGridview.RowDataBound
Dim dt As DataTable = DirectCast(ViewState("ManualDt"), DataTable)
Dim dtsnocol As DataTable = DirectCast(ViewState("dtsnocol"), DataTable)
If e.Row.RowType = DataControlRowType.DataRow OrElse e.Row.RowType = DataControlRowType.Header Then
For gvCol As Integer = 7 To dt.Columns.Count - 1
e.Row.Cells(gvCol).Visible = False
Next
SetupGridRowControls(e, dtsnocol, dt)
End If
End Sub
Protected Sub CustomeGridview_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles CustomeGridview.RowCreated
Dim dt As DataTable = DirectCast(ViewState("ManualDt"), DataTable)
Dim dtsnocol As DataTable = DirectCast(ViewState("dtsnocol"), DataTable)
e.Row.Cells(0).Visible = False ' Hide the QuestionID column
If Page.IsPostBack Then
If e.Row.RowType = DataControlRowType.DataRow OrElse e.Row.RowType = DataControlRowType.Header Then
SetupGridRowControls(e, dtsnocol, dt)
End If
End If
End Sub
Private Sub SetupGridRowControls(ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs, ByRef dtsnocol As DataTable, ByRef mainDt As DataTable)
Dim CurrSnoCount As Integer = 0
If Not dtsnocol Is Nothing Then
CurrSnoCount = dtsnocol.Rows.Count
End If
If e.Row.DataItemIndex = 0 Then ' Scenario Number row
Dim snoLabel As New Label()
snoLabel.Text = "SCENARIO "
snoLabel.ID = "snoHdrLabel"
e.Row.Cells(2).Controls.Add(snoLabel)
Dim addScenarioBtn = buildAddButton("AddScenario", "", "Click to add a new scenario column")
e.Row.Cells(2).Controls.Add(addScenarioBtn)
ElseIf e.Row.DataItemIndex = 1 Then ' Question Header and Sno Descriptions
Dim questLabel As New Label()
questLabel.Text = "QUESTIONS "
questLabel.ID = "questdrLabel"
e.Row.Cells(2).Controls.Add(questLabel)
Dim addQuestionBtn = buildAddButton("AddQuestion", "", "Click to add a new question row")
e.Row.Cells(2).Controls.Add(addQuestionBtn)
Dim cellText As String = ""
Dim snoId As String = ""
For snoRowIdx As Integer = 0 To CurrSnoCount - 1
snoId = dtsnocol.Rows(snoRowIdx)("ScenarioID").ToString()
cellText = dtsnocol.Rows(snoRowIdx)("Note").ToString()
Dim lnkBtn = buildLinkButton("EditScenario", snoId, cellText)
e.Row.Cells(snoRowIdx + 3).Controls.Add(lnkBtn)
Next
ElseIf e.Row.DataItemIndex > 1 Then ' Question / Responses
Dim cellText As String = ""
Dim cellAddr As String = ""
Dim snoId As String = ""
Dim questId As String = mainDt.Rows(e.Row.DataItemIndex).Item(0).ToString.Trim
For snoRowIdx As Integer = 0 To CurrSnoCount - 1
snoId = dtsnocol.Rows(snoRowIdx)("ScenarioID").ToString.Trim
cellAddr = String.Format("{0}:{1}", questId, snoId)
cellText = mainDt.Rows(e.Row.DataItemIndex).Item(snoRowIdx + 3).ToString.Trim
Dim lnkBtn = buildLinkButton("EditResponses", cellAddr, cellText)
e.Row.Cells(snoRowIdx + 3).Controls.Add(lnkBtn)
Next
End If
End Sub
Private Function buildLinkButton(ByVal linkCmd As String, ByVal linkCmdArg As String, ByVal linkText As String) As LinkButton
Dim lnkBtn As New LinkButton()
lnkBtn.Text = linkText
lnkBtn.CommandName = linkCmd
lnkBtn.CommandArgument = linkCmdArg
lnkBtn.ToolTip = "Click to update"
lnkBtn.CssClass = "cell_link"
Return lnkBtn
End Function
Private Function buildAddButton(ByVal btnCmd As String, ByVal btnCmdArg As String, ByVal btnToolTip As String) As ImageButton
Dim imgBtn As New ImageButton()
imgBtn.CommandName = btnCmd
imgBtn.CommandArgument = btnCmdArg
imgBtn.ImageUrl = "~/Images/services/SmallAddBtn.gif"
imgBtn.ToolTip = btnToolTip
imgBtn.ID = String.Format("{0}_GenImageButton", btnCmd)
Return imgBtn
End Function
Related
i'm a junior developer and i started working recently.
They put me on this LEGACY program and asked me to try and resolve this problem.
They strictly forbid me of using CLOB.
Dim fs As Stream = PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
pdfComunication = pdfConvert(bytes)
pdfComunication = bytes
idOperator = ViewState("idOperator")
'
Private Function pdfConvert(ByVal document As Byte()) As Byte()
Dim doc As Byte()
Using msRtf As MemoryStream = New MemoryStream(document)
Dim dc As softDocument.DocumentCore = softDocument.DocumentCore.Load(msRtf, New softDocument.DocxLoadOptions())
Using msDocx As MemoryStream = New MemoryStream()
dc.Save(msDocx, New softDocument.PdfSaveOptions())
doc = msDocx.ToArray()
End Using
End Using
Return doc
End Function
'
<WebMethod()>
Public Function InsertComunications(ByVal pIdComunicationType As Integer, ByVal pAwaitingStatus As Integer, ByVal pRequestingUser As String, ByVal pIdSr As String,
ByVal pItem As String, ByVal pText As String, ByVal pCommonSender As String, pPecSender As String, ByVal pDestination As String,
ByVal pPdfComunication As Byte()) As String
Dim dbConn As New OracleConnection
Dim cmd As New OracleCommand
Dim errMsg As String = String.Empty
dbConn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("DBConn").ToString
Try
dbConn.Open()
cmd.Parameters.Clear()
cmd.CommandText = ""
cmd.CommandType = System.Data.CommandType.StoredProcedure
cmd.Connection = dbConn
Dim p_IdComunicationType As New System.Data.OracleClient.OracleParameter("p_IdComunicationType ", System.Data.OracleClient.OracleType.Number)
p_IdComunicationType.Direction = ParameterDirection.Input
p_IdComunicationType.Value = pIdComunicationType
cmd.Parameters.Add(p_IdComunicationType)
Dim p_AwaitingStatus As New System.Data.OracleClient.OracleParameter("p_AwaitingStatus", System.Data.OracleClient.OracleType.Number)
p_AwaitingStatus.Direction = ParameterDirection.Input
p_AwaitingStatus.Value = pAwaitingStatus
cmd.Parameters.Add(p_AwaitingStatus)
Dim p_RequestingUser As New System.Data.OracleClient.OracleParameter("p_RequestingUser ", System.Data.OracleClient.OracleType.NVarChar)
p_RequestingUser.Direction = ParameterDirection.Input
p_RequestingUser.Value = pRequestingUser
cmd.Parameters.Add(p_RequestingUser)
Dim p_IdSr As New System.Data.OracleClient.OracleParameter("p_IdSr", System.Data.OracleClient.OracleType.NVarChar)
p_IdSr.Direction = ParameterDirection.Input
p_IdSr.Value = pIdSr
cmd.Parameters.Add(p_IdSr)
Dim p_Item As New System.Data.OracleClient.OracleParameter("p_Item", System.Data.OracleClient.OracleType.NVarChar)
p_Item.Direction = ParameterDirection.Input
p_Item.Value = pItem
cmd.Parameters.Add(p_Item)
Dim p_Text As New System.Data.OracleClient.OracleParameter("p_Text", System.Data.OracleClient.OracleType.NVarChar)
p_Text.Direction = ParameterDirection.Input
p_Text.Value = pText
cmd.Parameters.Add(p_Text)
Dim p_CommonSender As New System.Data.OracleClient.OracleParameter("p_CommonSender", System.Data.OracleClient.OracleType.NVarChar)
p_CommonSender.Direction = ParameterDirection.Input
p_CommonSender.Value = pCommonSender
cmd.Parameters.Add(p_CommonSender)
Dim p_PecSender As New System.Data.OracleClient.OracleParameter("p_PecSender", System.Data.OracleClient.OracleType.NVarChar)
p_PecSender.Direction = ParameterDirection.Input
p_PecSender.Value = pPecSender
cmd.Parameters.Add(p_PecSender)
Dim p_Destination As New System.Data.OracleClient.OracleParameter("p_Destination", System.Data.OracleClient.OracleType.NVarChar)
p_Destination.Direction = ParameterDirection.Input
p_Destination.Value = pDestination
cmd.Parameters.Add(p_Destination)
Dim p_PdfComunication As New System.Data.OracleClient.OracleParameter("p_PdfComunication", System.Data.OracleClient.OracleType.Blob)
p_PdfComunication.Direction = ParameterDirection.InputOutput
p_PdfComunication.Value = pPdfComunication
cmd.Parameters.Add(p_PdfComunication)
cmd.ExecuteNonQuery()
Finally
dbConn.Dispose()
cmd.Dispose()
End Try
'
The problem is that the file size is too big for the blob in the db, which is strange since in other parts of the program that don't do the conversion it takes files way bigger than the ones i'm trying right now...
Any suggestions?
'EDIT
TYPE t_Cursor IS REF CURSOR;
PROCEDURE GetMailTemplate(Cur_Out OUT t_Cursor);
PROCEDURE 1(p_IdComunicationType IN NUMBER,
p_AwaitingStatus IN NUMBER,
p_RequestingUser IN VARCHAR2,
p_IdSr IN VARCHAR2,
p_Item IN VARCHAR2,
p_Testo IN VARCHAR2,
p_CommonSender IN VARCHAR2,
p_PecSender IN VARCHAR2,
p_Destination IN VARCHAR2,
p_PdfComunication xx.PDF_COMUNICATION%Type
);
PROCEDURE 2( p_AwaytingStatus NUMBER, Cur_Out OUT t_Cursor);
PROCEDURE 3(p_IdComunicationType VARCHAR2,
p_AwaitingStatus NUMBER);
We finally found an answer, we had to put everything inside a TRANSACTION:
Public Function InsertComunications(ByVal pIdComunicationType As Integer, ByVal pAwaitingStatus As Integer, ByVal pRequestingUser As String, ByVal pIdSr As String,
ByVal pItem As String, ByVal pText As String, ByVal pCommonSender As String, pPecSender As String, ByVal pDestination As String,
ByVal pPdfComunication As Byte()) As String
Dim dbConn As New OracleConnection
**Dim trns as System.Data.OracleClient.OracleTransaction = Nothing**
Dim cmd As New OracleCommand
Dim errMsg As String = String.Empty
dbConn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("DBConn").ToString
Try
dbConn.Open()
**trns = dbConn.BeginTransaction**
**cmd.Transaction = trns**
cmd.Parameters.Clear()
cmd.CommandText = ""
cmd.CommandType = System.Data.CommandType.StoredProcedure
cmd.Connection = dbConn
Dim p_IdComunicationType As New System.Data.OracleClient.OracleParameter("p_IdComunicationType ", System.Data.OracleClient.OracleType.Number)
p_IdComunicationType.Direction = ParameterDirection.Input
p_IdComunicationType.Value = pIdComunicationType
cmd.Parameters.Add(p_IdComunicationType)
Dim p_AwaitingStatus As New System.Data.OracleClient.OracleParameter("p_AwaitingStatus", System.Data.OracleClient.OracleType.Number)
p_AwaitingStatus.Direction = ParameterDirection.Input
p_AwaitingStatus.Value = pAwaitingStatus
cmd.Parameters.Add(p_AwaitingStatus)
Dim p_RequestingUser As New System.Data.OracleClient.OracleParameter("p_RequestingUser ", System.Data.OracleClient.OracleType.NVarChar)
p_RequestingUser.Direction = ParameterDirection.Input
p_RequestingUser.Value = pRequestingUser
cmd.Parameters.Add(p_RequestingUser)
Dim p_IdSr As New System.Data.OracleClient.OracleParameter("p_IdSr", System.Data.OracleClient.OracleType.NVarChar)
p_IdSr.Direction = ParameterDirection.Input
p_IdSr.Value = pIdSr
cmd.Parameters.Add(p_IdSr)
Dim p_Item As New System.Data.OracleClient.OracleParameter("p_Item", System.Data.OracleClient.OracleType.NVarChar)
p_Item.Direction = ParameterDirection.Input
p_Item.Value = pItem
cmd.Parameters.Add(p_Item)
Dim p_Text As New System.Data.OracleClient.OracleParameter("p_Text", System.Data.OracleClient.OracleType.NVarChar)
p_Text.Direction = ParameterDirection.Input
p_Text.Value = pText
cmd.Parameters.Add(p_Text)
Dim p_CommonSender As New System.Data.OracleClient.OracleParameter("p_CommonSender", System.Data.OracleClient.OracleType.NVarChar)
p_CommonSender.Direction = ParameterDirection.Input
p_CommonSender.Value = pCommonSender
cmd.Parameters.Add(p_CommonSender)
Dim p_PecSender As New System.Data.OracleClient.OracleParameter("p_PecSender", System.Data.OracleClient.OracleType.NVarChar)
p_PecSender.Direction = ParameterDirection.Input
p_PecSender.Value = pPecSender
cmd.Parameters.Add(p_PecSender)
Dim p_Destination As New System.Data.OracleClient.OracleParameter("p_Destination", System.Data.OracleClient.OracleType.NVarChar)
p_Destination.Direction = ParameterDirection.Input
p_Destination.Value = pDestination
cmd.Parameters.Add(p_Destination)
Dim p_PdfComunication As New System.Data.OracleClient.OracleParameter("p_PdfComunication", System.Data.OracleClient.OracleType.Blob)
p_PdfComunication.Direction = ParameterDirection.InputOutput
p_PdfComunication.Value = pPdfComunication
cmd.Parameters.Add(p_PdfComunication)
cmd.ExecuteNonQuery()
**trns.Commit()**
Finally
dbConn.Dispose()
cmd.Dispose()
End Try
I designed a Form and it use to the sub Form
The Mainform is correctly display, but I use some action to show the sub Form and set Visible property of Mainform to false
The sub Form is displayed incorrectly
^^ Sub Form
^^ displayed
MainForm code:
Imports SearcherScreen = Osu_Offline_Searcher.My.SearcherScreen
Public Class SearcherOfOsu
Private ReadOnly SS As New SearcherScreen()
Private ReadOnly DOF As New DownloadOsuForm()
Private Sub Downloader_OnDownloadData(sender As OsuDownload.OsuDownloader, e As OsuDownload.OsuDownloader.DownloadDataEventArgs) Handles Downloader.DownloadData
If DOF.Created Then
DOF.ChangeProgressBar(e.Present)
Else
DOF.Icon = New Icon("osu!.ico")
DOF.Show()
Visible = False
End If
End Sub
Private Sub DetectButton_Click(sender As Object, e As EventArgs) Handles DetectButton.Click
Dim Detecter As New OsuDetect.DetectClass()
Dim UserDirectoryName = Detecter.DetectUserDirectory()
If UserDirectoryName = "No User" Then
MsgBox("I can't find any User.")
Else
Dim OsuDirectoryName = Detecter.DetectOsuDirectory(UserDirectoryName)
If OsuDirectoryName = "No Osu" Then
MsgBox("You don't download the Osu in defalut directory.")
Dim Result = MsgBox("Download Osu now?", MsgBoxStyle.YesNo, "Download Osu")
If Result = MsgBoxResult.Yes Then
OsuDirectoryPath.Text = Downloader.DownloadOsu(UserDirectoryName)
Visible = True
DOF.Close()
End If
Else
OsuDirectoryPath.Text = OsuDirectoryName
End If
End If
End Sub
Friend WithEvents Downloader As New OsuDownload.OsuDownloader()
End Class
Sub Form:
Public Class DownloadOsuForm
Sub ChangeProgressBar(Value As Integer)
OsuDownloadProgressBar.Value = Value
OsuDownloadLabel.Text = "Osu Downloading..."
End Sub
End Class
This the code of forms
and after here is the designer code
Sub Designer Code:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class DownloadOsuForm
Inherits System.Windows.Forms.Form
'Form 覆寫 Dispose 以清除元件清單。
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'為 Windows Form 設計工具的必要項
Private components As System.ComponentModel.IContainer
'注意: 以下為 Windows Form 設計工具所需的程序
'可以使用 Windows Form 設計工具進行修改。
'請勿使用程式碼編輯器進行修改。
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.OsuDownloadProgressBar = New System.Windows.Forms.ProgressBar()
Me.OsuDownloadLabel = New System.Windows.Forms.Label()
Me.SuspendLayout()
'
'OsuDownloadProgressBar
'
Me.OsuDownloadProgressBar.Location = New System.Drawing.Point(60, 205)
Me.OsuDownloadProgressBar.Minimum = 0
Me.OsuDownloadProgressBar.Maximum = 100
Me.OsuDownloadProgressBar.Value = 0
Me.OsuDownloadProgressBar.Name = "OsuDownloadProgressBar"
Me.OsuDownloadProgressBar.Size = New System.Drawing.Size(280, 30)
Me.OsuDownloadProgressBar.TabIndex = 0
'
'OsuDownloadLabel
'
Me.OsuDownloadLabel.AutoSize = True
Me.OsuDownloadLabel.Font = New System.Drawing.Font("新細明體", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.OsuDownloadLabel.Location = New System.Drawing.Point(105, 155)
Me.OsuDownloadLabel.Name = "OsuDownloadLabel"
Me.OsuDownloadLabel.Size = New System.Drawing.Size(190, 24)
Me.OsuDownloadLabel.TabIndex = 1
Me.OsuDownloadLabel.Text = "Osu Downloading..."
'
'DownloadOsuForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(9.0!, 18.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(400, 400)
Me.Controls.Add(Me.OsuDownloadLabel)
Me.Controls.Add(Me.OsuDownloadProgressBar)
Me.Margin = New System.Windows.Forms.Padding(1, 3, 1, 3)
Me.Name = "DownloadOsuForm"
Me.Text = "Downloading Osu"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents OsuDownloadProgressBar As ProgressBar
Friend WithEvents OsuDownloadLabel As Label
End Class
I found a script online to copy some files whilst also displaying a progress bar to the user. I wondered if it was possible to automate this process so the file copy initiates as soon as the program launches and then closes once completed. VB is not my strong point as I usually code in c sharp. Any help much appreciated.
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.IO
Public Class Form1
'--- Class to report progress
Private Class UIProgress
Public Sub New(ByVal name_ As String, ByVal bytes_ As Long, ByVal maxbytes_ As Long)
name = name_ : bytes = bytes_ : maxbytes = maxbytes_
End Sub
Public name As String
Public bytes As Long
Public maxbytes As Long
End Class
'--- Class to report exception
Private Class UIError
Public Sub New(ByVal ex As Exception, ByVal path_ As String)
msg = ex.Message : path = path_ : result = DialogResult.Cancel
End Sub
Public msg As String
Public path As String
Public result As DialogResult
End Class
'--- Members
Private mCopier As New BackgroundWorker
Private Delegate Sub ProgressChanged(ByVal info As UIProgress)
Private Delegate Sub CopyError(ByVal err As UIError)
Private OnChange As ProgressChanged
Private OnError As CopyError
Public Sub New()
InitializeComponent()
AddHandler mCopier.DoWork, AddressOf Copier_DoWork
AddHandler mCopier.RunWorkerCompleted, AddressOf Copier_RunWorkerCompleted
mCopier.WorkerSupportsCancellation = False
OnChange = AddressOf Copier_ProgressChanged
OnError = AddressOf Copier_Error
ChangeUI(False)
mCopier.RunWorkerAsync()
End Sub
Private Sub Copier_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
'--- Create list of files to copy
Dim theExtensions As String() = {"*.jpg", "*.jpeg", "*.bmp", "*.png", "*.gif"}
Dim files As New List(Of FileInfo)
Dim path As String = "c:\users\simon\desktop\b\"
Dim dir As New DirectoryInfo(path)
Dim maxbytes As Long = 0
For Each ext As String In theExtensions
Dim folder As FileInfo() = dir.GetFiles(ext, SearchOption.AllDirectories)
For Each file As FileInfo In folder
If ((file.Attributes And FileAttributes.Directory) <> 0) Then Continue For
files.Add(file)
maxbytes += file.Length
Next
Next
'--- Copy files
Dim bytes As Long = 0
For Each file As FileInfo In files
Try
Me.BeginInvoke(OnChange, New Object() {New UIProgress(file.Name, bytes, maxbytes)})
System.IO.File.Copy(file.FullName, "C:\Users\Simon\Desktop\t\" + file.Name, True)
Catch ex As Exception
Dim err As New UIError(ex, file.FullName)
Me.Invoke(OnError, New Object() {err})
If err.result = DialogResult.Cancel Then Exit For
End Try
bytes += file.Length
Next
End Sub
Private Sub Copier_ProgressChanged(ByVal info As UIProgress)
'--- Update progress
ProgressBar1.Value = CInt(100.0 * info.bytes / info.maxbytes)
Label1.Text = "Copying " + info.name
End Sub
Private Sub Copier_Error(ByVal err As UIError)
'--- Error handler
Dim msg As String = String.Format("Error copying file {0}\n{1}\nClick OK to continue copying files", Err.path, Err.msg)
err.result = MessageBox.Show(msg, "Copy error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation)
End Sub
Private Sub Copier_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
'--- Operation completed, update UI
ChangeUI(False)
End Sub
Private Sub ChangeUI(ByVal docopy As Boolean)
Label1.Visible = docopy
ProgressBar1.Visible = docopy
If docopy Then Button1.Enabled = False Else Button1.Text = "Copy"
Label1.Text = "Starting copy..."
ProgressBar1.Value = 0
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim docopy As Boolean = Button1.Text = "Copy"
ChangeUI(docopy)
If (docopy) Then mCopier.RunWorkerAsync() Else mCopier.CancelAsync()
End Sub
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click
End Sub
End Class
Just move the code that you have in Button1_Click into the Form_Load event.
Or, alternatively, you could just call the Button1_Click routine from the Form_Load.
Also, FYI, some VB.net tips for C# programmers:
you generally don't need to do the dynamic AddHandler setups in VB.net
This dynamic setup is usually replaced by the static Handles clause of the method declarations, which is auto-generated for you if you use the IDE Control/Event drop-downs
you probably do need "Private With Events ..." for your BackgroundWorker declaration.
Why not convert the code to C#?
http://www.developerfusion.com/tools/convert/vb-to-csharp/
http://converter.telerik.com/
http://codeconverter.sharpdevelop.net/SnippetConverter.aspx
http://www.dotnetspider.com/convert/Vb-To-Csharp.aspx
I'm using MVC3 and I need a HTMLHelper with image, so I found a nice code, the problem is that the image is not shown instead of I see html code ex:
<a href='whatever'><img src="images/printer.png" /></a>
Maybe this is because the helper is inside a webgrid helper, I really don't know, any suggestion?
Helper
<Extension()> _
Public Function ActionLinkWithImage(ByVal helper As HtmlHelper, ByVal actionName As String, ByVal controllerName As String, ByVal imageUrl As String, ByVal alternateText As String, ByVal routeValues As Object, ByVal linkHtmlAttributes As Object, ByVal imageHtmlAttributes As Object) As String
Dim urlHelper = New UrlHelper(helper.ViewContext.RequestContext)
Dim url = urlHelper.Action(actionName, controllerName, routeValues)
' Create link
Dim linkTagBuilder = New TagBuilder("a")
linkTagBuilder.MergeAttribute("href", url)
linkTagBuilder.MergeAttributes(New RouteValueDictionary(linkHtmlAttributes))
' Create image
Dim imageTagBuilder = New TagBuilder("img")
imageTagBuilder.MergeAttribute("src", urlHelper.Content(imageUrl))
imageTagBuilder.MergeAttribute("alt", urlHelper.Encode(alternateText))
imageTagBuilder.MergeAttributes(New RouteValueDictionary(imageHtmlAttributes))
' Add image to link
linkTagBuilder.InnerHtml = imageTagBuilder.ToString(TagRenderMode.SelfClosing)
Return linkTagBuilder.ToString()
End Function
WebGrid load
#<div id="divGrid">
#grid.GetHtml(
tableStyle:="webgrid",
headerStyle:="webgrid-header",
footerStyle:="webgrid-footer",
alternatingRowStyle:="webgrid-alternating-row",
selectedRowStyle:="webgrid-selected-row",
rowStyle:="webgrid-row-style",
mode:=WebGridPagerModes.All,
firstText:="<< Inicio",
previousText:="< Anterior",
nextText:="Siguiente >",
lastText:="Fin >>",
columns:=grid.Columns(
grid.Column(format:=Function(Model) Html.ActionLink(" ", "Details", "CertificadoVehiculo", New With {.area = "Certificados", .parIDCertificado = Model.ID_CERTIFICADO, .parIDPoliza = Model.ID_POLIZA}, New With {.class = "imgConsultar", .title = "Consultar"}), style:="webgrid-width-images"),
grid.Column(format:=Function(Model) Html.ActionLink(" ", "Edit", "CertificadoVehiculo", New With {.area = "Certificados", .parIDCertificado = Model.ID_CERTIFICADO, .parIDPoliza = Model.ID_POLIZA}, New With {.class = "imgEditar", .title = "Modificar"}), style:="webgrid-width-images"),
grid.Column(format:=Function(Model) Html.ActionLinkWithImage("Action", "Controller", Url.Content("~/Images/printer.png"), "TextoAlternativo", Nothing, Nothing, Nothing), style:="webgrid-width-images"),
grid.Column("ID_CERTIFICADO", "No. Certificado"),
grid.Column("POLIZAS.NUMERO_POLIZA", "No. Poliza"),
grid.Column("PRIMER_APELLIDO_ASEGURADO", "Asegurado", format:=Function(Model) Model.ASEGURADOS.PRIMER_APELLIDO_ASEGURADO & " " & Model.ASEGURADOS.SEGUNDO_APELLIDO_ASEGURADO & " " & Model.ASEGURADOS.NOMBRES_ASEGURADO),
grid.Column("PRIMA_CERTIFICADO", "Prima Total"),
grid.Column("ESTADOS.DESC_ESTADO", "Estado")
)
)
</div>
Make the ActionLinkWithImage helper return MvcHtmlString instead of string. Like this:
<Extension()> _
Public Function ActionLinkWithImage(ByVal helper As HtmlHelper, ByVal actionName As String, ByVal controllerName As String, ByVal imageUrl As String, ByVal alternateText As String, ByVal routeValues As Object, ByVal linkHtmlAttributes As Object, ByVal imageHtmlAttributes As Object) As MvcHtmlString
Dim urlHelper = New UrlHelper(helper.ViewContext.RequestContext)
Dim url = urlHelper.Action(actionName, controllerName, routeValues)
' Create link
Dim linkTagBuilder = New TagBuilder("a")
linkTagBuilder.MergeAttribute("href", url)
linkTagBuilder.MergeAttributes(New RouteValueDictionary(linkHtmlAttributes))
' Create image
Dim imageTagBuilder = New TagBuilder("img")
imageTagBuilder.MergeAttribute("src", urlHelper.Content(imageUrl))
imageTagBuilder.MergeAttribute("alt", urlHelper.Encode(alternateText))
imageTagBuilder.MergeAttributes(New RouteValueDictionary(imageHtmlAttributes))
' Add image to link
linkTagBuilder.InnerHtml = imageTagBuilder.ToString(TagRenderMode.SelfClosing)
Return MvcHtmlString.Create(linkTagBuilder.ToString())
End Function
I have a Winforms application and a combobox has it's datasource set to a DataTable when the form loads. The data displays fine in the combobox.
Then after a user clicks a button I want to create a new DataTable and assign that datatable as the datasource for the combobox.
The problem is that after setting the datasource to be the new datatable the items in the combobox don't change. Here is the code I'm using.
dlCustomer.DataSource = Nothing
dlCustomer.DataSource = dtCustomers
dlCustomer.DisplayMember = "Name"
dlCustomer.Refresh()
Does anyone know how to make the correct data be displayed in the combobox the second time I assign the data source for it?
It should work, at least it did in a quick test I threw together. Here's the code; it just expects a Form with a ComboBox and Button:
Public Class Form1
Private dtOne As DataTable
Private dtTwo As DataTable
Private Sub InitializeTables()
dtOne = New DataTable("TableOne")
With dtOne
.Columns.Add("Text", GetType(String))
.Columns.Add("Value", GetType(Integer))
End With
dtTwo = New DataTable("TableTwo")
With dtTwo
.Columns.Add("Text", GetType(String))
.Columns.Add("Value", GetType(Integer))
End With
Dim newRow As DataRow
For index As Integer = 0 To 2
newRow = dtOne.NewRow
newRow.ItemArray = (New Object() {SpellIt(index), index})
dtOne.Rows.Add(newRow)
Next
For index As Integer = 2 To 0 Step -1
newRow = dtTwo.NewRow
newRow.ItemArray = (New Object() {SpellIt(index), index})
dtTwo.Rows.Add(newRow)
Next
dtOne.AcceptChanges()
dtTwo.AcceptChanges()
End Sub
Private Shared Function SpellIt(ByVal int As Integer) As String
Select Case int
Case 0 : Return "Zero"
Case 1 : Return "One"
Case 2 : Return "Two"
Case Else : Throw New ArgumentOutOfRangeException("Bleh!")
End Select
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
InitializeTables()
Me.Label1.DataBindings.Add("Text", ComboBox1, "SelectedValue")
Me.ComboBox1.DataSource = dtOne
Me.ComboBox1.DisplayMember = "Text"
Me.ComboBox1.ValueMember = "Value"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.ComboBox1.DataBindings.Clear()
Me.ComboBox1.DataSource = Nothing
Me.ComboBox1.DataSource = dtTwo
Me.ComboBox1.DisplayMember = "Text"
Me.ComboBox1.ValueMember = "Value"
End Sub
End Class