I have done this previously but in a different way. I am trying to get the code below to work. If I do not cast 'OriginalPhoto' or 'Thumbnail' an error occurs. Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. I don't understand why it asking to cast. However if I do cast it, the images add to the database just fine in a binary data format. When trying to view the images, i get the error 'Unable to display the given data'. I have inserted both byte[] into a table using a SqlDataAdapter and that works. I want to use this method though, what am I doing wrong?
PROFILEGALLERY TABLE CONTAINS:
UserId nvarchar(50)
Title nvarchar(10)
OriginalImage varbinary(max)
ThumbImage varbinary(max)
protected void AddPhotoToDatabase()
{
byte[] OriginalPhoto = GetImage();
byte[] Thumbnail = GenerateThumbnail();
string Title = FileUpload1.FileName.ToString();
string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES ('" + User.Identity.Name + "', '" + Title + "', CAST('" + OriginalPhoto + "'AS VARBINARY(MAX)), CAST('" + Thumbnail + "'AS VARBINARY(MAX)))";
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
protected byte[] GetImage()
{
byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
FileUpload1.PostedFile.InputStream.Read(photo, 0, photo.Length);
return photo;
}
protected byte[] GenerateThumbnail()
{
System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
double thumbwidth = 0;
double thumbheight = 0;
double imgsz = 150.0;
if (imgsz / image.Width < imgsz / image.Height)
{
thumbwidth = image.Width * (imgsz / image.Width);
thumbheight = image.Height * (imgsz / image.Width);
}
else
{
thumbwidth = image.Width * (imgsz / image.Height);
thumbheight = image.Height * (imgsz / image.Height);
}
System.Drawing.Image thumb = image.GetThumbnailImage((int)thumbwidth, (int)thumbheight, delegate() { return false; }, (IntPtr)0);
MemoryStream ms = new MemoryStream();
thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
You should use sql parameters:
using( SqlConnection cnn = GetConnection() ) {
using( SqlCommand cmd = cnn.CreateCommand() ) {
cmd.CommandText = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES (#UserId, #Title, #OriginalPhoto, #Thumbnail)";
cmd.Parameters.AddWithValue( "#UserId", User.Identity.Name );
cmd.Parameters.AddWithValue( "#Title", Title );
cmd.Parameters.AddWithValue( "#OriginalPhoto", OriginalPhoto );
cmd.Parameters.AddWithValue( "#Thumbnail", Thumbnail );
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
}
}
Don't try to build the data into the insert query. Try this:
string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage],
[ThumbImage]) VALUES (#userId, #title, #originalImage, #thumbImage)";
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.Add(new SqlParameter("#userId", User.Identity.Name));
comm.Parameters.Add(new SqlParameter("#title", Title));
comm.Parameters.Add(new SqlParameter("#originalImage", OriginalPhoto));
comm.Parameters.Add(new SqlParameter("#thumbImage", Thumbnail));
Just looking at your code, I'm a little concerned that you are wide open for a SQL Injection attack. To help mitigate this should also fix your problem. You need to use a parametized query. Something like
cmd.CommandText="Insert into [ProfileGallery]" +
"(UserId,OriginalPhoto) values (#UserId,#OriginalPhoto)";
cmd.Parameters.AddWithValue("UserId",User.Identity.Name);
cmd.Parameters.AddWithValue("OriginalPhoto",OriginalPhoto);
The reason your code is failing can be seen with this sample application:
static void Main(string[] args)
{
byte[] byteArray = new byte[] { 1, 2, 0 };
Console.WriteLine("This is my byte array: " + byteArray);
Console.ReadLine();
}
This outputs This is my byte array: System.Byte[]
I'm a little shocked that you can add a byte array to a string, especially sicne it just gives us the name of the type.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
string strSQL = "Select * from table6";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn);
DataSet ds = new DataSet();
dt.Fill(ds);
grd1.DataSource = ds;
grd1.DataBind();
cn.Close();
}
protected void btn1_Click(object sender, EventArgs e)
{
if(fileupload.HasFile)
{
string imageSrc = "~/Image/" +fileupload.PostedFile.FileName;
string ImageName = txt1.Text;
SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
cn.Open();
string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.ExecuteNonQuery();
cn.Close();
BindData();
txt1.Text = "";
}
This simple code is enough to insert images to SQL without taking HTTP Handler
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
string strSQL = "Select * from table6";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn);
DataSet ds = new DataSet();
dt.Fill(ds);
grd1.DataSource = ds;
grd1.DataBind();
cn.Close();
}
protected void btn1_Click(object sender, EventArgs e)
{
if(fileupload.HasFile)
{
string imageSrc = "~/Image/" +fileupload.PostedFile.FileName;
string ImageName = txt1.Text;
SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
cn.Open();
string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.ExecuteNonQuery();
cn.Close();
BindData();
txt1.Text = "";
}
Related
I tried to save a picture into database using Sqlcommand . When I save , there is an exception throw said " Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query."
here is the code:
private void btn_save_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd1= new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
string squ1;
squ1 = "INSERT INTO Customer (cus_name, cus_address, cus_Image)Values('" + textBox1.Text + "' , '" + textBox2.Text + "', '"+pictureBox1 .Image +"');";
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30";
con.Open();
cmd1.Connection = con;
cmd1.CommandText = squ1;
cmd1.ExecuteNonQuery();
con.Close ();
}
// the browser button to get a picture
private void btn_browseImage_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
if (f.ShowDialog () == DialogResult .OK )
{
pictureBox1.ImageLocation = f.FileName;
}
You have to pass the image data as a varbinary parameter to the query:
using (var con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30"))
using (var cmd1 = new SqlCommand("INSERT INTO Customer (cus_name, cus_address, cus_Image)Values(#name, #address, #image);", con))
{
var imageData = new MemoryStream();
pictureBox1.Image.Save(imageData, pictureBox1.Image.RawFormat);
cmd1.Parameters.AddWithValue("#name", textBox1.Text);
cmd1.Parameters.AddWithValue("#address", textBox2.Text);
cmd1.Parameters.Add("#image", SqlDbType.VarBinary).Value = imageData.ToArray();
con.Open();
var result = cmd1.ExecuteNonQuery();
}
And you should really read up on how to use SqlCommand to avoid future SQL injection.
The statement '"+pictureBox1.Image +"' will actually call pictureBox1.Image.ToString() which is not the binary content of the image. Use SqlParameters to add your binary data. You can find a solution here...
I have two textboxes and two buttons on one site. The problem is that this second textbox and second button doesn't work. First textbox+button doing well:
int NoOfDigTextBoxEngine;
protected void TextBoxADDEngine_TextChanged(object sender, EventArgs e)
{
NoOfDigTextBoxEngine = TextBoxADDEngine.Text.Length;
}
protected void ButtonADDEngine_Click(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Engine, Created, LastChange, WhoInserted, WhoLastModified, Disable FROM PartsEngine";
cmd.Connection = con;
sda.SelectCommand = cmd;
if (FillWhoIsLogged > 0) // ----------------Wypełnianie tebeli kiedy jest ktos zalogowany--- //
{
if (NoOfDigTextBoxEngine == 7)
{
try
{
Convert.ToInt32(TextBoxADDEngine.Text);
con.Open();
cmd.CommandText = ("INSERT INTO PartsEngine ([Engine], [Created], [WhoInserted], [Disabled]) VALUES ('" + TextBoxADDEngine.Text + "', GETDATE(), '" + FillWhoIsLogged + "', '1');");
cmd.ExecuteNonQuery();
GridView3.DataBind();
TextBoxADDEngine.Text = string.Empty;
con.Close();
}
catch
{
Response.Write("<script type='text/javascript'> alert('Nr Silnika może zawierać jedynie cyfry.')</script>");
TextBoxADDEngine.Text = string.Empty;
}
}
else
{
Response.Write("<script type='text/javascript'> alert('Nr Silnika musi mieć 7 cyfr.Podano: " + NoOfDigTextBoxEngine + " ')</script>");
TextBoxADDEngine.Text = string.Empty;
}
}
}
}
But the second (is the same) don't want to work.
int NoOfDigTextBoxGear;
protected void TextBoxADDGear_TextChanged(object sender, EventArgs e)
{
NoOfDigTextBoxGear = TextBoxADDGear.Text.Length;
}
protected void ButtonADDGear_Click(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Gear, Created, LastChange, WhoInserted, WhoLastModified, Disable FROM PartsGear";
cmd.Connection = con;
sda.SelectCommand = cmd;
if (FillWhoIsLogged > 0) // ----------------Wypełnianie tebeli kiedy jest ktos zalogowany--- //
{
if (NoOfDigTextBoxGear == 7)
{
try
{
Convert.ToInt32(TextBoxADDGear.Text);
con.Open();
cmd.CommandText = ("INSERT INTO PartsGear ([Gear], [Created], [WhoInserted], [Disabled]) VALUES ('" + TextBoxADDGear.Text + "', GETDATE(), '" + FillWhoIsLogged + "', '1');");
cmd.ExecuteNonQuery();
GridView5.DataBind();
TextBoxADDGear.Text = string.Empty;
con.Close();
}
catch
{
Response.Write("<script type='text/javascript'> alert('Nr Skrzyni może zawierać jedynie cyfry.')</script>");
TextBoxADDGear.Text = string.Empty;
}
}
else
{
Response.Write("<script type='text/javascript'> alert('Nr Skrzyni musi mieć 7 cyfr. Podano: "+ NoOfDigTextBoxGear +" ')</script>");
TextBoxADDGear.Text = string.Empty;
}
}
}
}
When i write something in second textbox and then click button- always NoOfDigTextBoxGear = 0...why?
It's not make any sense for me because this code(for second textbox and button) is the same like the the first one(for first textbox and button).
Oh... i just saw this:
<asp:TextBox ID="TextBoxADDGear" runat="server" Visible="False"
Width="96px"></asp:TextBox>
I didn't add ontextchanged(!)
ontextchanged="TextBoxADDGear_TextChanged"
Now everything is ok.
I am trying to get next rows from the table of access database but I am getting last row all time.
Please guide me how to loop through all rows?
Here is the code:
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; DataSource=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
while(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
con1.Close();
}
=It`s must outside a button click:
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
con1.Close();
Its must inside button click. You must make i property of form
if(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
But i think it`s may rewrite to more beauty solve.
Sounds like you are after something like
private int _currentRecordId = -1;
...
string cmdStr = String.Format("SELECT * FROM Table WHERE id > {0} ORDER BY id LIMIT 1", _currentRecordId);
using (var con = new OleDbConnection(constr))
using (var com = new OleDbCommand(cmdStr, con))
{
con.Open();
using(var reader = com.ExecuteReader())
{
while (reader.Read())
{
_currentRecordId = reader.GetInt32(0); // whatever field the id column is
// populate fields
}
}
}
On first call this will retrieve the first record with an ID > -1. It then records whatever the ID is for this record so then on the next call it will take the first record greater than that e.g. if the first record is id 0 then the next record it will find is 1 and so on...
This only really works if you have sequential IDs of course.
Assuming that your table is not big (meaning it contains a manegeable number of records) you could try to load everything at the opening of your form and store that data in a datatable.
At this point the logic in your button should simply advance the pointer to the record to be displayed.
private DataTable data = null;
private int currentRecord = 0;
protected void form_load(object sender, EventArgs e)
{
using(OleDbConnection con1 = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("select * from table", con1))
{
con1.Open();
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
data = new DataTable();
da.Fill(data);
}
DisplayCurrentRecord();
}
}
private void DisplayCurrentRecord()
{
label1.Text = String.Format("{0}", data.Rows[currentRecord][1]);
RadioButton1.Text = String.Format("{0}", data.Rows[currentRecord][2]);
RadioButton2.Text = String.Format("{0}", data.Rows[currentRecord][3]);
RadioButton3.Text = String.Format("{0}", data.Rows[currentRecord][4]);
RadioButton4.Text = String.Format("{0}", data.Rows[currentRecord][5]);
}
protected void btn_clk(object sender, EventArgs e)
{
if(currentRecord >= data.Rows.Count - 1)
currentRecord = 0;
else
currentRecord++;
DisplayCurrentRecord();
}
Keep in mind that this is just an example. Robust checking should be applied to the rows (if they contains null values) and if there are rows at all in the returned table. Also, this is a poor man approach to the problem of DataBindings in WinForm, so perhaps you should look at some tutorials on this subject
Hope your table is not really named Table, that word is a reserved keyword for Access
simply remove the for loop to fetch record one by one
int lastFetchedRecordIndex=2;
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
string cmdstr = "select * from table where id = " + lastFetchedRecordIndex;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
lastFetchedRecordIndex++;
con1.Close();
}
I am storing images to the database in the table test (id, name, image), by reading images from a picture box.
This is my code:
private void browse_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "(*.BMP;*.JPG;*.GIF;*.JPEG;*.PNG)|*.BMP;*.JPG;*.GIF;*.JPEG;*.PNG";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
imgloc = openFileDialog1.FileName.ToString();
pictureBox1.ImageLocation = imgloc;
}
}
private void save_Click(object sender, EventArgs e)
{
byte[] img = null;
FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
SqlConnection CN = new SqlConnection(constring);
string Query = "insert into test (id,name,image) values('" + txtid.Text + "','" + txtname.Text + "',#img)";
CN.Open();
cmd = new SqlCommand(Query, CN);
cmd.Parameters.Add(new SqlParameter("#img", img));
cmd.ExecuteNonQuery();
CN.Close();
}
It works but I would like to know how to use the update command here.
private void update_Click(object sender, EventArgs e)
{
byte[] img = null;
FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
SqlConnection CN = new SqlConnection(constring);
// this is a smaple query for update statement and update where id=#id
string Query = "update test set name=#name,image=#img where id=#id ";
CN.Open();
cmd = new SqlCommand(Query, CN);
cmd.Parameters.Add(new SqlParameter("#img", img));
cmd.Parameters.Add(new SqlParameter("#id", txtid.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtname.Text));
cmd.ExecuteNonQuery();
CN.Close();
}
Your code and query should be like this :
SqlConnection CN = new SqlConnection(constring);
string Query = "Update test Set name=#Name,image=#Image where id=#id"
CN.Open();
cmd = new SqlCommand(Query, CN);
cmd.Parameters.Add(new SqlParameter("#Image", img));
cmd.Parameters.Add(new SqlParameter("#Name",txtname.Text));
cmd.Parameters.Add(new SqlParameter("#id",txtid.Text));
cmd.ExecuteNonQuery();
CN.Close();
Just delete that particular record using your Id field and Fire the Save query again, if updating is difficult.
SqlConnection con = Connectionclass.SQLCONNECTION();
SqlDataAdapter da = new SqlDataAdapter();
string query = ("Update Doctor set ID ='" + idtxt.Text + "',Name='" + nametxt.Text + "',Contact='" + contactxt.Text + "',CNIC='" + cnictxt.Text + "',Address='" + addresstxt.Text + "',Qualification='" + qualitxt.Text + "',specialization='" + specialtxt.Text + "',Gender='" + gendertxt.Text + "',DOB='" + dobtxt.Text + "', Fee='"+textBox1.Text+"',Date='" + System.DateTime.Today.ToString("dd-MM-yyyy") + "', Picture= #image where ID='" + idtxt.Text + "'");
da.UpdateCommand = new SqlCommand(query, con);
con.Open();
da.UpdateCommand.Parameters.Add("image", SqlDbType.VarBinary).Value = binaryphoto;
int RowsEffected = da.UpdateCommand.ExecuteNonQuery();
con.Close();
I am trying to retrieve image from back end in ASP.Net. Using SQL SERVER 2005 as back end. I have tried n number of codes including the one available online. Can any one guide me solve this issue.
My code is below
Table Design:-
create table Image
(
ImageId Int identity (1,1),ImageName Varchar(50), Image image
)
Code:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
string strcon = "Data Source=SUJITHA\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//getting length of uploaded file
int length = FileUpload1.PostedFile.ContentLength;
//create a byte array to store the binary image data
byte[] imgbyte = new byte[length];
//store the currently selected file in memeory
HttpPostedFile img = FileUpload1.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename =TextBox1.Text;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)", connection);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
TextBox1.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT ImageName,Image from [Image]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Attributes.Add("bordercolor", "black");
}
SqlConnection con = new SqlConnection(#"Data Source=AMAR-PC\SQLEXPRESS;Initial Catalog=a;User ID=sa;Password=amar");
string path = Server.MapPath("Images/");
if (FileUpload1.HasFile)
{
byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile myimage = FileUpload1.PostedFile;
myimage.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
SqlCommand cmd = new SqlCommand("insert into images values ('" + TextBox1.Text + "','" + FileUpload1.PostedFile + "')", con);
con.Open();
This is what i did...and I also know that there are many other ways to upload file....
Now I want that a the uploaded pic should be dispayed in Image Control....could you help me now
*/Your code Like this*
**//Insert the file into database**
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
**//Select the file from database**
string strQuery = "select Name, ContentType, Data from tblFiles where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
private void download (DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
Couple of things worry me
you use the master database
your table name is image which is a reserved word in SQL Server
If you need to name tables with reserved names, you need to quote them with square brackets: INSERT INTO [Image] ...
similar questions have been asked and answered many times here
your acceptance rate is 0%