Insert values into SQL Server using asp.net - mysql

Form button:
<asp:Button ID="Button1" runat="server" Text="GO" onclick="Button1_Click" />
Code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
What is a simple code to insert a value (generated id) into SQL Server database? When Button1_Click is triggered, generated id should be inserted to tbl_batch.
Should I add anything to web.config (like db connection)?

Using con As SqlConnection = New SqlConnection("Server=localhost\SQLEXPRESS; Database=databasename; User Id=sa; Password=yourpassword;")
Using cmd As SqlCommand = con.CreateCommand()
Using da As New SqlDataAdapter
con.Open()
cmd.CommandText = "insert into ..."
da.SelectCommand = cmd
Dim dt As New DataTable
da.Fill(dt)
End Using
End Using
End Using

You cannot do CRUD operation in web.config file but I have one simple solution for you using SqlDataSource. Follow up below steps and make your stuff happen, just in simple way.
Connection String In my Web.config:
<add name="Conn" connectionString="Server=David-PC;Database=DNN711;uid=sa;pwd=sa123;" providerName="System.Data.SqlClient"/>
ASPX Markup:
<asp:Button ID="Button1" runat="server" Text="GO" onclick="Button1_Click" />
<asp:SqlDataSource ID="sdsInsert" runat="server"
ConnectionString="<%$ ConnectionStrings:Conn %>"
InsertCommand="Insert into tbl_batch (GeneratedID) values (#GeneratedID)"
InsertCommandType="Text"></asp:SqlDataSource>
Button Click Event:
protected void Button1_Click(object sender, EventArgs e)
{
sdsInsert.InsertParameters.Add("GeneratedID", "123");
sdsInsert.Insert();
}
Please let me know if you have any questions.

Related

