Unable to reflect changes in dataset or dataadapter on page reload - asp.net

What is the problem in my this code?
The code is working fine but when i enter new record in table and refresh the page then the changes will not be reflected...
what was the problem iam confused..
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub

I have refatored your source code now you should see your new records on page load
Private Sub BindData()
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.BindData()
End Sub

Related

Select Code Doesn't Affect The Web Page

I have a web form to save transactions in database and a button to display the previous action but it doesn't work although there is no error message.
Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim nmb As Long = Convert.ToInt32(TextBox1.Text) - 1
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("dataConnectionString").ConnectionString)
Dim sql1 As New SqlCommand("select * from internal_trans where numbr = #numbr", conn)
sql1.Parameters.AddWithValue("#numbr", nmb)
conn.Open()
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
adapter.SelectCommand = sql1
adapter.Fill(ds)
Me.TextBox1.Text = ds.Tables(0).Rows(0).Item(0).ToString
Me.TextBox2.Text = ds.Tables(0).Rows(0).Item(1).ToString
adapter.Dispose()
sql1.Dispose()
conn.Close()
End Sub

to filter the rdlc report data according to parameter passed in vb.net

Try
Dim ed As New Editor()
Using con As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=LMS ;Integrated Security=True")
con.Open()
Dim cmd As New SqlCommand("select * from Editor", con)
Dim da As New SqlDataAdapter(cmd)
da.Fill(ed, "DataTable1")
con.Close()
End Using
ReportViewer1.ProcessingMode = ProcessingMode.Local
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Report.rdlc")
Dim parReportParam1 As New ReportParameter("Parameter1", Me.txtLan.Text.ToString())
Me.ReportViewer1.LocalReport.SetParameters(New ReportParameter() {
parReportParam1
})
Dim datasource As New ReportDataSource("Editor", ed.Tables(0))
ReportViewer1.LocalReport.DataSources.Clear()
ReportViewer1.LocalReport.DataSources.Add(datasource)
Me.ReportViewer1.LocalReport.Refresh()
Catch ex As Exception
End Try
I am not able to get any data from my data set it is showing empty report viewer after adding parameter to report.rdlc
Protected Sub bSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bSubmit.Click
ReportViewer1.ProcessingMode = ProcessingMode.Local
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Report.rdlc")
Dim ed As New Editor()
Using con As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=LMS ;Integrated Security=True")
con.Open()
Dim cmd As New SqlCommand("select * from Editor where ([Language] = #Lang)", con)
cmd.Parameters.AddWithValue("#Lang", txtLan.Text)
Dim da As New SqlDataAdapter(cmd)
da.Fill(ed, "DataTable1")
con.Close()
End Using
Dim datasource As New ReportDataSource("Editor", ed.Tables(0))
ReportViewer1.LocalReport.DataSources.Clear()
ReportViewer1.LocalReport.DataSources.Add(datasource)
End Sub
End Class

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.

ASP.NET Downloading files from an SQL table

I'm trying to download a file from an SQL Server table. I am using a GridView. Whenever I try to download a file, I get a corrupted file.
I am using ASP.NET and VB.NET with SQL Server 2012 Express.
Any ideas why ?
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim ContentID = Convert.ToInt32(GridView1.SelectedRow.Cells(1).Text)
Dim ContentName = GridView1.SelectedRow.Cells(2).Text
Dim ContentType = GridView1.SelectedRow.Cells(3).Text
lblContentName.Text = "[ " + ContentName + " ]"
lblContentName.Visible = True
End Sub
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
Dim cn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
If e.CommandName = "Download" Then
Dim filename As String = String.Empty
Dim id As Integer = Convert.ToInt32(e.CommandArgument)
Dim cmd As New SqlCommand("SELECT content_name,content_type,content_data FROM content WHERE content_id = " & id, cn)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim bytes As Byte()
dr = cmd.ExecuteReader()
If dr.Read() Then
filename = dr("content_name").ToString()
Response.ContentType = dr("content_type").ToString()
Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
bytes = DirectCast(dr("content_file"), Byte())
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(bytes)
Response.Flush()
Response.[End]()
End If
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT content_id, content_name FROM content"
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub

How to save and upload Image

How I can upload and save image in ASP.net using with vb Language and SQL server 2008.
You can go with this tutorial.
A part from the link to save images in database:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
If TextBox1.Text = "" Then
MsgBox("Fill the Name Field")
Else
Dim sql As String = "INSERT INTO Information VALUES(#name,#photo)"
Dim cmd As New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#photo", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
MessageBox.Show("Name & Image has been saved", "Save", MessageBoxButtons.OK)
Label1.Visible = False
TextBox1.Visible = False
End If
End Sub
and here is how images retrieves:
Private Sub DataGridView1_CellMouseClick(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
cmd = New SqlCommand("select photo from Information where name='" & _
DataGridView1.CurrentRow.Cells(0).Value() & "'", con)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox1.BackgroundImage = Image.FromStream(ms, True)
End Using
End If
GroupBox2.SendToBack()
GroupBox2.Visible = False
Label1.Visible = True
Label1.Text = DataGridView1.CurrentRow.Cells(0).Value()
End Sub
Compare your findings with this sample and explore what you are missing.

Resources