ASP.NET delete specific rows from gridview by checkbox - asp.net

i need help with following code.its works well..but when page is loading it show all data from database and user can choose from them whichone rows he want to delete..
i want to use some kind of filter.
i mean.when page is loading,,its empty..i just input text in textbox and then click search button and all rows that contains specific text from textbox are diplayed..now i choose that rows i want to delete and mark them by checkbox to delete.
in easy words...i want to choose from specific rows that containts textbox text and mark them to delete...not from all rows ...
thank you all for any help
that my code
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Collections
Imports System.Text
Partial Public Class VB
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If IsPostBack Then
GetData()
End If
BindGrid()
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager _
.ConnectionStrings("conString").ConnectionString()
Dim query As String = "select * from TestCustomers"
Dim con As New SqlConnection(constr)
Dim sda As New SqlDataAdapter(query, con)
Dim dt As New DataTable()
sda.Fill(dt)
gvAll.DataSource = dt
gvAll.DataBind()
End Sub
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gvAll.PageIndex = e.NewPageIndex
gvAll.DataBind()
SetData()
End Sub
Private Sub GetData()
Dim arr As ArrayList
If ViewState("SelectedRecords") IsNot Nothing Then
arr = DirectCast(ViewState("SelectedRecords"), ArrayList)
Else
arr = New ArrayList()
End If
Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
.Cells(0).FindControl("chkAll"), CheckBox)
For i As Integer = 0 To gvAll.Rows.Count - 1
If chkAll.Checked Then
If Not arr.Contains(gvAll.DataKeys(i).Value) Then
arr.Add(gvAll.DataKeys(i).Value)
End If
Else
Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
.FindControl("chk"), CheckBox)
If chk.Checked Then
If Not arr.Contains(gvAll.DataKeys(i).Value) Then
arr.Add(gvAll.DataKeys(i).Value)
End If
Else
If arr.Contains(gvAll.DataKeys(i).Value) Then
arr.Remove(gvAll.DataKeys(i).Value)
End If
End If
End If
Next
ViewState("SelectedRecords") = arr
End Sub
Private Sub SetData()
Dim currentCount As Integer = 0
Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
.Cells(0).FindControl("chkAll"), CheckBox)
chkAll.Checked = True
Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
, ArrayList)
For i As Integer = 0 To gvAll.Rows.Count - 1
Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
.FindControl("chk"), CheckBox)
If chk IsNot Nothing Then
chk.Checked = arr.Contains(gvAll.DataKeys(i).Value)
If Not chk.Checked Then
chkAll.Checked = False
Else
currentCount += 1
End If
End If
Next
hfCount.Value = (arr.Count - currentCount).ToString()
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim count As Integer = 0
SetData()
gvAll.AllowPaging = False
gvAll.DataBind()
Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
, ArrayList)
count = arr.Count
For i As Integer = 0 To gvAll.Rows.Count - 1
If arr.Contains(gvAll.DataKeys(i).Value) Then
DeleteRecord(gvAll.DataKeys(i).Value.ToString())
arr.Remove(gvAll.DataKeys(i).Value)
End If
Next
ViewState("SelectedRecords") = arr
hfCount.Value = "0"
gvAll.AllowPaging = True
BindGrid()
ShowMessage(count)
End Sub
Private Sub DeleteRecord(ByVal CustomerID As String)
Dim constr As String = ConfigurationManager _
.ConnectionStrings("conString").ConnectionString
Dim query As String = "delete from TestCustomers where" & _
" CustomerID=#CustomerID"
Dim con As New SqlConnection(constr)
Dim cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#CustomerID", CustomerID)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
Private Sub ShowMessage(ByVal count As Integer)
Dim sb As New StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("alert('")
sb.Append(count.ToString())
sb.Append(" records deleted.');")
sb.Append("</script>")
ClientScript.RegisterStartupScript(Me.GetType(), _
"script", sb.ToString())
End Sub
End Class