I have written a vb.net code to display image in the image control but not able to display the image

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim con As New SqlConnection
Dim img As New Image
con.ConnectionString = ("Initial Catalog=test; Data Source=LAPTOP-DJ6MPGR2\ROOT123;User ID=SA;Password=root;Integrated Security=False;MultipleActiveResultSets=True")
con.Open()
Dim cmd As New SqlCommand("select image from Images ", con)
cmd.Connection = con
Dim dr As SqlDataReader = cmd.ExecuteReader()
If (dr.HasRows) Then
While (dr.Read)
Dim bytes As Byte() = DirectCast(dr("image"), Byte())
Image1.ImageUrl = Convert.ToBase64String(bytes)
End While
End If
con.Close()
End Sub
The following will show how to both upload an image to a SQL Server database as well as how to retrieve and image from the database and display it on an ASP.NET web page.
Create a table in the database:
Create Table Images(Id int IDENTITY(1, 1) Not null,
Image varbinary(max),
Constraint PK_Images_Id PRIMARY KEY(Id));
The SQL Server 'sa' user really shouldn't be used to access the database as this creates a security issue. Instead create a user for your application.
Create a Database User
Open Microsoft SQL Server Management Studio
Expand Security
Right-click Logins
Select New Login
Select SQL Server authentication
Login name: <desired login name> (ex: appUser)
Enter your desired password
Uncheck "User must change password at next login"
Select the desired default database (ex: testDR)
Click OK
Add User to Database
Open Microsoft SQL Server Management Studio
Expand Databases
Expand <desired database> (ex: testDR)
Expand Security
Right-click Users
Select New User...
Enter desired user name (ex: appUser)
For "Login name", Click ...
Click Browse
Select desired user (ex: appUser)
Click OK
Click OK
Leave "Default schema", blank.
Click OK
Grant User Permissions on Table
Open Microsoft SQL Server Management Studio
Expand Databases
Expand <desired database> (ex: testDR)
Expand Tables
Right-click <desired table> (ex: dbo.Images)
Select Properties
Under "Select a page", click Permissions
Click Search
Click Browse
Check desired user (ex: appUser)
Click OK
Click OK
Under Grant, check the following: Delete, Insert, Select, Update
Click OK
Note: "With Grant" allows the user to grant the permissions to another user.
VS 2019:
Create a new project
Open Visual Studio
Click Continue without code
Click File
Select New
Select Project
Select the following:
Click Next
Select the following:
Click Next
Enter desired project name
Click Create
Select the following:
Under Advanced, uncheck Configure for HTTPS
Click Create
Open Solution Explorer
In VS menu, click View
Select Solution Explorer
Add WebForm (name: default.aspx)
In Solution Explorer, right-click <project name>
Select Add
Select New Item...
Select Web Form (name: default.aspx)
Click Add
Add WebForm (name: DisplayImage.aspx)
In Solution Explorer, right-click <project name>
Select Add
Select New Item...
Select Web Form (name: DisplayImage.aspx)
Click Add
Add connection string to Web.config
In Solution Explorer, double-click Web.config
In code below, modify the code within <connectionStrings>...</connectionStrings> for your environment (ie: server, database name, user name, password).
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="testDRConnection" connectionString="Server=.\SQLExpress;Database=testDR;User Id=appUser;Password=myAppPassword;" />
</connectionStrings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" />
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
In "default.aspx" we'll add the ability to upload a file to the database. When the upload is complete, we'll use "Display.aspx" to display the last uploaded image.
In Solution Explorer, double-click default.aspx.
default.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="DatabaseGetImage.UploadImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="frmDefault" runat="server">
<div>
<asp:Label ID="LabelFileUpload" for="FileUpload1" runat="server" Text="Label">Upload a File</asp:Label>
<p />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="ButtonUploadFile" runat="server" Text="Upload" OnClick="ButtonUploadFile_Click" />
<p />
<asp:Label ID="LblMsg" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
Below is the code that uploads an image to the database.
In Solution Explorer, right-click default.aspx. Select View Code
default.aspx.vb
Imports System.Configuration
Imports System.Data.SqlClient
Public Class UploadImage
Inherits System.Web.UI.Page
'Private _connectionStr As String = "Server=.\SQLExpress;Database=testDR;User Id=appAdmin;Password=appPass;"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Function UploadImage(imageBytes As Byte()) As Integer
Dim rowsAffected As Integer = 0
Dim connectionStr As String = ConfigurationManager.ConnectionStrings("testDRConnection").ConnectionString
Dim sqlText As String = "INSERT INTO Images(Image) VALUES(#img);"
Using con As SqlConnection = New SqlConnection(connectionStr)
'open
con.Open()
Using cmd As SqlCommand = New SqlCommand(sqlText, con)
'size = -1 is needed to exceed 8000 bytes; it maps to varbinary(max)
cmd.Parameters.Add("#img", SqlDbType.VarBinary, -1).Value = imageBytes
'execute
rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Return rowsAffected
End Function
Protected Sub ButtonUploadFile_Click(sender As Object, e As EventArgs)
If FileUpload1.HasFile() Then
LblMsg.Text = "Filename: " & FileUpload1.FileName & " File bytes: " & FileUpload1.FileBytes.Length
'upload image to database
Dim rowsAffected As Integer = UploadImage(DirectCast(FileUpload1.FileBytes, Byte()))
Response.Redirect("DisplayImage.aspx")
End If
End Sub
End Class
Next, we'll modify "DisplayImage.aspx" so that it will display an image.
In Solution Explorer, double-click DisplayImage.aspx
DisplayImage.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="DisplayImage.aspx.vb" Inherits="DatabaseGetImage.displayImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div>
<asp:Image ID="Image1" runat="server" ></asp:Image>
<p />
<asp:Label ID="LblMsg" runat="server" Text=""></asp:Label>
</div>
</body>
</html>
The code below retrieves an image from the database and displays it.
In Solution Explorer, right-click DisplayImage.aspx. Select View Code
DisplayImage.aspx.vb
Imports System.Configuration
Imports System.Data.SqlClient
Public Class displayImage
Inherits System.Web.UI.Page
'Private _connectionStr As String = "Server=.\SQLExpress;Database=testDR;User Id=appAdmin;Password=appPass;"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim imagesBytes As Byte() = GetImage(id:=1) 'get image with id = 1
If imagesBytes IsNot Nothing Then
'LblMsg.Text = "Base64 String: " & Convert.ToBase64String(imagesBytes)
Image1.ImageUrl = "data:image/jpeg;base64," & Convert.ToBase64String(imagesBytes)
End If
End Sub
Protected Function GetImage(id As Integer) As Byte()
Dim imageBytes As Byte() = Nothing
Dim connectionStr As String = ConfigurationManager.ConnectionStrings("testDRConnection").ConnectionString
Dim sqlText As String = "SELECT * from Images where Id = (SELECT max(Id) from Images)"
Try
Using con As SqlConnection = New SqlConnection(connectionStr)
con.Open() 'open
Using cmd As SqlCommand = New SqlCommand(sqlText, con)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
Using dr As SqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
While dr.Read()
imageBytes = DirectCast(dr("image"), Byte())
End While
End If
End Using
End Using
End Using
Catch ex As SqlException
'ToDo: add desired code
LblMsg.Text = "Error: " & ex.Message
'Throw
Catch ex As Exception
'ToDo: add desired code
LblMsg.Text = "Error: " & ex.Message
'Throw
End Try
Return imageBytes
End Function
End Class
Resources:
Store Connection String in Web.config
SQL Server Connection Strings
How to display Base64 images in HTML

