vb.net OleDbDataAdapter not working with Select From Where - asp.net

If I Debug this I just get a Invalid Columnname Error("Name of the Object"). I am using a SQL database.
Protected Sub ddlKunden_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlKunden.SelectedIndexChanged
Dim strSql As String
Dim kontakt As String = ddlKunden.SelectedItem.Value
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.ConnectionString = strConnection
connection.Open()
'Kontaktpersonen laden
strSql = "SELECT * FROM Kontaktpersonen WHERE Nr =" & Chr(34) & kontakt & Chr(34)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbP)
End Using
ddlKontaktperson.Items.Clear()
ddlKontaktperson.DataSource = dtbP
ddlKontaktperson.DataTextField = "AP_Nam"
ddlKontaktperson.DataValueField = "ID"
ddlKontaktperson.DataBind()
End Using
ddlKontaktperson.Visible = True
End Sub
The Error pops at
dad.fill(dtbP)
It should select all rows Where Nr="SELECTED VALUE" and you select it in a dropdownlist. And all these rows should be saved in a Datatable then and are used in another dropdownlist.
It works when I try the exact same thing without the where.
Example:
'Kunden laden
strSql = "SELECT * FROM Kontakte"
dtbK = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbK)
End Using
ddlKunden.Items.Clear()
ddlKunden.DataSource = dtbK
ddlKunden.DataTextField = "Nr"
ddlKunden.DataValueField = "Nr"
ddlKunden.DataBind()

Please try following code
You do not need to use "'" around parameters
Just add these values as a parameter to the oledbcommand with its value and type
Otherwise, your sql command will be vulnerable to sql injection
Dim strConnection As String = "Provider=sqloledb;Data Source=(local);" &
"Initial Catalog=kodyaz;" &
"User Id=sa;Password=sa"
Dim kontakt As Int32 = 1
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.Open()
Dim cmd As New OleDbCommand()
cmd.Connection = connection
cmd.CommandText = "SELECT * FROM Kontaktpersonen WHERE Nr = ?"
cmd.Parameters.AddWithValue("Nr", kontakt)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(cmd)
dad.Fill(dtbP)
End Using
End Using

Related

Query string not retrieving data values

