Dropdown list from MS-SQL and second value - asp.net

I have found this code and I slightly re-writte it. I want that when I select order value from dropdown list, is showing customer in text below.
I have to say, that I have very little VB programming experience, so I'm stuck here.
Code:
<%# Page Language="VB" Debug="True" Strict="True" %>
<%# Import Namespace="System.Data.Odbc" %>
<%# Import Namespace="System.Data" %>
<%# import Namespace="System.Data.SqlClient" %>
<font face="calibri">
<script runat="server">
Dim connStr As String = "server=MSSQLEXP;database=ppwin1;Uid=sa_ro;pwd=sa_ro"
Sub Userlist_Init(ByVal Sender As Object, ByVal E As EventArgs)
Dim conn As New SqlConnection(connStr)
conn.Open()
Dim sql_user As String
Dim cmd_user As Sqlcommand
sql_User = "SELECT DISTINCT order, customer FROM dbo.T_CUSTOMER ORDER BY order ASC"
cmd_user = New Sqlcommand (sql_user, conn)
finduser.Datasource=cmd_user.ExecuteReader()
finduser.datatextfield = "customer"
finduser.databind()
conn.Close()
End Sub
Sub Finduser_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
txtuser.text = finduser.selecteditem.text
End sub
</script>
<html><head><title>Dropdown list from MS SQL DB</title></head>
<body><h1>Dropdown list from MS SQL DB</h1>
<br>
<form runat="server">
<asp:DropDownList ID="finduser" runat="server" AutoPostBack = "true" OnSelectedIndexChanged="Finduser_SelectedIndexChanged" OnInit="userlist_Init">
</asp:DropDownList>
<asp:Label id="txtuser" runat="server" />
</form>
</body>
</html>
Rok

Instead of this
finduser.Datasource = cmd_user.ExecuteReader()
finduser.datatextfield = "customer"
finduser.databind()
Did you tried this?
Dim dr As SqlClient.SqlDataReader = cmd_user.ExecuteReader
finduser.Items.Clear()
While dr.Read()
finduser.Items.Add(new ListItem(dr("customer"),dr("order"))
End While
OR
Dim dr As SqlClient.SqlDataReader
dr = cmd_user.ExecuteReader
Dim myData as New DataTable
If dr.HasRows Then
myData.Load(dr)
End If
ddldept.datasource = myData
ddldept.DataTextField = "customer"
ddldept.DataValueField = "order"
ddldept.DataBind()

Related

GridView not populating on Page_Load but on PostBack or Refresh

In an ASP.NET WebForms application there are just two controls in an aspx page, a DropDownList and a GridView. There is no default selected value of DropDownList on Page_Load. Changing the selection in DropDownList populates GridView accurately.
When the page is requested with a URL parameter such as .../View_Details.aspx?C_ID=123, the selected value in DropDownList changes but GridView does not populate for the first time but refreshing the page shows the records for given URL parameter.
ASPX markup:
<%# Page Title="Data" Language="vb" AutoEventWireup="false" MasterPageFile="~/HomePage.Master" CodeBehind="View_Details.aspx.vb" Inherits="App1.View_Details" %>
<asp:Content ID="Content4" ContentPlaceHolderID="BodyCP" runat="server">
<asp:DropDownList ID="CIDCombo" runat="server" DataSourceID="SqlDSCID" DataTextField="CName" DataValueField="CID" AutoPostBack="true"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDSCID" runat="server" ... ></asp:SqlDataSource>
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Fld1" />
<asp:BoundField DataField="Fld2" />
...
</Columns>
</asp:GridView>
</asp:Content>
Code Behind:
Private C_ID As Long
Dim con As SqlConnection = New SqlConnection(ConfigurationManager.Connect...)
Dim cmd As New SqlCommand()
Dim stSqlQry As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
C_ID = CLng(Request.QueryString("C_ID"))
If IsPostBack Then
Else
If C_ID > 0 Then
CIDCombo.SelectedValue = C_ID.ToString
LoadGVData(C_ID)
End If
End If
End Sub
Private Sub CIDCombo_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles CIDCombo.SelectedIndexChanged
If CIDCombo.SelectedIndex >= 0 AndAlso CLng(CIDCombo.SelectedValue) > 0 Then
LoadGVData(CLng(CIDCombo.SelectedValue))
End If
End Sub
Private Sub LoadGVData(ByVal lnCID As Long)
Try
If con.State <> ConnectionState.Open Then con.Open()
Dim da As SqlDataAdapter = New SqlDataAdapter()
stSqlQry = "SELECT Fld1, Fld2 ... WHERE CID = #CID"
da = New SqlDataAdapter()
cmd = New SqlCommand(stSqlQry, con)
cmd.Parameters.AddWithValue("#CID", lnCID)
Dim dtDataTableInc As DataTable = New DataTable("t_Data")
da.SelectCommand = cmd
da.Fill(dtDataTableInc)
'SOME DATA MANIPULATION WITH DATATABLE'
'****************************************************************************'
'DEBUG MODE SHOWS DataTable HAS ROWS BUT DON'T SHOW UP FIRST TIME IN GRIDVIEW'
'****************************************************************************'
gvData.DataSource = dtDataTableInc
gvData.DataBind()
Catch ex As Exception
'EXCEPTION HANDLING
Finally
If con.State <> ConnectionState.Closed Then con.Close()
End Try
End Sub
I see you have AutoEventWireup="false" put it on true.
Just a general note:
When working with DropDownLists and using AutoPostBack=True
make use of an UpdatePanel since the User gets frustrated when he always see a white page flickering :)
if you use an UpdatePanel you use the Onload event to populate your data
and put UpdateMode=Conditional
Good luck and happy coding.