Fill data in a dropdown list with mysql table in aspx vb using a class

I'm trying to load a dropdown list linked to a table in mysql in a webform asp.net in vb. I'm using a class with the following code:
Public Class ClCountries
Public Function Read(ByVal Opcion As Integer) As DataTable
Dim cnn As New MySqlConnection(ConfigurationManager.ConnectionStrings("cnnPortalSmart").ConnectionString)
Dim dt As New DataTable
Try
Dim cmd As New MySqlCommand("PA_COUNTRIES_SELECT", cnn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Opcion", Opcion)
cnn.Open()
dt.Load(cmd.ExecuteReader(), LoadOption.OverwriteChanges)
cnn.Close()
Catch ex As Exception
Dim msgError As String
msgError = ex.Message.ToString()
cnn.Close()
End Try
Return dt
End Function
End Class
It's called from Page_Load() via this method:
Sub LoadCountries()
Try
Dim dv As New DataView(New ClCountries().Read(1))
ddlCountry.DataSource = dv
ddlCountry.DataTextField = "Name"
ddlCountry.DataValueField = "ID"
ddlCountry.DataBind()
Dim li As New ListItem("Select Country", "0")
ddlCountry.Items.Insert(0, li)
Catch ex As Exception
End Try
End Sub
The connecction string in the aspx :
<connectionStrings>
<add name="cnnPortalSmart" connectionString="Data Source=IP_NUMBER;Initial Catalog=SCHEMA_NAME; User ID=root;Password=XXXX;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
Thank you.
Hope this may helpful to you
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT CustomerId, Name FROM Customers")
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
ddlCustomers.DataSource = cmd.ExecuteReader()
ddlCustomers.DataTextField = "Name"
ddlCustomers.DataValueField = "CustomerId"
ddlCustomers.DataBind()
con.Close()
End Using
End Using
ddlCustomers.Items.Insert(0, New ListItem("--Select Customer--", "0"))
End If
End Sub
I solved it by modifying the connection string to:
<connectionStrings>
<add name="cnnPortalSmart" connectionString="server=XXXX;user id=XXXX;password=XXXXX!;persistsecurityinfo=True;database=XXXXX;SslMode=none" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>

VB.NET webpage gets access denied when trying to upload a file to a database

I'm attempting to write a page to upload a logo onto a SQL database. However, I keep getting access denied errors. When I run the procedure, the following exception is thrown:
System.UnauthorizedAccessException: Access to the path 'C:\Users\ANDY\Pictures\Logo.PNG' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at _Default.SaveToDB(String info) in...
The file: 'C:\Users\ANDY\Pictures\Logo.PNG' is on my client (not the server) and if I grant everyone full control permissions to the file, then it uploads to the remote server successfully.
I cant ask my users to change their permissions to upload files.
during my testing I have tried it on 2 computers:
+My development computer:
-in debug mode in visual studio, it works great
-on the same computer, if I load it into IIS it throws an the exception above requiring permissions to be granted to the local file or folder that I am trying to upload.
+My Production Server:
-The same files uploaded to the production server produce a slightly different error. This time it wants permissions to modify this path on the server: c:\Windows\System32\inetsrv I thought I'd try granting access to this folder to the NetworkService account, however, it appears that this is a protected folder and you cannot modify permissions to folders under System32. you also cannot add the NetworkService account to local Administrators (I know, I know - bad security - but I'm just troubleshooting here).
IIS 6 with SQL server 2008 R2 is hosting the site.
Web page code is as follows:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="TestImageUpload.aspx.vb" Inherits="_Default" MasterPageFile="MasterPage.master"%>
<%# Register Src="sideMenuControl.ascx" TagName="sideMenuControl" TagPrefix="uc1" %>
<asp:Content ID="contentHolder" ContentPlaceHolderID="ContentPlaceHolder" runat="Server">
<div id="mainContent">
<div id="sidecol">
<uc1:sideMenuControl ID="SideMenuControl1" runat="server" />
</div>
<div id="content">
<h1>Upload your company logo here</h1>
<asp:Label ID="Label3" runat="server" Text="Select your Logo File:"></asp:Label>
<br />
<input id="FileUpload1" type="file" runat="server" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Update my Logo" />
<br />
<asp:Label ID="Label2" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</asp:Content>
VB codefile is as follows:
Imports System.Data
Imports System.Collections.Generic
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports MigrateNationalTrades
Imports System.IO
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FileUpload1.Value <> "" Then
Label1.Text = ""
Label2.Text = "Starting upload of: " + FileUpload1.Value.ToString().Trim()
Dim imageInfo As FileInfo = New FileInfo(FileUpload1.Value.ToString().Trim())
Select Case (imageInfo.Extension.ToUpper())
Case ".JPG" : SaveToDB(Me.FileUpload1.Value.Trim())
Case ".JPEG" : SaveToDB(Me.FileUpload1.Value.Trim())
Case ".GIF" : SaveToDB(Me.FileUpload1.Value.Trim())
Case ".BMP" : SaveToDB(Me.FileUpload1.Value.Trim())
Case ".PNG" : SaveToDB(Me.FileUpload1.Value.Trim())
Case Else
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alertMsg", "<script>alert('Error: Unknown File Type.');</script>")
End Select
Else
Label1.Text = "Please cloose a file and try again"
Label2.Text = "" + FileUpload1.Value.ToString()
End If
End Sub
Private Sub SaveToDB(ByVal info As String)
Dim objconn As SqlConnection
objconn = New SqlConnection(ConfigurationManager.ConnectionStrings("TestConnectionString").ConnectionString)
Dim objCom As SqlCommand
Try
Dim imagestream As FileStream = New FileStream(info, FileMode.Open)
Dim data() As Byte
ReDim data(imagestream.Length - 1)
imagestream.Read(data, 0, imagestream.Length)
imagestream.Close()
objCom = New SqlCommand("insert into Logos(UserID,Logo) values (#UserID,#Logo)", objConn)
Dim useridparameter As SqlParameter = New SqlParameter("#UserID", SqlDbType.Int)
useridparameter.Value = "251"
objCom.Parameters.Add(useridparameter)
Dim logoparameter As SqlParameter = New SqlParameter("#Logo", SqlDbType.Image)
logoparameter.Value = data
objCom.Parameters.Add(logoparameter)
objconn.Open()
objCom.ExecuteNonQuery()
objconn.Close()
Label2.Text = "Logo uploaded successfully!"
Catch ex As Exception
Label1.Text = ""
Label2.Text = "Failed: " + ex.ToString()
End Try
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
'Form.Enctype() = "multipart/form-data"
End Sub
End Class
I'm puzzled as to why the system needs write access to the file that it is reading for upload. maybe you guys and gals can help me out?
Try this below. fileData is what you will pass to you sql.
Change asp control to:
<asp:FileUpload ID="FileUpload1" runat="server" />
Then use:
If FileUpload1.ContentLength > 0 Then
Dim size As Integer = FileUpload1.ContentLength
Dim name As String = FileUpload1.FileName
Dim position As Integer = name.LastIndexOf("\")
name = name.Substring(position + 1)
Dim contentType As String = FileUpload1.ContentType
Dim fileData As Byte() = New Byte(size - 1) {}
FileUpload1.InputStream.Read(fileData, 0, size)
End If
Many thanks to RickJames who helped me out with this conundrum. He's awesome! here is the final working code for the file upload routine that tested out ok on all my machines. I guess it was the full path that was stopping the process from working correctly and the FileUpload control handles that for you:
Web Page:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="TestImageUpload.aspx.vb" Inherits="_Default" MasterPageFile="MasterPage.master"%>
<%# Register Src="sideMenuControl.ascx" TagName="sideMenuControl" TagPrefix="uc1" %>
<asp:Content ID="contentHolder" ContentPlaceHolderID="ContentPlaceHolder" runat="Server">
<div id="mainContent">
<div id="sidecol">
<uc1:sideMenuControl ID="SideMenuControl1" runat="server" />
</div>
<div id="content">
<h1>Upload your company logo here</h1>
<asp:Label ID="Label3" runat="server" Text="Select your Logo File:"></asp:Label>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Update my Logo" />
<br />
<asp:Label ID="Label2" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</asp:Content>
and here is the working VB script:
Imports System.Data
Imports System.Collections.Generic
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Text.RegularExpressions.Regex
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FileUpload1.FileContent.Length > 0 Then
End If
If FileUpload1.FileContent.Length > 0 Then
Label1.Text = ""
Label2.Text = "Starting upload of: " + FileUpload1.FileName.ToString().Trim()
SaveToDB(FileUpload1.FileName.ToString().Trim())
'Dim imageInfo As FileInfo = New FileInfo(FileUpload1.Value.ToString().Trim())
'Select Case (imageInfo.Extension.ToUpper())
' Case ".JPG" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case ".JPEG" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case ".GIF" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case ".BMP" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case ".PNG" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case Else
'ClientScript.RegisterClientScriptBlock(Me.GetType(), "alertMsg", "<script>alert('Error: Unknown File Type.');</script>")
'End Select
Else
Label1.Text = "Please choose a file and try again"
Label2.Text = "" + FileUpload1.FileName.ToString()
End If
End Sub
Private Sub SaveToDB(ByVal name As String)
Dim objconn As SqlConnection
objconn = New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
Dim objCom As SqlCommand
Try
Dim size As Integer = FileUpload1.FileContent.Length
Dim position As Integer = name.LastIndexOf("\")
name = name.Substring(position + 1)
Dim contentType As String = FileUpload1.PostedFile.ContentType
Dim fileData As Byte() = New Byte(size - 1) {}
FileUpload1.PostedFile.InputStream.Read(fileData, 0, size)
Label2.Text = fileData.ToString()
objCom = New SqlCommand("insert into Logos(UserID,Logo) values (#UserID,#Logo)", objconn)
Dim useridparameter As SqlParameter = New SqlParameter("#UserID", SqlDbType.Int)
useridparameter.Value = "251"
objCom.Parameters.Add(useridparameter)
Dim logoparameter As SqlParameter = New SqlParameter("#Logo", SqlDbType.Image)
logoparameter.Value = fileData
objCom.Parameters.Add(logoparameter)
objconn.Open()
objCom.ExecuteNonQuery()
objconn.Close()
Label2.Text = "Logo uploaded successfully!"
Catch ex As Exception
Label1.Text = "" + name
Label2.Text = "Failed: " + ex.ToString()
End Try
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
'Form.Enctype() = "multipart/form-data"
End Sub
End Class

Code behide VB.connection string?

I am currently developing a webpage using ASP.NET with VB as back end. But I am facing a problem. I don't know how to make a database connection to connect with MYSQL WORKBENCH. I just wrote the connection but it just code for SQL server.
This is my sample code for connection but it for sql server. I just want code for mySQL workbench.
Imports System.Data
Imports System.Data.SqlClient
Partial Class Request
Inherits System.Web.UI.Page
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
txt1.Focus()
txt2.Focus()
txt3.Focus()
txt4.Focus()
txt5.Focus()
txt6.Focus()
txt7.Focus()
ddl1.Focus()
ddl2.Focus()
ddl3.Focus()
ddl4.Focus()
End Sub
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
con.ConnectionString = "Server=localhost;Database=test;Uid=root;Pwd=1234;"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO cr_record (Emplid, Nama, date, DeptDesc, email, Change, reasonchange,problem,priority,reasondescription,systemrequest) VALUES (#Emplid, #Nama, #date, #DeptDesc, #email, #Change, #reasonchange,#problem,#priority,#reasondescription,#systemrequest)"
cmd.Parameters.AddWithValue("#Emplid", ddl1.Text)
cmd.Parameters.AddWithValue("#Nama", TextBox1.Text)
cmd.Parameters.AddWithValue("#date", txt5.Text)
cmd.Parameters.AddWithValue("#DeptDesc", txt2.Text)
cmd.Parameters.AddWithValue("#email", txt4.Text)
cmd.Parameters.AddWithValue("#Change", ddl2.Text)
cmd.Parameters.AddWithValue("#reasonchange", txt6.Text)
cmd.Parameters.AddWithValue("#problem", ddl3.Text)
cmd.Parameters.AddWithValue("#priority", rbl1.Text)
cmd.Parameters.AddWithValue("#reasondescription", txt7.Text)
cmd.Parameters.AddWithValue("#systemrequest", ddl4.Text)
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Added Successfully")
End Sub
End Class
You will need to download and reference the MySQL .NET Connector http://dev.mysql.com/downloads/connector/net/. You will then use the System.Data.MySqlClient namespace and replace your SqlConnection and SqlCommand with MySqlConnection and MySqlCommand

how to avoid error A control with ID 'SqlDataSource1' could not be found

In this prgram i am getting below error:
The DataSourceID of GridView1 must be the ID of a control of type IDataSource. A control with ID SqlDataSource1 could not be found.
Imports MySql.Data.MySqlClient
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Dim con As MySqlConnection = New MySqlConnection("data source=localhost;database=dbconnect;user id=root;password=search;")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btn_display_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_display.Click
Dim connection As MySqlConnection = New MySqlConnection("data source=localhost;database=dbconnect;user id=root;password=search;")
Dim mydataset As New DataSet()
Dim mydataadpter As MySqlDataAdapter = New MySqlDataAdapter()
Dim mysql As MySqlCommand = New MySqlCommand("select * from userinfo", connection)
connection.Open()
mydataadpter.SelectCommand = mysql
mydataadpter.Fill(mydataset, "product")
Try
'GridView1.DataSource = mydataset
GridView1.DataBind()
GridView1.DataMember = "product"
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Remove the DataSourceID attribute and its value (DataSourceID="SqlDataSource1") from your GridView1 control inside the source view (.aspx).
The problem is that the DataSourceID property is designed to be used in an ASPX page and you are in the code. You want to use the DataSource property instead. It is looking in your ASPX page for a control named "SqlDataSource1" and there is not one. If you create this SqlDataSource1 object in the ASPX page instead of in the code you will be able to set the DataSourceID to the ID of the SqlDataSource1 object
DataSourceID="SqlDataSource1"