Hope you guys could give me some help.
I have a asp.net web form which gets data from SQL database and displays it on webpage via product code number or product description.
Searching by description will display a list of similar products where each list will have a button with the product code when clicked will open another site with extra product information,
e.g.
13892
14589
17485
00010
08890
The problem is all the codes that start from 1 upwards will show more details, but when I click on product codes that start with 0 such as 00010, 08890 will show no data when in fact there should be data.
Any help would be appreciated.
code I have below,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Val(Request.QueryString("Stock_code")) <> 0 Then
Dim dt As DataTable = New DataTable
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & _
"AND LOC_STOCK_CODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & Val(Request.QueryString("stock_code")) & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & Val(Request.QueryString("stock_code")) & "'"
Using cmd4 As SqlCommand = New SqlCommand(strQuery4)
Dim da3 As SqlDataAdapter = New SqlDataAdapter
Dim dt4 As New DataTable
cmd4.Connection = cnn : cnn.Open()
da3.SelectCommand = cmd4
da3.Fill(dt4)
For i = 0 To dt4.Rows.Count - 1
Label8.Text = dt4.Rows(i).Item("Retail_Rest_Split")
Next
End Using
cnn.Close()
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = cnn : cnn.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
For i = 0 To dt.Rows.Count - 1
Label7.Text = dt.Rows(i).Item("Stock_Code")
Label1.Text = dt.Rows(i).Item("Notes")
Label3.Text = dt.Rows(i).Item("Retail_Price")
Label4.Text = dt.Rows(i).Item("Pack_Size")
Label5.Text = dt.Rows(i).Item("Stock_Description")
'Label8.Text = dt.Rows(i).Item("Pack_Size")
Label9.Text = dt.Rows(i).Item("Net_Weight")
Label10.Text = dt.Rows(i).Item("Gross_Weight")
GridView1.DataSource = dt
GridView1.DataBind()
Next
End Using
cnn.Close()
Dim dt3 As DataTable = New DataTable
Using cmd3 As SqlCommand = New SqlCommand(strQuery3)
Dim da2 As SqlDataAdapter = New SqlDataAdapter
cmd3.Connection = cnn : cnn.Open()
da2.SelectCommand = cmd3
da2.Fill(dt3)
End Using
For i = 0 To dt3.Rows.Count - 1
Label6.Text = dt3.Rows(i).Item("Chinese_Description")
Next
Dim cmd2 As New SqlCommand
Dim dt2 As New DataTable
Dim da As New SqlDataAdapter
With cmd2
.Connection = cnn
.CommandText = strQUery2
End With
da.SelectCommand = cmd2
da.Fill(dt2)
GridView1.DataSource = dt2
GridView1.DataBind()
End If
End Sub
You want to use a paramaterized query like this (I'm going to fold that query string to make it more readable without having to scroll horizontally):
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description],
STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as
[Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as
[Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM
dbo.STK_STOCK WHERE STKCODE = #StockCode"
Using cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#StockCode", Request.QueryString("Stock_code"))
' Do your other stuff here.
End Using
Note, that you don't want to just use string concatenation to insert your query parameter. That opens you up to SQL injection attacks.
Instead, you use a placeholder in your query like #StockCode. Then you call AddWithValue on the command to give it the value of that parameter.
You can also explicitly specify the parameter type if you need to:
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
Assuming they are all 5 digit codes, this will make sure the stock code is numeric.
Replace
Val(Request.QueryString("Stock_code"))
with
String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Will raise an exception if Request.QueryString("Stock_code") is not parsed as integer, which prevents against malicious injection.
For example:
Dim stockCode = String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & stockCode & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & "AND LOC_STOCK_CODE = '" & stockCode & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & stockCode & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & stockCode & "'"
#dwilliss has just answered the question using parameters, which is probably better than my method. Posting this anyway

Using ViewState to apply filters on Listview

I have used ListView Control to gets list of products from database. I also stores result in viewstate . Now to apply filter from checkbox to get refined data I want to know how can I use viewState values?
e.g. If 10 Products found in Music category when page loads. Now if user apply filter(Bluetooth) then only that products should be shown which are in Music & has bluetooth..
Now It is working Like on page load Music category gets fetched Then if I check Bluetooth filter then all bluetooth products comes which are not related to music.
Private Sub shop_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim pageName As String = Me.Page.RouteData.Values("category").ToString()
if not Me.isPostback Then
Try
query = select * from products where category = '"+pageName+"'
Dim conString As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Dim con As New MySqlConnection(conString)
Dim cmd As New MySqlCommand(query)
con.Open()
Dim da As New MySqlDataAdapter()
cmd.Connection = con
da.SelectCommand = cmd
Dim dt As New DataTable()
da.Fill(dt)
ViewState("Data") = dt
products.DataSource = dt
products.DataBind()
catHeading.Text = pageName
itemCount.Text = dt.Rows.Count.ToString
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End Sub
Filter Apply code
Private Sub priceFilter_SelectedIndexChanged(sender As Object, e As EventArgs) Handles priceFilter.SelectedIndexChanged
'buildWhereClause()
Dim price As String = priceFilter.SelectedValue.ToString()
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.[Select]((Convert.ToString("category='") & price) + "'")
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Sub
I just want when user apply any filter then it should check from viewstate(Data) rather to entire table.
Save your category in viewstate & on Checked get that category in string & join that string in your query. something like this
Dim constr As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString
Dim query As String = "select * from table"
Dim joiner As String = ""
Dim condition As String = String.Empty
Dim whereClause As String = String.Empty
Dim priceCondition As String = String.Empty
Try
Dim category As String = ViewState("Data")
condition = String.Concat(condition, joiner, String.Format("{0}", category))
If joiner = "" Then joiner = ""
joiner = " where "
If Not String.IsNullOrEmpty(condition) Then
whereClause = String.Concat(whereClause, joiner, String.Format("category Like '%{0}%'", condition))
joiner = " and "
End If
'Same way you can apply multiple filters as you want & then get that in one string like below
Dim masterClause As String = String.Empty
masterClause = (query & whereClause)
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand(masterClause)
Using sda As New MySqlDataAdapter(cmd)
cmd.Connection = con
Using dt As New DataTable()
sda.Fill(dt)
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Using
End Using
End Using
End Using
For your filter you could use :
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.Select("category='" & category & "'")
products.DataSource = dr
products.DataBind()
itemCount.Text = dr.Length

Textbox with textmode = date does not show data after executereader

I am using VS 2012 asp.net web project and VB.net as programming language.
I have on my form a textbox field that its textmode property is set to Date (Datepicker).
when I run the following code I can't retrieve the date saved in the record,
Protected Sub Srch_Click(sender As Object, e As EventArgs) Handles Srch.Click
Dim ARTSQLCON As SqlConnection = New SqlConnection("Data Source=EMBRYOLOGIST;Initial Catalog=ARTSQL;Integrated Security=True")
Try
ARTSQLCON.Open()
If Not Len(FilenumSrc.Text) = 0 Then
Dim sqlread = New SqlCommand
sqlread.CommandText = "SELECT Filenum, DOB FROM TblReg WHERE Filenum = " & FilenumSrc.Text
sqlread.Connection = ARTSQLCON
Dim dr As SqlDataReader
dr = sqlread.ExecuteReader
If dr.HasRows Then
dr.Read()
FileNumTxt.Text = dr.Item("Filenum")
DobTxt.Text = dr.Item("DOB")
dr.Close()
End If
End If
Catch ex As Exception
Finally
ARTSQLCON.Close()
End Try
end sub
Dim dt As DateTime = Convert.ToDateTime(dr.
Item("DOB").ToString())
DobTxt.Text = String.Format("{0:yyyy-MM-dd}", dt)
ref.: data binding

GridViewUpdateEventArgs not working with update to sql table

I'm not getting my GridViewUpdateEventArgs to work for some reason.
I'm trying to update my gridview(table in sql) but it´s not working.
And i don´t know how to write the the Where clause in the sql to match.
Public Sub GridView1_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim SelectRow As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim RowID As HiddenField = Gridview1.FindControl("ID")
Dim Report As String = SelectRow.Cells(1).Text
Dim BusinessArea As String = SelectRow.Cells(2).Text
Dim Salesdepartment As String = SelectRow.Cells(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim SqlCommand As New SqlCommand("UPDATE TEST SET Report = ('" & Report & "'), [Business Area] = ('" & BusinessArea & "'), Salesdepartment = ('" & Salesdepartment & "') WHERE ID = #RowID ", SqlConnection)
Dim SqlDataAdapter As New SqlDataAdapter(SqlCommand)
Dim dataSet As New DataSet()
SqlDataAdapter.Fill(dataSet)
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using
The "ID" column is my PK in the table and is in a (ItemTemplate) (Hidden)
In this Way SqlDataAdapter can't update database record, see here how to update record using SqlDataAdapter .
or you can try like this:
Dim row As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim hf As HiddenField = TryCast(row.FindControl("ID"), HiddenField)
Dim Report As [String] = row.Cell(1).Text
Dim BusinessArea As [String] = row.Cell(2).Text
Dim Salesdepartment As [String] = row.Cell(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim cmd As New SqlCommand("UPDATE TEST SET Report = #Report,[Business Area] =#BusinessArea, Salesdepartment=#Salesdepartment WHERE ID = #RowID ", SqlConnection)
cmd.Parameters.AddWithValue("#Report", Report)
cmd.Parameters.AddWithValue("#BusinessArea", BusinessArea)
cmd.Parameters.AddWithValue("#Salesdepartment", Salesdepartment)
cmd.Parameters.AddWithValue("#RowID", hf.Value)
cmd.ExecuteNonQuery()
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using

retrieving whole database into dataset

I have access db with 3 different tables,I want to load the whole database into dataset so I will be able to work with the data without load the db serval times.
all the examples of working with dataset are showing how to get part of the database using ".fill"
for example :
OleDbCommand CommandObject = new OleDbCommand ("Select * from employee");
OleDbAdapter myDataAdapter = new OleDbAdapter (null, con);
myDataAdapter.SelectCommand = CommandObject;
myDataAdapter.Fill (myDataSet, "EmployeeData");
this example load only from employee but how can I etrieve the all tables in once into dataset?
in xml for instance there is command to load all the document to dataset with:" dataset.ReadXml"
How can I achive it in access db?
Thanks for any help
Baaroz
Protected Function getDataSetAndFill(ByRef connection As OleDb.OleDbConnection,
Optional ByVal isExportSchema As Boolean = True) As DataSet
Dim myDataSet As New DataSet
Dim myCommand As New OleDb.OleDbCommand
Dim myAdapter As New OleDb.OleDbDataAdapter
myCommand.Connection = connection
'Get Database Tables
Dim tables As DataTable = connection.GetOleDbSchemaTable( _
System.Data.OleDb.OleDbSchemaGuid.Tables, _
New Object() {Nothing, Nothing, Nothing, "TABLE"})
'iterate through all tables
Dim table As DataRow
For Each table In tables.Rows
'get current table's name
Dim tableName As String = table("TABLE_NAME")
Dim strSQL = "SELECT * FROM " & "[" & tableName & "]"
Dim adapter1 As New OleDb.OleDbDataAdapter(New OleDb.OleDbCommand(strSQL, connection))
adapter1.FillSchema(myDataSet, SchemaType.Source, tableName)
'Fill the table in the dataset
myCommand.CommandText = strSQL
myAdapter.SelectCommand = myCommand
myAdapter.Fill(myDataSet, tableName)
Next
''''''''''''''''''''''''''''''''''''''
'''' Add relationships to dataset ''''
''''''''''''''''''''''''''''''''''''''
'First, get relationships names from database (as well as parent table and child table names)
Dim namesQuery As String = "SELECT DISTINCT szRelationship, szReferencedObject, szObject " & _
"FROM MSysRelationships"
Dim namesCommand As New System.Data.OleDb.OleDbCommand(namesQuery, connection)
Dim namesAdapter As New System.Data.OleDb.OleDbDataAdapter(namesCommand)
Dim namesDataTable As New DataTable
namesAdapter.Fill(namesDataTable)
'Now, get MSysRelationship from database
Dim relationsQuery As String = "SELECT * FROM MSysRelationships"
Dim command As New System.Data.OleDb.OleDbCommand(relationsQuery, connection)
Dim adapter As New System.Data.OleDb.OleDbDataAdapter(command)
Dim relationsDataTable As New DataTable
adapter.Fill(relationsDataTable)
Dim relationsView As DataView = relationsDataTable.DefaultView
Dim relationName As String
Dim parentTableName As String
Dim childTablename As String
Dim row As DataRow
For Each relation As DataRow In namesDataTable.Rows
relationName = relation("szRelationship")
parentTableName = relation("szReferencedObject")
childTablename = relation("szObject")
'Keep only the record of the current relationship
relationsView.RowFilter = "szRelationship = '" & relationName & "'"
'Declare two arrays for parent and child columns arguments
Dim parentColumns(relationsView.Count - 1) As DataColumn
Dim childColumns(relationsView.Count - 1) As DataColumn
For i As Integer = 0 To relationsView.Count - 1
parentColumns(i) = myDataSet.Tables(parentTableName). _
Columns(relationsView.Item(i)("szReferencedColumn"))
childColumns(i) = myDataSet.Tables(childTablename). _
Columns(relationsView.Item(i)("szColumn"))
Next
Dim newRelation As New DataRelation(relationName, parentColumns, childColumns, False)
myDataSet.Relations.Add(newRelation)
Next
If isExportSchema Then
Dim schemaName = GetXmlSchemaFileName()
If File.Exists(schemaName) Then File.SetAttributes(schemaName, FileAttributes.Normal)
myDataSet.WriteXmlSchema(schemaName)
End If
Return myDataSet
End Function
You should just call the OleDbDataAdapter.Fill method with different SelectCommands and pass the same DataSet but different table names inside. In this case, your dataSet will contain different filled tables.

Resources