Help filling gridview from a stored procedure - asp.net

I am trying to execute a stored procedure and place the information in a datagrid(without using the .net wizard) i want to do it manually. Using ado.net i believe. I am using vb.net and asp.net
Public cmd As New SqlCommand()
Public saoda As New SqlDataAdapter(cmd)
Public conn As New SqlConnection(" ")
Dim saods As New DataSet
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim reader As SqlDataReader
cmd.Parameters.AddWithValue("#yeartoget", DropDownList1.SelectedValue)
cmd.CommandText = "casof"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
conn.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
GridView1.DataSource = saods
saoda.FillSchema(saods, SchemaType.Mapped)
GridView1.DataBind()
conn.Close()
End Sub
End Class
vvvvv
Dim pctofsales As New DataColumn
pctofsales = New DataColumn("PCTofsales", GetType(Decimal))
pctofsales.Expression = "IIF([YEsales] = 0, 0, [ASOFSales] / [YEsales])"
saods1.Tables("salesasoftable").Columns.Add(pctofsales)

You don't need to bind a DataSet to a GridView - a SqlDataReader will suffice. That is, you could use the following:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim reader As SqlDataReader
cmd.Parameters.AddWithValue("#yeartoget", DropDownList1.SelectedValue)
cmd.CommandText = "casof"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
conn.Open()
reader = cmd.ExecuteReader()
GridView1.DataSource = reader
GridView1.DataBind()
conn.Close()
End Sub
However, if you want/need to use a DataTable, that's no big deal, either. The following snippet loads a reader into a DataTable:
Dim reader As SqlDataReader
cmd.Parameters.AddWithValue("#yeartoget", DropDownList1.SelectedValue)
cmd.CommandText = "casof"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
conn.Open()
reader = cmd.ExecuteReader()
Dim myTable As DataTable = New DataTable()
myTable.Load(reader)
GridView1.DataSource = dt
GridView1.DataBind()
conn.Close()
Happy Programming!

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

ADO.net ASP.net How to Fill datatable?

I am new to this....How do I correctly fill this datatable ? The editor does not like this code, it gives me squiggles beneath the last occurrence of conn and Fill
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class WebForm4
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connstring As String
connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\CompanyData.mdb"
Dim conn As OleDbConnection
conn = New OleDbConnection(connstring)
conn.Open()
Dim strSql As String
strSql = "select * from Company"
Dim cmd As SqlCommand
cmd = New SqlCommand(strSql, conn)
Dim da As SqlDataAdapter
da = New SqlDataAdapter
da.SelectCommand = cmd
Dim dt As DataTable
dt = New DataTable
da.Fill(dt, "Company")
End Sub
You are using an OleDb to use an MS-Access database. You should use OleDb classes for everything. You create an SqlCommand and a SqlDataAdapter, these classes work for Sql Server but not with OleDb.
Dim connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\CompanyData.mdb"
Dim strSql = "select * from Company"
Using conn = New OleDbConnection(connstring)
Using cmd = New OleDbCommand(strSql, conn)
conn.Open()
Using da = New OleDbDataAdapter
da.SelectCommand = cmd
Dim dt = New DataTable
da.Fill(dt, "Company")
End Using
End Using
I have changed a bit your code to show how to use the Using Statement. This statement is very important to keep your code clean because it closes and disposes every disposable object declared in the using line.

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

Resources