display image from db alongside other webpage elements

A continuation of the question on display (not download) image from db
<%# Page Language="VB" AutoEventWireup="false" CodeFile="imgTest1.aspx.vb" Inherits="imgTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="background-color: aliceblue;">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<br />
</div>
<div style="background-color: burlywood;">
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?id=1" />
<br />
<br />
<br />
</div>
</div>
</form>
</body>
</html>
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Partial Class imgTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("id") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
Dim bytes() As Byte = CType(dt.Rows(0)("data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "filename=" & dt.Rows(0)("name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If
End If
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("CapstoneConnectionString1").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
End Class
I can now display the image on the aspx page but only the image is being displayed, all other web elements are missing.
I can only think of one reason for this, given that following are true:
Page used to render contents is imgTest1.aspx as well as page used to return image is also imgTest1.aspx.
imgTest1.aspx is always invoked with query parameter, id.
because of this page always returns an image.
Can you change the code as follows and tell us how it works:
...
...
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?imageId=1" />
...
...
and in code-behind
If Request.QueryString("imageId") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")

SQL Injection prevention with Microsoft Access and VB.NET

I'm a beginner in ASP.NET so I have some questions about how to prevent SQL injection in ASP.NET. My programming language is VB.NET, not C#, and I'm using Microsoft Access as my database.
My questions are:
How to protect my database from SQL injection?
I have been reading postings from other forums and they said using
parameters with stored procedures, parameters with dynamic SQL. Can they be implemented in a Microsoft Access database?
Here is a very simple ASP.NET example using a parameterized query via OleDb in VB.NET:
Default.aspx
<%# Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Default.aspx.vb" Inherits="vbOleDbSite._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
First Name: <asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
Last Name: <asp:TextBox ID="LastName" runat="server"></asp:TextBox><br />
<br />
<asp:Button ID="btnAddUser" runat="server" Text="Add User" />
<br />
Status: <span id="spanStatus" runat="server">Awaiting submission...</span>
</p>
</asp:Content>
Default.aspx.vb
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btnAddUser_Click(sender As Object, e As EventArgs) Handles btnAddUser.Click
Dim newID As Long = 0
Using con As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\__tmp\testData.accdb;"
con.Open()
Using cmd As New OleDb.OleDbCommand
cmd.Connection = con
cmd.CommandText = "INSERT INTO UsersTable (LastName, FirstName) VALUES (?, ?);"
cmd.Parameters.AddWithValue("?", Me.LastName.Text)
cmd.Parameters.AddWithValue("?", Me.FirstName.Text)
cmd.ExecuteNonQuery()
End Using
Using cmd As New OleDb.OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT ##IDENTITY"
newID = cmd.ExecuteScalar()
End Using
con.Close()
End Using
Me.spanStatus.InnerText = "User """ & Me.FirstName.Text & " " & Me.LastName.Text & _
""" has been added (ID: " & newID.ToString() & ")."
End Sub
End Class
Notes:
The parameterized query uses "?" instead of "real" names for the parameters because Access OLEDB ignores parameter names. The parameters must be defined in the exact order that they appear in the OleDbCommand.CommandText.
The [UsersTable] table has an AutoNumber primary key, and SELECT ##IDENTITY retrieves the new key value created by the INSERT INTO statement.

Using SqlBulkCopy SqlRowsCopied to update a label

I have a simple web application that is reading records from a CSV file and storing them in a database table. Then I am using SqlBulkCopy to copy the records into an SQL database using batches. All is fine with the insert. I am trying to give the user some feedback using OnSqlRowsCopied and NotifyAfter. The goal is to update a label that is contained in an UpdatePanel to display the number of records copied at the current NotifyAfter interval. However, the label will not update until SqlBulkCopy has complete. I can see that the s_OnSqlRowsCopied event is firing using Debug.WriteLine. What is the reason why the label won't update and how can I overcome this?
Code Behind
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Dim filePath As String
Dim rowsCopied As String
Public Sub btnGetCSV_Click(sender As Object, e As EventArgs) Handles btnGetCSV.Click
filePath = System.IO.Path.GetFullPath(fileUpload1.PostedFile.FileName)
lblInfo.Text = filePath
End Sub
Protected Sub btnToSQL_Click(sender As Object, e As EventArgs) Handles btnToSQL.Click
Dim cs As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("csMediaPortal").ConnectionString
CopyData(CSVtoDataTable(lblInfo.Text.ToString()), cs)
End Sub
Private Function CSVtoDataTable(filePath As String) As DataTable
Dim dt As DataTable = Nothing
Dim sourcePath As String = String.Empty
Dim csvFile As String = String.Empty
Dim conString As String = String.Empty
Dim conn As OleDb.OleDbConnection = Nothing
Dim adapter As OleDb.OleDbDataAdapter = Nothing
Dim selString As String = String.Empty
Try
sourcePath = System.IO.Path.GetDirectoryName(filePath)
csvFile = System.IO.Path.GetFileName(filePath)
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sourcePath & ";Extended Properties=""text;HDR=No;FMT=FixedLength"""
conn = New OleDb.OleDbConnection(conString)
selString = "Select * From " & csvFile
adapter = New OleDb.OleDbDataAdapter(selString, conn)
dt = New DataTable(System.IO.Path.GetFileNameWithoutExtension(filePath))
conn.Open()
adapter.Fill(dt)
conn.Close()
Catch ex As Exception
lblInfo.Text = ex.Message
Finally
adapter.Dispose()
conn.Dispose()
End Try
Return dt
End Function
Protected Sub CopyData(sourceTable As DataTable, cs As String)
Using s As SqlBulkCopy = New SqlBulkCopy(cs, SqlBulkCopyOptions.UseInternalTransaction)
s.DestinationTableName = "test"
s.BatchSize = 1000
Try
AddHandler s.SqlRowsCopied, AddressOf s_OnSqlRowsCopied
s.NotifyAfter = 900
s.WriteToServer(sourceTable)
Catch ex As Exception
DirectCast(DirectCast(HttpContext.Current.Handler, Page).FindControl("lblInfo"), Label).Text = "Commit Error: " & ex.Message
End Try
s.Close()
End Using
End Sub
Protected Sub s_OnSqlRowsCopied(sender As Object, e As SqlRowsCopiedEventArgs)
Me.lblProgress.Value = e.RowsCopied.ToString()
Me.UpdatePanel1.Update()
Debug.WriteLine(e.RowsCopied)
End Sub
End Class
Web Form
<%# Page Language="vb" CodeBehind="WebForm1.aspx.vb" Inherits="CSVUpload.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:FileUpload ID="fileUpload1" runat="server" />
<asp:Button ID="btnGetCSV" runat="server" Text="Post" OnClick="btnGetCSV_Click" />
<asp:Label ID="lblInfo" runat="server" Text="Label"></asp:Label>
</div>
<asp:Button ID="btnToSQL" runat="server" Text="Insert To SQL" OnClick="btnToSQL_Click" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<input runat="server" type="text" id="lblProgress" value="0" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

dynamically build html table on page load

Edit for vhinn
I want it to look like this:
I am trying to build an html table dynamically on pageload with variables from a database.
this is an example strictly html http://jsfiddle.net/jdv590/daCum/1/
code:
Private Sub brothersgird()
Dim html As New StringBuilder
Dim sql As String = "select Name, Hometown, Picture, Class from brothers",
connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;",
conn As New OleDbConnection(connstring),
myCommand As New OleDbCommand(sql, conn),
namevar As String,
classvar As String,
hometownvar As String
Dim x As Integer = 1
conn.Open()
Dim dr As OleDbDataReader = myCommand.ExecuteReader
html.Append("<table>")
Do While dr.Read
' imagevar = dr("Picture")
namevar = dr("Name")
classvar = dr("Class")
hometownvar = dr("Hometown")
html.Append("<tr>")
Do While x < 4
html.Append("<td><p>" & namevar & "<br /> Hometown: " & hometownvar & "<br /> Class: " & classvar & "</p></td>")
x = x + 1
Loop
html.Append("</tr>")
x = 0
Loop
html.Append("</table>")
dr.Close()
conn.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
brothersgird()
'write to panel maybe with this idea:
seniorpanel.html=html ???
End Sub
aspx side:
<asp:Panel ID="seniorpanel" runat="server">
</asp:Panel>
in your markup:
<asp:Panel ID="seniorpanel" runat="server">
<asp:GridView ID="brothersgird" runat="server" ShowHeader="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<p>
<%# Eval("Name")%><br />
Hometown:
<%# Eval("Hometown")%><br />
Class:
<%# Eval("Hometown")%>
</p>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
code-behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
brothersgird.DataSource = SelectBrothers()
brothersgird.DataBind()
End If
End Sub
Private Function SelectBrothers() As DataTable
Dim sql As String = "select Name, Hometown, Picture, Class from brothers"
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;"
Dim conn As New OleDbConnection(connstring)
Dim ds As New DataSet
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand(sql, conn)
adapter.Fill(ds)
Return ds.Tables(0)
End Function
You familiar with DataGrids?
Client Side:
<asp:DataGrid runat="server" id="dataTable">
</asp:DataGrid>
Server Side:
//Get your data table from the database - let's say the variable is called dt
dataTable.DataSource = dt
dataTable.DataBind()
There is a lot more you can do with datagrids, but this should be enough to get you started if you decide to go this route.
Are you asking how to do this in javascript if you already have the data? If so an example would be kinda like this:
var row = document.createElement("TR");
var th1 = document.createElement("TH");
row.appendChild(th1);

Resources