Pass data from a Datagrid to a form and vice versa - datagrid

I have a form called "FrmClientesEdicion" which has a postal code field, I am trying to open the postal code file and return to the first form the information selected in the second form from the datagrid. What happens is that with the code so far the info does not pass to me but rather it opens a new instance of the form "FrmClientesEdicion", help?
Open the postal code form "FrmCodigosPosAr" from a button in "FrmClientesEdicion" with this line:
Dim f As New FrmCodigosPosAr
f.ShowDialog()
Search in the form : "FrmCodigosPosAr" select a row and pass data (p.e Code, Name) again to the first one: "FrmClientesEdicion" with this lines:
Try
Dim F As New FrmClienteEdicion
With F
.TxtCPOCLI.Text = DG.CurrentRow.Cells(0).Value.ToString ' The code
.TxtPOBCLI.Text = DG.CurrentRow.Cells(1).Value.ToString ' The name city
.TxtPROCLI.Text = DG.CurrentRow.Cells(2).Value.ToString ' The state
End With
Catch ex As Exception
MsgBox("Verifique: " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
Me.Close()
This second point doesn't works open a new instance but don`t...
Thanks again
Note: The first form still open, never close it when I open the second one!
The pictures:
Open form 2
Then pass data from FORM2 to the FORM1 AGAIN

I answer myself in case someone needs it
In form2 (FrmCodigosPosAr)
Public Class FrmCodigosPosAr
Inherits System.Windows.Forms.Form
Public myCaller As FrmClienteEdicion
In form 1, (p.e in a Button to call form2 (FrmCodigosPosAr))
Dim myform As FrmCodigosPosAr
Private Sub BtnBuscaCP_Click(sender As Object, e As EventArgs) Handles BtnBuscaCP.Click
If myform Is Nothing Then
myform = New FrmCodigosPosAr
myform.myCaller = Me
End If
myform.Show()
End Sub
And in the form 2 (FrmCodigosPosAr) to pass data to Form1 (FrmClientesEdicion)
Try
If Not myCaller Is Nothing Then
myCaller.Text = Now.ToLongTimeString
myCaller.TxtCPOCLI.Text = DG.CurrentRow.Cells(0).Value.ToString
myCaller.TxtPOBCLI.Text = DG.CurrentRow.Cells(1).Value.ToString
myCaller.TxtPROCLI.Text = DG.CurrentRow.Cells(2).Value.ToString
End If
Catch ex As Exception
MsgBox("Verifique: " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
Me.Close()

Related

How can I store the data in memory and use by the other Button click event to display the data?

Here is the code, but the datatable is NULL in ButtonExport click event, how can i pass the DataTable to Sub ButtonExport_Click ? I dont want to store in Session as the data is too big
Here is the class clsGlobalVarriable
Public Class clsGlobalVariable
Private _gdt As DataTable
Public Property globalDataTable As DataTable
Get
Return _gdt
End Get
Set(ByVal value As DataTable)
_gdt = value
End Set
End Property
End Class
Here is the From frmTest code:
Public Class frmTest
Inherits System.Web.UI.Page
Private gdt As New clsGlobalVariable
Protected Sub ButtonInactivePC_Click(sender As Object, e As EventArgs) Handles ButtonInactivePC.Click
Try
Dim func As New clsFunction
Dim command As String = "Get-ADComputer -Filter { OperatingSystem -NotLike '*Windows Server*'} -Property * | select Name, CanonicalName, operatingSystem, LastLogonDate, Description, whenChanged | Where {($_.LastLogonDate -lt (Get-Date).AddDays(-90)) -and ($_.LastLogonDate -ne $NULL)}"
Dim arr As New ArrayList
arr.Add("Name")
arr.Add("CanonicalName")
arr.Add("operatingSystem")
arr.Add("LastLogonDate")
arr.Add("whenChanged")
arr.Add("Description")
gdt.globalDataTable = func.PSObjectToDataTable(command, arr)
Me.GridView1.DataSource = gdt.globalDataTable
Me.GridView1.DataBind()
Catch ex As Exception
Me.LabelDebug.Text = "Button Click" + ex.Message
End Try
End Sub
Protected Sub ButtonExport_Click(sender As Object, e As EventArgs) Handles ButtonExport.Click
Dim func As New clsFunction
Dim dt As New DataTable
dt = (DirectCast(Me.GridView1.DataSource, DataTable))
Me.LabelDebug.Text = "Global Data Table Count = " & dt.Rows.Count
End Sub
When working with webpages that show data to the user, and the user takes some action on that data you either need to store the data somewhere in their computer, your computer (the server) or rely on the fact that it's still stored in the computer you got it from. As a process you have undertaken:
You generate a grid from querying AD
You send the grid to the customer's computer - so it's stored there as a visual representation (and maybe also ViewState)
It's still stored in AD, where you got it
You could also store it locally on the server somehow - Session, DB, text file, whatever
Decide on which of these to use when the user clicks Export:
Dig it out of the viewstate or other data that was sent to the user - for this you'll have to code things up so it comes back from the user
Get it out of AD again - simple to do; you did it once and sent it to the user in HTML. Getting it again and sending it to the user again this time as a CSV isn't really any different from the first time you did it
Restore it from wherever you kept it on the server
Choose the first if your user is going to modify the data or choose to export only some of it - the data he sends back to you should indicate which bits he wants exporting.
Choose the second option if you want an easy life, and it's just a straight export, no editing or subset of data. Write one method that gets the data out of AD and then use it in either place, one to form HTML/fill a grid, in the other to send a file to the user. Don't get hung up on "well I already got this data once, it's a waste to get it again" - no-one writes a Login Page and thinks "i'll only ever look up a user from the DB once, then get the server to remember the login data forever more and use it next time there is a login request" - they store the data in the db, and look it up every time there is a login. DBs store data and perform the same queries over and over again. This is no different
You probably wouldn't choose the third option, for reasons already mentioned
I decided to use alternative for the Excel Export, i am not going to pass the DataTable, instead i pass the GridView to the Export to Excel function
Add the following sub right after Page_load, this is to avoid the GridView error
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
Here is the Code:
Public Sub ExportFromGridview(ByVal gv As GridView, ByVal response As HttpResponse
response.Clear()
response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>")
response.AddHeader("content-disposition", "attachment;filename=" & Now & ".xls")
response.ContentType = "application/vnd.xls"
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
gv.RenderControl(htmlWrite)
response.Write(stringWrite.ToString())
response.End()
End Sub

Validation Summary

I use a login entrance in my Asp.Net project
And I use validationSummary for User Name and password.
Everything goes well but.
What I want is to know if the ValidationSummary has errors to show me or not before the appearance of the errors window
I use vb.net to build the project
I don't have any code to show. And also I can't find anything relative in on the Internet to assist me on this issue.
You are probably using the ValidationSummary method in your Razor views, which - as per MSDN
Returns an unordered list (ul element) of validation messages in the ModelStateDictionary object.
So, if you want to know if there will be any errors shown by the ValidationSummary method, you can check this ModelStateDictionary in your controller before delivering your response to the browser. Doing this is described i.e. here (in C#).
In your controller method you can access ModelState.IsValid if you want to know if there are any errors which will be displayed.
This does directly answer your question, but this might not be the optimal way to achieve what you want when looking at the bigger picture. If you want to i.e. do something special if the login fails in your controller you should check directly if the login failed, not if some other method added model errors. To provide an answer, which might be more on point, you need to clarify your question and add more details about what you specifically want to do and possibly add some of your code too.
The idea to use the code I post is finally correct.
Public Sub IsGroupValid(ByVal sValidationGroup As String, ByVal sender As Object, ByVal e As EventArgs)
For Each validator As BaseValidator In Validators
If validator.ValidationGroup = sValidationGroup Then
Dim fValid As Boolean = validator.IsValid
Dim CtrlToValidate As String = validator.ControlToValidate
validator.DataBind()
If Not fValid And CtrlToValidate = ServerHandler.UName Then
validator.Validate()
fValid = validator.IsValid
ModelState.AddModelError(CtrlToValidate, validator.ID)
ElseIf Not fValid And CtrlToValidate = "Password" And validator.ID = ServerHandler.PwdRq Then
validator.Validate()
fValid = validator.IsValid
ModelState.AddModelError(CtrlToValidate, validator.ID)
ElseIf Not fValid And CtrlToValidate = "Password" And validator.ID = ServerHandler.PwdRegEx Then
validator.Validate()
fValid = validator.IsValid
ModelState.AddModelError(CtrlToValidate, validator.ID)
End If
End If
Next
End Sub
But has condition that someone or something give him the error list from ValidationSummaryGroup
And this is done with the following code
Public Function LoadModel(ByVal sender As Object, ByVal e As EventArgs) As Boolean
Dim retVal As New Boolean
Try
If Not ModelState.IsValid Then
Dim result As StringBuilder = New StringBuilder()
For Each item In ModelState
Dim key As String = item.Key
Dim errors = item.Value.Errors
For Each [vError] In errors
ModelAnswer.Add(key & "^" & [vError].ErrorMessage)
retVal = True
Next
Next
End If
ModelState.Clear()
Catch ex As Exception
Environment.AssemblyInfo.ErrorAnswer = ServerHandler.ErrHandler.GetError(3, Nothing, Nothing, ex, Nothing)
Environment.AssemblyInfo.ErrorAnswer = Environment.AssemblyInfo.ErrorAnswer & "\r\n ifExistConsistencyRecord "
ServerHandler.ErrProperty._InnerError = Environment.AssemblyInfo.ErrorAnswer
Environment.AssemblyInfo.errorCall = True
retVal = False
End Try
Return retVal
End Function
Of course ModelAnswer is an ArrayList and declared as Public
And all this under the very basic prerequisite, all the processes to work within the main page and NOT in a "class"
Thank you very much for those who helped to solve this puzzle

Global Variables lose value in another event

I have following global variables
Dim cardNumber As String
Dim txnAmount As String
Dim TerminalID As String
Dim CurrencyCode As String
And Values are assigned on a click Event from the result set returned from SP
dsCards = Utilities.GetVirtualResultNew(txtCardNumber.Text.Trim)
grdTransactionResultSearch.DataSource = dsCards
grdTransactionResultSearch.DataBind()
cardNumber = IIf(IsDBNull(dsCards.Tables(0).Rows(0).Item("pan")), "", dsCards.Tables(0).Rows(0).Item("pan"))
txnAmount = IIf(IsDBNull(dsCards.Tables(0).Rows(0).Item("TotalAmount")), "", dsCards.Tables(0).Rows(0).Item("TotalAmount"))
TerminalID = IIf(IsDBNull(dsCards.Tables(0).Rows(0).Item("TerminalID")), "", dsCards.Tables(0).Rows(0).Item("TerminalID"))
CurrencyCode = IIf(IsDBNull(dsCards.Tables(0).Rows(0).Item("CurrencyCode")), "", dsCards.Tables(0).Rows(0).Item("CurrencyCode"))
I Debugged the code and I can see the values are assigned to them but when I try to access them in another button click event, They are empty
Here is my button click event where These variables are empty
Protected Sub btnAuthorize_Click(sender As Object, e As EventArgs) Handles btnAuthorize.Click
Utilities.InsertAuthorizedTransactions(cardNumber, txnAmount, TerminalID, CurrencyCode)
Label1.Visible = True
END Sub
Whats the problem with my code?
When a button is clicked, then a postback is performed (What is a postback?) which in this case will re-initliase your variables.
The preferred option is probably to store your variables in ViewState (What is ViewState?) in your first button click:
ViewState("cardNumber") = "foo"
ViewState("txnAmount") = "bar"
'etc.
And then access them in your second click.
Note also that you should not use the IIF function in VB.NET but you should instead use the If Operator

VB.Net exception: Object reference not set to an instance of an object

I'm currently working on coding a web page for a school project. This site is supposed to be a simple online store where people can order prints of artwork. The specific page I'm working on has a Drop Down List (ddlArt) that is bound to my database and displays a list of the different art pieces available. When the user selects one of the items, all the information on that item is pulled from the database and displayed on the page in a variety of labels and such. The only thing is that I'm getting a null reference exception error saying "Object reference not set to an instance of an object" when I go to try to run the page. I got the same error on a homework assignment earlier in the year and managed to get it fixed, but I can't remember what I did and I can't get help from school until next week, so I thought I'd try my luck on here. Here's my code:
Private selectedArt As Art
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlArt.DataBind()
End If
selectedArt = Me.GetSelectedArt
lblArtID.Text = selectedArt.ArtID()
lblArtName.Text = selectedArt.ArtName()
lblCaption.Text = selectedArt.Caption()
lblDescription.Text = selectedArt.Description()
imgArt.ImageUrl = "~/images/" & selectedArt.FileName()
End Sub
Private Function GetSelectedArt() As Art
Dim artTable As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
artTable.RowFilter = "ArtID = '" & ddlArt.SelectedValue & "'"
Dim artRow As DataRowView = artTable(0)
Me.imgArt.ImageUrl = "~/images/" & artRow("FileName")
Dim art As New Art
art.ArtID = artRow("ArtID").ToString
art.ArtName = artRow("ArtName").ToString
art.Caption = artRow("Caption").ToString
art.Description = artRow("LongDescription").ToString
art.FileName = artRow("FileName").ToString
Return art
End Function
And here's the code for the Art class, in case anybody is interested:
Public Class Art
Public Property ArtID As Integer
Public Property ArtName As String
Public Property ArtType As String
Public Property Caption As String
Public Property FileName As String
Public Property Description As String
End Class
When I get the error, it highlights the artTable.RowFilter = "ArtID = '" & ddlArt.SelectedValue & "'" line in the GetSelectedArt function. I've tried comparing it to my corrected homework assignment that I mentioned, but I can't seem to find the problem. My VB is a little fuzzy because it's been awhile since I actually took the class. Any suggestions? Thanks a bunch!
If I understand your comment above correctly, on the initial page load there is nothing in the ddlArt, because the user must first choose an art type.
If that is correct, then your answer to my question is your answer.
For whatever reason (and without seeing at least the Select statement), artTbl is not getting instantiated, which is why you're seeing the Object reference not set to an instance of an object error.
One way to fix this (without knowledge of your SqlDataSource it's hard to give a precise answer) is to modify your Page Load method so that GetSelectedArt is only called when the user has selected an item from the drop down list. Right now GetSelectedArt is called every time the page loads.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlArt.DataBind()
Else
selectedArt = Me.GetSelectedArt
lblArtID.Text = selectedArt.ArtID()
lblArtName.Text = selectedArt.ArtName()
lblCaption.Text = selectedArt.Caption()
lblDescription.Text = selectedArt.Description()
imgArt.ImageUrl = "~/images/" & selectedArt.FileName()
End If
End Sub
However, the above modification will only prevent GetSelectedArt from being called on the initial page load. If your SqlDataSource.Select command is still returning nothing, then you're still going to have this problem.
A better solution would be to call the GetSelectedArt on the ddlArt.SelectedIndexChanged event handler. This way you'll know that you have (or should have) a valid SelectedValue from ddlArt.
Also, if you don't populate the drop down until the user selects an art type from the radio button list, why are you binding the drop down list on the initial page load (and what are you binding it to)? Or is the drop down list and detail information on a different page from the radio button list?
May be .. with ArtID as integer
artTable.RowFilter = "ArtID = " & format(ddlArt.SelectedValue)

ASP CascadingDropDown Control Causes IE Script timeout

Before a page is loaded, I use a subroutine to link DropDownList controls together:
Private Sub CreateCascadingDropDown(ByVal category As String, ByRef parentDDL As DropDownList, ByRef targetDDL As DropDownList)
Dim CDDL As New CascadingDropDown
With CDDL
.Category = category
If Not parentDDL Is Nothing Then
parentDDL.Items.Clear()
.ParentControlID = parentDDL.ID
End If
targetDDL.Items.Clear()
.TargetControlID = targetDDL.ID
.PromptText = SharedWeb.GC_SELECTONE
.PromptValue = "-1"
.LoadingText = "Please wait..."
.ServicePath = "/ajax/InvestmentProcess.asmx"
.ServiceMethod = "GetTaxo"
End With
'Page.ClientScript.RegisterForEventValidation(CDDL.UniqueID)
targetDDL.Parent.Controls.Add(CDDL)
End Sub
When the web service method is called, it executes the following code. Based on the category, it gets the appropriate data from the adapter.
<WebMethod()> _
Public Function GetTaxo(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim log As ILog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
log.Debug("GetSegmentTaxonomy(" + category + ") -> {" + knownCategoryValues + "}")
Dim kv As StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Dim adapter As New SegmentTaxonomyTableAdapters.SEGMENT_ARCHITECTURE_TableAdapter
Dim rows As DataRowCollection
Select Case category
Case InvestmentEdit.ST_SEG_ARCH
rows = New SegmentTaxonomyTableAdapters.SEGMENT_ARCHITECTURE_TableAdapter().GetData().Rows
Case InvestmentEdit.ST_LOB
If kv.ContainsKey(InvestmentEdit.ST_SEG_ARCH) Then
log.Debug("found seg architecture - > " + kv(InvestmentEdit.ST_SEG_ARCH))
rows = New SegmentTaxonomyTableAdapters.LINE_OF_BUSINESSTableAdapter().GetData(kv(InvestmentEdit.ST_SEG_ARCH)).Rows
End If
End Select
If Not rows Is Nothing Then
Dim results As New List(Of CascadingDropDownNameValue)
For Each row As DataRow In rows
log.Debug("ROW >>>> " + row("lov_label").ToString() + " : " + row("lov_cd").ToString())
results.Add(New CascadingDropDownNameValue(row("lov_label"), row("lov_cd")))
Next
Return results.ToArray
End If
Return Nothing
End Function
There are about 5 drop downs I need to link together. The top-level drop down control (myDDL) loads fine if it is the only one linked like so:
CreateCascadingDropDown("MyCat",Nothing,myDDL)
But when I link a second drop down control, Internet Explorer gives a script timeout. If I keep allowing the script to run, it just keeps giving me the prompt. If elect to discontinue running the script, I get a Method Error 12031 or Error 500 (and yes, I have the ScriptService() declaration in my web service file). Any ideas on what's causing this?
It turns out I just needed to add the following control from the Ajax Control Toolkit:
<ajax:ToolkitScriptManager ID="tsm" runat="server" />
Instead of .TargetControlID = targetDDL.ID I needed to use:
.TargetControlID = targetDDL.UniqueId

Resources