You just have to modify your SQL query. It is selecting all fields without any where condition. Let's assume you have two fields A and B in which you want to search for the text. Then your query should change to
Select * from TestCustomers where A like '%"+TextBox1.Text+"%' or B like '%"+TextBox1.Text+"%'

Related

How do I print to the default printer on my Laptop from a VB.NET app I deployed to a IIS 8 server?

I've developed a VB.Net App using Visual studio 2015 on my Laptop which will print a rdlc local report for each selected row from a Gridview control directly to my laptop's default printer (which is a network printer) using the Microsoft code for 'walkthrough: Printing a Local Report without Preview' (and runs successfully on my local IIS express). When I deploy this App to a virtual company windows 2012 server that has IIS8 running, it no longer sees the default printer on my laptop (and tries to use the default printer on the windows 2012 server). I've searched the web to no success. I assume it's possible because when I use the reportviewer control in other apps I've developed and deployed on the Windows 2012 server, it can see the list of printers from my local laptop. Any ideas?
Here's the relevant VB code I'm using now...
Imports System.Management
Imports System
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Printing
Imports System.Collections.Generic
Imports Microsoft.Reporting.WebForms
Partial Class _Default
Inherits System.Web.UI.Page
Implements IDisposable
Private m_currentPageIndex As Integer
Private m_streams As IList(Of Stream)
Public Shared ViewID As String
Public Shared UserID As String
Public Shared StampID As String
Public Shared GridViewQry As String
Public Shared OpenCntr As Integer = 0
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim sqlConnection2 As New SqlConnection("DataSource=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1))
Response.Cache.SetNoStore()
OpenCntr = OpenCntr + 1
ViewID = Request.QueryString("ViewID")
If ViewID = "" Then
Response.Redirect("http://AOXWEBAPP1.SCOTT.COM/login/login.aspx")
Else
UserID = Request.QueryString("UserID")
StampID = Request.QueryString("StampID")
End If
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=1 WHERE Printed = 1"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
If OpenCntr = 1 Then
GridViewQry = "SELECT [Printed], [Customer], [AssySN], [Dte], [AssyPartNbr], [Operator], [PrintDate] FROM [Super_FinalChk] ORDER BY [Dte]"
End If
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
If (superfinalchk.Tables.Count > 0) Then
PrintATRs.DataSource = superfinalchk
If Not IsPostBack Then
PrintATRs.DataBind()
End If
Else
TextBox1.Text = "Unable to Connect to Database"
End If
' TextBox1.Text = DefaultPrinterName()
End Sub
' Routine to provide to the report renderer, in order to
' save an image for each page of the report.
Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
Dim stream As Stream = New MemoryStream()
m_streams.Add(stream)
Return stream
End Function
' Export the given report as an EMF (Enhanced Metafile) file.
Private Sub Export(ByVal report As LocalReport)
Dim deviceInfo As String = "<DeviceInfo>" &
"<OutputFormat>EMF</OutputFormat>" &
"<PageWidth>8.5in</PageWidth>" &
"<PageHeight>11in</PageHeight>" &
"<MarginTop>0.25in</MarginTop>" &
"<MarginLeft>0.50in</MarginLeft>" &
"<MarginRight>0.50in</MarginRight>" &
"<MarginBottom>0.25in</MarginBottom>" &
"</DeviceInfo>"
Dim warnings As Warning()
m_streams = New List(Of Stream)()
report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
For Each stream As Stream In m_streams
stream.Position = 0
Next
End Sub
' Handler for PrintPageEvents
Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
' Adjust rectangular area with printer margins.
Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX),
ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY),
ev.PageBounds.Width,
ev.PageBounds.Height)
' Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
' Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect)
' Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex += 1
ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
End Sub
Private Sub PrintRep()
If m_streams Is Nothing OrElse m_streams.Count = 0 Then
Throw New Exception("Error: no stream to print.")
End If
Dim printDoc As New PrintDocument()
If Not printDoc.PrinterSettings.IsValid Then
**
It FAILS HERE!!!!
**
Throw New Exception("Error: cannot find the printer.")
Else
AddHandler printDoc.PrintPage, AddressOf PrintPage
m_currentPageIndex = 0
printDoc.Print()
End If
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
If m_streams IsNot Nothing Then
For Each stream As Stream In m_streams
stream.Close()
Next
m_streams = Nothing
End If
End Sub
Private Function LoadSuperFinalChkVwData(AssySN As String) As DataTable
Dim sqlConnection1 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim querystring As String = "SELECT * FROM dbo.Super_FinalChkVw WHERE AssySN = '" & AssySN & "'"
Dim adapter As New SqlDataAdapter(querystring, sqlConnection1)
Dim superfinalchkvw As New DataSet("DataSet1")
adapter.Fill(superfinalchkvw, "Super_FinalChkVw")
Return superfinalchkvw.Tables(0)
End Function
Protected Sub Print_Click(sender As Object, e As EventArgs) Handles Print.Click
Dim report As New LocalReport()
Dim sqlConnection2 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Dim cudate As DateTime
Dim AssySN As String
Dim cntr As Integer = 0
Dim SelectCount As Integer = 0
cudate = DateTime.Now
cmd2.Parameters.AddWithValue("#cudate", cudate)
For Each row As GridViewRow In PrintATRs.Rows
cntr = cntr + 1
Dim cb As CheckBox = DirectCast(row.FindControl("checkbox3"), CheckBox)
AssySN = row.Cells(3).Text
If cb.Checked Then
SelectCount = SelectCount + 1
report.ReportPath = "..\..\Manufacture\Superiox\ATR.rdlc"
report.DataSources.Clear()
report.DataSources.Add(New ReportDataSource("DataSet1", LoadSuperFinalChkVwData(AssySN)))
Export(report)
PrintRep()
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=0, Printed=1, PrintDate=#cudate WHERE AssySN = '" & AssySN & "';"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
End If
Next
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
PrintATRs.DataSource = superfinalchk
PrintATRs.DataBind()
If SelectCount > 0 Then
TextBox1.Text = "Reports Have Been Printed!"
Else
TextBox1.Text = "Please Select Reports to Print!"
End If
End Sub

Adding new object into ArrayList, currently it rewrites the last object

I am adding products to an ArrayList to display with a repeater
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
Dim ProductID As Integer = ddProduct.SelectedValue
Dim Qty As Integer = QtyBox.Text
Dim TempProduct As OrderEntry = fillProduct(ProductID, Qty)
OrderList.Add(TempProduct)
Orders.DataSource = OrderList
Orders.DataBind()
End Sub
However, when I add a new object, it replaces the old one with a new, and I assume its because it references the old object, instead of creating a new one. Where do I create a new one?
Imports System.Data
Imports System.Data.SqlClient
Partial Class placeOrder
Inherits System.Web.UI.Page
Dim OrderList As New ArrayList
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack() Then
dataFill()
End If
End Sub
Private Sub dataFill()
fillProduct()
End Sub
Private Sub fillProduct()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT distinct ProductID, Name FROM dbo.Product;"
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
ddProduct.DataSource = objDataSet.Tables(0)
ddProduct.DataBind()
End Sub
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
Dim ProductID As Integer = ddProduct.SelectedValue
Dim Qty As Integer = QtyBox.Text
Dim TempProduct As OrderEntry = fillProduct(ProductID, Qty)
OrderList.Add(TempProduct)
Orders.DataSource = OrderList
Orders.DataBind()
dataFill()
End Sub
Private Function fillProduct(ByVal ProductID As Integer, ByVal Qty As Integer) As OrderEntry
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT * FROM dbo.Product WHERE ProductID=#ProductID ;"
.Parameters.Add(New SqlParameter("#ProductID", SqlDbType.Int, 4)).Value = ProductID
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
Dim dtRow As DataRow = objDataSet.Tables(0).Rows(0)
Dim Total_Cost As Decimal = Decimal.Multiply(Qty, dtRow("Wholesale_Price"))
Dim Total_Price As Decimal = Decimal.Multiply(Qty, dtRow("Retail_Price"))
Dim Profit As Decimal = Total_Price - Total_Cost
Dim productInfo As New OrderEntry(dtRow("ProductID"), Qty, Total_Cost, Total_Price, Profit, dtRow("Name"))
sqlCmd.Dispose()
conn.Dispose()
Return productInfo
End Function
End Class
As #OneFineDay points out, if each element of your array is going to be of the same type then use an object of type "List Of" instead of "ArrayList".
This is how your class should look. You are saving your list to a session variable in Add_Click. In Page_Load, you are retrieving this session variable, casting it to a List(Of OrderEntry) and assigning it back to your page level list variable. Also I have removed the unnecessary dataFill procedure. Make sure that you understand the concepts rather than just copying and pasting.
Imports System.Data
Imports System.Data.SqlClient
Partial Class placeOrder
Inherits System.Web.UI.Page
Private m_myOrderList As List(Of OrderEntry)
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack() Then fillProduct()
m_myOrderList = CType(Session("MyOrderList"), List(Of OrderEntry))
End Sub
Private Sub fillProduct()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT distinct ProductID, Name FROM dbo.Product;"
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
ddProduct.DataSource = objDataSet.Tables(0)
ddProduct.DataBind()
End Sub
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
If IsNothing(m_myOrderList) = True Then m_myOrderList = New List(Of OrderEntry)
Dim ProductID As Integer = ddProduct.SelectedValue
Dim Qty As Integer = QtyBox.Text
Dim TempProduct As OrderEntry = fillProduct(ProductID, Qty)
m_myOrderList.Add(TempProduct)
Session("MyOrderList") = m_myOrderList
Orders.DataSource = m_myOrderList
Orders.DataBind()
End Sub
Private Function fillProduct(ByVal ProductID As Integer, ByVal Qty As Integer) As OrderEntry
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT * FROM dbo.Product WHERE ProductID=#ProductID ;"
.Parameters.Add(New SqlParameter("#ProductID", SqlDbType.Int, 4)).Value = ProductID
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
Dim dtRow As DataRow = objDataSet.Tables(0).Rows(0)
Dim Total_Cost As Decimal = Decimal.Multiply(Qty, dtRow("Wholesale_Price"))
Dim Total_Price As Decimal = Decimal.Multiply(Qty, dtRow("Retail_Price"))
Dim Profit As Decimal = Total_Price - Total_Cost
Dim productInfo As New OrderEntry(dtRow("ProductID"), Qty, Total_Cost, Total_Price, Profit, dtRow("Name"))
sqlCmd.Dispose()
conn.Dispose()
Return productInfo
End Function
End Class
OK so it's an ASP.NET webpage. After you click on the button, it's posting the page back to the server. OrderList does not persist between calls and is reinitialised with each click. Try adding OrderList to a session variable as follows in your button click procedure :
OrderList.Add(TempProduct)
Session("OrderList") = OrderList
and in your page load event, insert:
OrderList = Session("OrderList")
Also your dataFill procedure is superfluous. Delete that procedure and replace calls to dataFill with fillProduct. It's not an error but it's untidy.

VB dot net session value set in text box not change

In one of my vb page i am setting the value of a textbox through the value coming from session. In the same page i want to perform an edit operation of the record. On the page load i displayed the variables in textboxes and after editing values when i submit and take the value from the textboxes, it still take the value i set through session. It do not take the value changed in the textbox rather it shows the value assigned at the time of page load. Please help.
Here is my code,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
Add postback prevention with the line "If (Page.IsPostBack = false) Then", for not assigning the same value again to the textbox,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Page.IsPostBack = false) Then
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
I fancy you're missing a check for IsPostBack to see whether or not this is a new request or a submission.
If (Not IsPostBack) Then
' populate for first load
End If
You have to put your code in IsPostback property.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (!IsPostBack) Then
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class

DataSet not defined?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim AppName As String = Session("App_Name").ToString()
Dim username As String = Session("username").ToString()
Dim password As String = Session("password").ToString()
Dim ds As DataSet = GContactsImport.GetGmailContacts(AppName, username, password)
GridView1.DataSource = ds
GridView1.DataBind()
End Sub
how do i fix it??
This is my class file
Imports Microsoft.VisualBasic
Imports Google.GData.Contacts
Imports Google.GData.Client
Imports Google.GData.Extensions
Imports Google.Contacts
Public Class Google
Public Shared Function GetGmailContacts(ByVal AppName As String, ByVal Uname As String, ByVal UPassword As String) As DataSet
Dim ds As New DataSet()
Dim dt As New DataTable()
Dim C2 As New DataColumn()
C2.DataType = Type.GetType
C2.ColumnName = "EmailID"
dt.Columns.Add(C2)
Dim rs As New RequestSettings(AppName, Uname, UPassword)
rs.AutoPaging = True
Dim cr As New ContactsRequest(rs)
Dim f As Feed(Of Contact) = cr.GetContacts()
For Each t As Contact In f.Entries
For Each email As EMail In t.Emails
Dim dr1 As DataRow = dt.NewRow()
dr1("EmailID") = email.Address.ToString()
dt.Rows.Add(dr1)
Next
Next
ds.Tables.Add(dt)
Return ds
End Function
End Class
Verify that DataSet is in scope (you may need to add an Import statement) or, alternatively, fully qualify the DataSet references in your code by replacing Dim ds As DataSet with Dim ds As System.Data.DataSet.
You might need to reference the System.Data assembly from the GAC and Imports System.Data (at the top of your file) in order to bring the DataSet class into scope.

problems with postbacks events from dynamic controls in ASP.Net

I am currently working on a page that has a user control that builds a dynamic table. The control is originally loaded on the Page_Init event, and any time that an event is raised that changes the dynamic control the table is reloaded. The problem here is that if the control is changed between between loads, the events from the control do not fire. For instance, there are originally two rows in the table. An item is added to the table during the postback and now there are four rows (this table adds two rows at a time). Each row has one or two buttons. When the page is loaded and sent back to the browser, if a user clicks on any of the buttons, a postback occurs, but the event does not fire. What am I doing wrong here? How can I tell what control/event caused the postback? Below is the code for both the page, and the user control.
Payments.aspx:
Partial Public Class Payments
Inherits BasePage
Private foodMaster As Food
Private _check As BusinessLayer.CustomerCheck
Private Sub btnAddCheck_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddCheck.Click
' do nothing. the modal window is tied to the button via the modal window in the designer
End Sub
Private Sub btnCalendar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnCalendar.Click
calCheckDate.Visible = Not calCheckDate.Visible
modCheck.Show()
End Sub
Private Sub btnCheckSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCheckSave.Click
Try
If IsNothing(_check) Then _check = New BusinessLayer.CustomerCheck
If Me.CurrentCheck > 0 Then _check.CheckId = Me.CurrentCheck
_check.CheckNumber = txtCheckNumber.Text
_check.CheckDate = CDate(txtCheckDate.Text)
_check.CheckAmount = CDbl(txtCheckAmount.Text)
_check.DepositId = Me.CurrentDeposit
_check.Save()
LoadControls()
' reset the current check to not get confused after an edit
Me.CurrentCheck = 0
SetupNewCheck()
Catch ex As Exception
lblMessage.Text = "Could not save check."
lblMessage.Visible = True
modCheck.Show()
End Try
End Sub
Private Sub calCheckDate_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles calCheckDate.SelectionChanged
txtCheckDate.Text = calCheckDate.SelectedDate.ToShortDateString()
calCheckDate.Visible = False
modCheck.Show()
End Sub
Private Sub cvFutureDate_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvFutureDate.ServerValidate
Try
Dim depositDate As DateTime = DateTime.Parse(txtCheckDate.Text)
Dim futureDate As DateTime = Now.AddDays(1)
Dim tomorrow As New DateTime(futureDate.Year, futureDate.Month, futureDate.Day)
args.IsValid = CBool(depositDate < tomorrow)
Catch
args.IsValid = False
End Try
End Sub
Private Sub cvInvalidAmount_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvInvalidAmount.ServerValidate
Try
Double.Parse(txtCheckAmount.Text)
Catch
args.IsValid = False
End Try
End Sub
Private Sub cvInvalidDate_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvInvalidDate.ServerValidate
Try
DateTime.Parse(txtCheckDate.Text)
Catch
args.IsValid = False
End Try
End Sub
Private Sub DepositEditing()
foodMaster.Deposit.Load(Me.CurrentDeposit)
foodMaster.ShowDepositWindow()
End Sub
Private Sub DepositSaved()
dihHeader.Deposit.Load(Me.CurrentDeposit)
dihHeader.Reload()
End Sub
Private Sub Payments_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
LoadControls()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
foodMaster = DirectCast(Me.Master, Food)
AddHandler foodMaster.SaveClicked, AddressOf DepositSaved
AddHandler foodMaster.EditButtonClicked, AddressOf DepositEditing
If IsPostBack = False Then
Me.CurrentCheck = 0
SetupNewCheck()
End If
End Sub
Private Sub pcPayments_ApplyFundsClicked(ByVal CheckId As Integer) Handles pcPayments.ApplyFundsClicked
End Sub
Private Sub pcPayments_DeleteClicked(ByVal CheckId As Integer) Handles pcPayments.DeleteClicked
Try
If Me.CurrentCheck = CheckId Then Me.CurrentCheck = 0
_check = New BusinessLayer.CustomerCheck
_check.CheckId = CheckId
_check.DeleteAllPayments()
_check.Delete()
LoadControls()
Catch
End Try
End Sub
Private Sub pcPayments_EditClicked(ByVal CheckId As Integer) Handles pcPayments.EditClicked
Me.CurrentCheck = CheckId
_check = New BusinessLayer.CustomerCheck(CheckId)
txtCheckAmount.Text = _check.CheckAmount.ToString("0.00")
txtCheckDate.Text = _check.CheckDate.ToShortDateString
calCheckDate.SelectedDate = _check.CheckDate
txtCheckNumber.Text = _check.CheckNumber
modCheck.Show()
End Sub
Private Sub LoadControls()
Dim checks As New BusinessLayer.CustomerCheckCollection()
checks.LoadByDeposit(Me.CurrentDeposit)
pcPayments.Checks = checks
pcPayments.Reload()
dihHeader.Deposit.Load(Me.CurrentDeposit)
dihHeader.TotalCheckAmount = pcPayments.TotalCheckAmount
dihHeader.TotalAppliedAmount = pcPayments.TotalAmountApplied
dihHeader.Reload()
End Sub
Private Sub SetupNewCheck()
_check = Nothing
txtCheckDate.Text = Now.ToShortDateString()
calCheckDate.SelectedDate = Now
txtCheckAmount.Text = String.Empty
txtCheckNumber.Text = String.Empty
End Sub
End Class
PaymentsControl.ascx
Public Partial Class PaymentsControl
Inherits System.Web.UI.UserControl
Private _checks As BusinessLayer.CustomerCheckCollection
Private _applied As Double
Public Event ApplyFundsClicked(ByVal CheckId As Integer)
Public Event DeleteClicked(ByVal CheckId As Integer)
Public Event EditClicked(ByVal CheckId As Integer)
Public Sub New()
_checks = New BusinessLayer.CustomerCheckCollection
_applied = 0
End Sub
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'If IsPostBack = False Then
' BindChecks()
'End If
End Sub
Private Sub ApplyButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent ApplyFundsClicked(DirectCast(sender, LinkButton).CommandArgument)
End Sub
Private Sub DeleteButtonClicked(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
RaiseEvent DeleteClicked(DirectCast(sender, ImageButton).CommandArgument)
End Sub
Private Sub EditButtonClicked(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
RaiseEvent EditClicked(DirectCast(sender, ImageButton).CommandArgument)
End Sub
Private Sub BindChecks()
tblChecks.Rows.Clear()
tblChecks.Rows.Add(BuildTableHeader())
_applied = 0
For i As Int16 = 0 To _checks.Count - 1
_checks(i).LoadAllPayments()
_applied += _checks(i).TotalAmountApplied
tblChecks.Rows.Add(BuildCheckRow(_checks(i)))
tblChecks.Rows.Add(BuildInvoiceRow(_checks(i)))
Next
If tblChecks.Rows.Count = 1 Then tblChecks.Visible = False
End Sub
Private Function BuildCheckRow(ByVal Check As BusinessLayer.CustomerCheck) As TableRow
Dim checkNumberCell As New TableCell()
Dim checkDateCell As New TableCell()
Dim checkAmountCell As New TableCell()
Dim totalAppliedCell As New TableCell()
checkNumberCell.Text = Check.CheckNumber
checkDateCell.Text = Check.CheckDate.ToShortDateString()
checkAmountCell.Text = Check.CheckAmount.ToString("C")
totalAppliedCell.Text = Check.TotalAmountApplied.ToString("C")
If Check.TotalAmountApplied <> Check.CheckAmount Then totalAppliedCell.ForeColor = Drawing.Color.Red
Dim myRow As New TableRow
myRow.Cells.Add(BuildCheckControlCell(Check.CheckId))
myRow.Cells.Add(checkNumberCell)
myRow.Cells.Add(checkDateCell)
myRow.Cells.Add(checkAmountCell)
myRow.Cells.Add(totalAppliedCell)
Return myRow
End Function
Private Function BuildCheckControlCell(ByVal CheckId As Integer) As TableCell
Dim editButton As New ImageButton()
editButton.CommandArgument = CheckId
editButton.CausesValidation = False
editButton.AlternateText = "Edit"
editButton.ImageUrl = "~/images/icons/bullet_edit.png"
AddHandler editButton.Click, AddressOf EditButtonClicked
Dim deleteButton As New ImageButton
deleteButton.CommandArgument = CheckId
deleteButton.CausesValidation = False
deleteButton.AlternateText = "Delete"
deleteButton.ImageUrl = "~/images/icons/bullet_cross.png"
deleteButton.Attributes.Add("onclick", "return confirmDelete()")
AddHandler deleteButton.Click, AddressOf DeleteButtonClicked
Dim blankSpace As New Literal()
blankSpace.Text = " "
Dim myCell As New TableCell
myCell.Controls.Add(editButton)
myCell.Controls.Add(blankSpace)
myCell.Controls.Add(deleteButton)
Return myCell
End Function
Private Function BuildInvoiceRow(ByVal Check As BusinessLayer.CustomerCheck) As TableRow
Dim invoiceDetailCell As New TableCell
invoiceDetailCell.ColumnSpan = 4
invoiceDetailCell.Controls.Add(BuildInvoiceDetailTable(Check.Payments))
Dim myRow As New TableRow
myRow.Cells.Add(BuildInvoiceControlCell(Check.CheckId))
myRow.Cells.Add(invoiceDetailCell)
Return myRow
End Function
Private Function BuildInvoiceControlCell(ByVal CheckId As Integer) As TableCell
Dim text As New Literal
text.Text = "Invoices for check:<br />"
Dim applyButton As New LinkButton
applyButton.CommandArgument = CheckId
applyButton.CausesValidation = False
applyButton.Text = "Apply Funds"
AddHandler applyButton.Click, AddressOf ApplyButtonClicked
Dim myCell As New TableCell
myCell.Controls.Add(text)
myCell.Controls.Add(applyButton)
Return myCell
End Function
Private Function BuildInvoiceDetailTable(ByVal Payments As BusinessLayer.PaymentTransactionCollection) As Table
Dim myTable As New Table
myTable.CssClass = "tableSub"
myTable.CellPadding = "0"
myTable.CellSpacing = "0"
myTable.BorderWidth = "0"
myTable.Rows.Add(BuildInvoiceDetailHeader())
For i As Integer = 0 To Payments.Count - 1
myTable.Rows.Add(BuildPaymentRow(Payments(i)))
Next
If myTable.Rows.Count = 1 Then myTable.Visible = False
Return myTable
End Function
Private Function BuildInvoiceDetailHeader() As TableRow
Dim customerCell As New TableHeaderCell
Dim invoiceCell As New TableHeaderCell
Dim dueCell As New TableHeaderCell
Dim paymentCell As New TableHeaderCell
customerCell.Text = "Customer"
invoiceCell.Text = "Invoice number"
dueCell.Text = "Amount due"
paymentCell.Text = "Payment amount"
Dim myRow As New TableRow
myRow.Cells.Add(customerCell)
myRow.Cells.Add(invoiceCell)
myRow.Cells.Add(dueCell)
myRow.Cells.Add(paymentCell)
Return myRow
End Function
Private Function BuildPaymentRow(ByVal Payment As BusinessLayer.PaymentTransaction) As TableRow
Dim customerCell As New TableCell
Dim invoiceCell As New TableCell
Dim amountDueCell As New TableCell
Dim paymentCell As New TableCell
'Payment.Customer.Load()
customerCell.Text = Payment.Customer.NumberAndName
invoiceCell.Text = Payment.Invoice.InvoiceNumber
amountDueCell.Text = Payment.Invoice.AmountDue.ToString("C")
paymentCell.Text = Payment.PaymentAmount.ToString("C")
Dim myRow As New TableRow
myRow.Cells.Add(customerCell)
myRow.Cells.Add(invoiceCell)
myRow.Cells.Add(amountDueCell)
myRow.Cells.Add(paymentCell)
Return myRow
End Function
Private Function BuildTableHeader() As TableRow
Dim blankCell As New TableHeaderCell()
Dim checkNumberCell As New TableHeaderCell()
Dim checkDateCell As New TableHeaderCell()
Dim checkAmountCell As New TableHeaderCell()
Dim totalUnappliedCell As New TableHeaderCell()
checkNumberCell.Text = "Check number"
checkDateCell.Text = "Check date"
checkAmountCell.Text = "Check amount"
totalUnappliedCell.Text = "Total unapplied"
Dim myRow As New TableRow
myRow.Cells.Add(blankCell)
myRow.Cells.Add(checkNumberCell)
myRow.Cells.Add(checkDateCell)
myRow.Cells.Add(checkAmountCell)
myRow.Cells.Add(totalUnappliedCell)
Return myRow
End Function
Public Sub Reload()
BindChecks()
End Sub
Public Property Checks() As BusinessLayer.CustomerCheckCollection
Get
Return _checks
End Get
Set(ByVal value As BusinessLayer.CustomerCheckCollection)
_checks = value
End Set
End Property
Public ReadOnly Property TotalCheckAmount() As Double
Get
Return _checks.TotalCheckAmount
End Get
End Property
Public ReadOnly Property TotalAmountApplied() As Double
Get
Return _applied
End Get
End Property
End Class
You need to assign the Id property to each dynamically added server control that will serve up postback events. Also, on postback, I believe that the dynamically added controls need to be recreated with the same id in order for postback methods and viewstate to function correctly.

Resources