I have a mysql table called images with MultipleImageID, MultipleImageName, MultipleImageMap and PropertyID (foreign key). The problem I'm having is the actually images seem to duplicate when I upload them but the columns filled with the correct info. Here is an image to better explain.
As you can see the image names are all different as each image should be different but the first image selected seems to upload multiple times. Other times the right image will upload which has confused me as to what was causing this. I am also getting no errors in my code.
Here is my c# for the upload.
protected void Insert(object sender, EventArgs e)
{
string PropertyName = txtName.Text;
string PropertyFeatures = txtPropFeat.Text;
string PropertyLocation = txtPropLoc.Text;
string PropertyInformation = txtPropInfo.Text;
string PropertyNumBeds = txtNumBeds.Text;
string PropertyPrice = txtPrice.Text;
string PropertyType = txtPropType.Text;
long InsertedID;
string constr = ConfigurationManager.ConnectionStrings["realestatedbAddConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO property (PropertyName, PropertyNumBeds, PropertyType, PropertyPrice, PropertyFeatures, PropertyLocation, PropertyInformation, ImageName, ImageMap) VALUES (#PropertyName, #PropertyNumBeds, #PropertyType, #PropertyPrice, #PropertyFeatures, #PropertyLocation, #PropertyInformation, #ImageName, #ImageMap)"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Parameters.AddWithValue("#PropertyName", PropertyName);
cmd.Parameters.AddWithValue("#PropertyNumBeds", PropertyNumBeds);
cmd.Parameters.AddWithValue("#PropertyPrice", PropertyPrice);
cmd.Parameters.AddWithValue("#PropertyType", PropertyType);
cmd.Parameters.AddWithValue("#PropertyFeatures", PropertyFeatures);
cmd.Parameters.AddWithValue("#PropertyLocation", PropertyLocation);
cmd.Parameters.AddWithValue("#PropertyInformation", PropertyInformation);
string FileName = Path.GetFileName(MainImageUploada.FileName);
MainImageUploada.SaveAs(Server.MapPath("ImagesUploaded/") + FileName);
cmd.Parameters.AddWithValue("#ImageName", FileName);
cmd.Parameters.AddWithValue("#ImageMap", "ImagesUploaded/" + FileName);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
InsertedID = cmd.LastInsertedId;
con.Close();
}
}
}
if (ImageUploada.HasFiles)
{
foreach (var file in ImageUploada.PostedFiles)
{
string FileName1 = Path.GetFileName(ImageUploada.FileName);
ImageUploada.SaveAs(Server.MapPath("ImagesUploaded/") + file.FileName);
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO propertyimage(MultipleImageName, MultipleImageMap, PropertyID) VALUES (#MultipleImageName, #MultipleImageMap, #InsertedID); "))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Parameters.AddWithValue("#MultipleImageName", file.FileName);
cmd.Parameters.AddWithValue("#MultipleImageMap", "ImagesUploaded/" + file.FileName);
cmd.Parameters.AddWithValue("#InsertedID", InsertedID);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
txtName.Text = "";
txtPropFeat.Text = "";
txtPropInfo.Text = "";
txtPropLoc.Text = "";
txtNumBeds.Text = "";
txtPrice.Text = "";
txtPropType.Text = "";
Label1.Visible = true;
Label1.Text = "Property Added to Database Successfully!";
}
I am lost to whether its my code, database or the images I am using.
You're correctly looping over ImageUploada.PostedFiles, but then you're ignoring that and calling the methods on ImageUploada itself, which will only handle the first file.
So if you upload multiple files, all files saved on the server will be copies of the first file.
You need to change the code to handle each file individually:
foreach (var file in ImageUploada.PostedFiles)
{
string FileName1 = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("ImagesUploaded/") + file.FileName);
// ...
}
Related
I have an upload button that can upload excel file and save it to my database. What I want to happen is that if there's one or more data in that excel file that already existing the other data will also not be uploaded though it's not yet existing. My code for adding it to the database and upload button are below.
Add to database
private void AddNewTrainee(string strdelname, string strrank, string strcomp, string strcourse, string strcenter, string strinst,
string strsdate, string stredate, string strcissued, string strcnumber, string strremark, int recdeleted, string credate, string update, int fromupload)
{
connection.Open();
String checkDateAndName = "Select count(*) from Trainees where StartDate= '" + strsdate + "' and Delegate='" + strdelname + "' and REC_DELETED = 0 ";
SqlCommand cmd = new SqlCommand(checkDateAndName, connection);
int dataRepeated = Convert.ToInt32(cmd.ExecuteScalar().ToString());
bool boolDataRepated;
connection.Close();
if (!(dataRepeated >= 1))
{
boolDataRepated = false;
}
else
boolDataRepated = true;
connection.Open();
string certNumber = "Select * from CertID_Table update CertID_Table set CertificateID = CertificateID + 1 from CertID_Table ";
SqlCommand cmdCert = new SqlCommand(certNumber, connection);
using (SqlDataReader oReader = cmdCert.ExecuteReader())
{
while (oReader.Read())
{
string test1 = oReader["CertificateID"].ToString();
ViewState["certnumber"] = test1;
}
}
connection.Close();
strcnumber = (string)ViewState["certnumber"];
if (boolDataRepated == false)
{
string path = "D:\\Intern\\BASSWeb\\SQLCommands\\AddSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
try
{
connection.Open();
SqlCommand cmd1 = new SqlCommand(sql, connection);
cmd1.Parameters.AddWithValue("#delName", strdelname);
cmd1.Parameters.AddWithValue("#rank", strrank);
cmd1.Parameters.AddWithValue("#comp", strcomp);
cmd1.Parameters.AddWithValue("#course", strcourse);
cmd1.Parameters.AddWithValue("#center", strcenter);
cmd1.Parameters.AddWithValue("#instructor", strinst);
cmd1.Parameters.AddWithValue("#sdate", strsdate);
cmd1.Parameters.AddWithValue("#edate", stredate);
cmd1.Parameters.AddWithValue("#cissued", strcissued);
cmd1.Parameters.AddWithValue("#cnumber", strcnumber);
cmd1.Parameters.AddWithValue("#remark", strremark);
cmd1.Parameters.AddWithValue("#rdeleted", recdeleted);
cmd1.Parameters.AddWithValue("#cdate", credate);
cmd1.Parameters.AddWithValue("#udate", update);
cmd1.Parameters.AddWithValue("#fupload", fromupload);
cmd1.CommandType = CommandType.Text;
cmd1.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert/Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
}
else
{
string script = "alert(\"The data already exists\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
}
Upload Button
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/Datas/") + path);
String ExcelPath = Server.MapPath("~/Datas/") + path;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
OleDbCommand cmdX = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmdX.ExecuteReader();
while (dr.Read())
{
delegateName = dr[0].ToString();
rankPos = dr[1].ToString();
company = dr[2].ToString();
courseTitle = dr[3].ToString();
trainingCenter = dr[4].ToString();
instructor = dr[5].ToString();
staDa = DateTime.Parse(dr[6].ToString());
string startDate = staDa.ToString("MM/dd/yyyy");
endDa = DateTime.Parse(dr[7].ToString());
string endDate = endDa.ToString("MM/dd/yyyy");
certIssued = dr[8].ToString();
certNum = dr[9].ToString();
remarks = dr[10].ToString();
recDeleted = 0;
dateCreated = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
dateUpdated = string.Empty;
fromUpload = 1;
AddNewTrainee(delegateName, rankPos, company, courseTitle, trainingCenter, instructor,
startDate, endDate, certIssued, certNum, remarks, recDeleted, dateCreated, dateUpdated, fromUpload);
}
}
catch (Exception ex)
{
string errorMessage = "alert(\"ERROR: " + ex.Message.ToString() + " \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
}
else
{
string errorMessage = "alert(\"ERROR: You have not specified a file \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
PopulateData();
}
You have to set the transferMode to 'Streamed', otherwise you will always get one file.
Have a look at this article: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-enable-streaming
I think there is a few things you'll need to tackle to reach your end goal.
Use a multiselect method and a get a post list of all files required
for upload.
Do your processing requirements in a Transaction
When your done processing, commit or rollback the transaction as necessary and keep the data you want.
Study the link I posted a little bit. At first transaction seem a little bit overwhelming, but they are actually very simple. Maybe I can help you get started in your understandings. There are really only three extra steps;
1.
Initialize a transaction object after you create a command.
SqlTransaction transaction = connection.BeginTransaction();
2.
On all of your Sql Commands (Inserts,updates, deletes ect) attach the transaction.
cmd.Transaction = transaction;
This will allow you to Execute the SqlCommands without actually putting them into your database. Lastly, when you've processed all of your inserts and updates you can do the final step. The using statement is not required, just good practice. That could be the next thing you'll want to understand it is very helpful.
3.
Commit all SqlCommands to the database.
transaction.Commit();
If at any point during your data processing, something goes wrong than you can rollback every transaction like this.
transaction.Rollback();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (Request.InputStream.Length > 0)
{
using (StreamReader reader = new StreamReader(Request.InputStream))
{
string hexString = Server.UrlEncode(reader.ReadToEnd());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/losefound/{0}.png", imageName);
string ItemName = txtItemName.Text;
string Place = txtPlace.Text;
byte[] bytes = ConvertHexToBytes(hexString);
File.WriteAllBytes(Server.MapPath(imagePath), bytes);
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
string query = "INSERT INTO LostFound (ItemName, FoundAt, TimeIn, ImageName, ContentType, Data) VALUES(#ItemName, #FoundAt, #TimeIn, #ImageName, #ContentType, #Data);SELECT SCOPE_IDENTITY()";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#ItemName", ItemName);
cmd.Parameters.AddWithValue("#FoundAt", Place);
cmd.Parameters.AddWithValue("#TimeIn", DateTime.Now);
cmd.Parameters.AddWithValue("#ImageName", imageName);
cmd.Parameters.AddWithValue("#ContentType", "image/png");
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
Session["CapturedImageId"] = cmd.ExecuteScalar();
con.Close();
}
}
}
}
}
}
private static byte[] ConvertHexToBytes(string hex)
{
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
[WebMethod(EnableSession = true)]
public static string GetCapturedImage()
{
string url = string.Empty;
int imageId = Convert.ToInt32(HttpContext.Current.Session["CapturedImageId"]);
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Data FROM LostFound WHERE Id = #Id";
cmd.Parameters.AddWithValue("#Id", imageId);
cmd.Connection = con;
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
url = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
con.Close();
}
}
HttpContext.Current.Session["CapturedImageId"] = null;
return url;
}
protected void btnCapture_Click(object sender, EventArgs e)
{
}
}
The values form the textbox never inserted into the database. only
datetime.now, imageName, contentType and data can be inserted.
should the insert textbox query at btncapture?
Can someone guide me where am I going wrong?
This code should at least be in a button click.
By the time the page_load event is called in the asp.net page event life cycle the TextBoxes will have been cleared.
You're only submitting to DB if it's not a postback.
if (!this.IsPostBack)
Since you're only running this in Page_Load, the textfields will probably not have any user inputs, and is therefore blank. Either you can do it on PostBack.
if (this.IsPostBack)
{
// Do stuff
}
Or, even better, do as Jeremy Thompson suggested and assign an event handler when the user clicks a button. Doing this kind of logic in Page_Load often come back and haunt you later. What happens when some other developer adds an UpdatePanel, or another postback event? Then this code will run at every postback. It will not scale very good. It seems as you already got an event handler for this - btnCapture_Click, I suggest that you use it.
Example:
In your HTML:
<asp:Button ID="Button1" runat="server" onclick="btnCapture_Click" Text="Button" />
And in your CS:
protected void btnCapture_Click(object sender, EventArgs e)
{
if (Request.InputStream.Length > 0)
{
using (StreamReader reader = new StreamReader(Request.InputStream))
{
string hexString = Server.UrlEncode(reader.ReadToEnd());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/losefound/{0}.png", imageName);
string ItemName = txtItemName.Text;
string Place = txtPlace.Text;
byte[] bytes = ConvertHexToBytes(hexString);
File.WriteAllBytes(Server.MapPath(imagePath), bytes);
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
string query = "INSERT INTO LostFound (ItemName, FoundAt, TimeIn, ImageName, ContentType, Data) VALUES(#ItemName, #FoundAt, #TimeIn, #ImageName, #ContentType, #Data);SELECT SCOPE_IDENTITY()";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#ItemName", ItemName);
cmd.Parameters.AddWithValue("#FoundAt", Place);
cmd.Parameters.AddWithValue("#TimeIn", DateTime.Now);
cmd.Parameters.AddWithValue("#ImageName", imageName);
cmd.Parameters.AddWithValue("#ContentType", "image/png");
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
Session["CapturedImageId"] = cmd.ExecuteScalar();
con.Close();
}
}
}
}
}
If you're having trouble binding the button you can take a look at this question.
First, check if you have AutoEventWireup="true" in the declaration of your aspx.
You can also try to manually assigning the delegate.
btnCapture += new EventHandler(btnCapture_Click);
I am try to check if any column1, any of the cell's is not empty. i want to make then empty and copy the file to next column-cell. What ,my idea is to check if one particular Column1- all cells lets say "COLUMN1" one of the cell is not empty. Then i need the file [ I have attached the file path to that particular cell] to get copied to next column2. at the same time i want to copy the file to a folder on my desktop Lets say the location is C:/user/elec/copy, and i want to erase the Column1 -cell data.
How can i do this. Link for what i am trying to do..
Edited coding.....
private void button6_Click(object sender, EventArgs e)
{
string copyPath = #"C:\user\elec\copy";
if (!System.IO.Directory.Exists(copyPath))
System.IO.Directory.CreateDirectory(copyPath);
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[2].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[2].Value.ToString()))
{
string filePath = dataGridView1.Rows[i].Cells[2].Value.ToString();
if (System.IO.File.Exists(filePath))
{
string fileName = System.IO.Path.GetFileName(filePath);
string newpath = System.IO.Path.Combine(copyPath, fileName);
System.IO.File.Copy(filePath, newpath, true);
dataGridView1.Rows[i].Cells[3].Value = newpath;
try
{
SqlConnection con = new SqlConnection(#"Data Source=SREEJITHMOHA492\SQLEXPRESS;Initial Catalog=cndb;Integrated Security=True");
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "update cncinfo set draftpath=#draftpath,releasepath=#releasepath Where part=#part";
cmd.Parameters.Add("#draftpath", SqlDbType.NVarChar).Value = filePath;
cmd.Parameters.Add("#releasepath", SqlDbType.NVarChar).Value = newpath;
cmd.CommandText = "update cncinfo set draftpath='" + string.Empty + "',releasepath=#releasepath Where part=#part";
//you must have the id value in datagridview to update the specific record.
cmd.Parameters.Add("#part", SqlDbType.NVarChar).Value = Convert.ToString(dataGridView1.Rows[i].Cells["Part Number"].Value);
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
dataGridView1.Rows[i].Cells[2].Value = string.Empty;
}
}
}
There are lot of problems in your code. you are trying to read DataGridViewCell instead of its value. to read the cell value you must have to return value from .Value property of DataGridVIewCell. ie. string x=dgv.Rows[0].Cells[1].Value. Row does not contains Columns it contains Cells. So, to read the value from particular cell you should read that value from Cell object instead of Column.
private void button6_Click(object sender, EventArgs e)
{
string copyPath = #"C:\user\elec\copy";
if (!System.IO.Directory.Exists(copyPath))
System.IO.Directory.CreateDirectory(copyPath);
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value != null &&
!String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[0].Value.ToString()))
{
string filePath = dataGridView1.Rows[i].Cells[0].Value.ToString();
if (System.IO.File.Exists(filePath))
{
string fileName = System.IO.Path.GetFileName(filePath);
string newpath = System.IO.Path.Combine(copyPath, fileName);
System.IO.File.Copy(filePath, newpath, true);
dataGridView1.Rows[i].Cells[1].Value = newpath;
try
{
Using (SqlConnection con = new SqlConnection(#"Data Source=STACY121\SQLEXPRESS;Initial Catalog=cndb;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "update cncinfo set Column1=#Column1,Column2=#Column2 Where id=#id";
cmd.Parameters.Add("#Column1",SqlDbType.VarChar).Value =filePath;
cmd.Parameters.Add("#Column2",SqlDbType.VarChar).Value =newpath;
//you must have the id value in datagridview to update the specific record.
cmd.Parameters.Add("#id",SqlDbType.Int).Value =Convert.ToInt32(dataGridView1.Rows[i].Cells["id"].Value);
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
dataGridView1.Rows[i].Cells[0].Value = string.Empty;
}
}
}
EDITED:
if you would like to copy with different file name then you can specify the file name like this.
int iFileNo = 1; // this is the part of file number in sample-rev-01
string fileName = System.IO.Path.GetFileName(filePath);
string ext = new System.IO.FileInfo(filePath).Extension;
//if the file name is sample.txt then it would be return as sample-rev-01.txt
fileName = String.Format("{0}-rev-{1:00}{2}", fileName.Replace(ext, ""), iFileNo, ext);
string newpath = System.IO.Path.Combine(copyPath, fileName);
System.IO.File.Copy(filePath, newpath, true);
I am developing a winform application in VS 2010 C#.
I have developed a form to insert and update the user details in this.
My Update user form is as below image
![Update User Screen][1]
http://i.stack.imgur.com/iZaAJ.png
And coding to update is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Drawing.Imaging;
using System.IO;
namespace SampleApplication
{
public partial class UserUpdate : Form
{
public UserUpdate()
{
InitializeComponent();
}
SqlDataAdapter da;
SqlConnection con = new SqlConnection("user id=sa; password=123;initial catalog=Inventory;data source=Aniket-PC");
SqlCommand cmd;
MemoryStream ms;
byte[] photo_array;
DataSet ds;
int rno = 0;
string str;
private void nameTxt_Validating(object sender, CancelEventArgs e)
{
if (nameTxt.Text.Trim().Length == 0)
{
namewarning.Visible = true;
}
else
{
namewarning.Visible = false;
}
}
private void Update_Load(object sender, EventArgs e)
{
contTxt.MaxLength = 10;
retriveData();
retriveImg();
}
void retriveImg()
{
con.Open();
cmd = new SqlCommand("Select Logo from Register where UserName='" + uNameTxt.Text + "'", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet("MyImage");
da.Fill(ds, "MyImage");
DataRow myRow;
myRow = ds.Tables["MyImage"].Rows[0];
photo_array = (byte[])myRow["Logo"];
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
con.Close();
}
void retriveData()
{
con.Open();
cmd = new SqlCommand("Select * from Register where UserName='"+uNameTxt.Text+"'",con);
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
nameTxt.Text = (read["Name"].ToString());
passTxt.Text = (read["Password"].ToString());
conPassTxt.Text = (read["Password"].ToString());
emailTxt.Text = (read["EmailId"].ToString());
addTxt.Text = (read["Address"].ToString());
contTxt.Text = (read["ContactNo"].ToString());
DORTxt.Text = (read["DOR"].ToString());
validity.Text = "Account Valid till "+(read["Validity"].ToString());
}
read.Close();
con.Close();
}
private void AttachBtn_Click(object sender, EventArgs e)
{
// Open image by OpenFiledialog and show it in PicturBox.
try
{
//filter only image format files.
openFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
DialogResult res = openFileDialog1.ShowDialog();
if (res == DialogResult.OK)
{
Image img = new Bitmap(openFileDialog1.FileName);
//inserting image in PicturBox
profPic.Image = img.GetThumbnailImage(127, 128, null, new IntPtr());
openFileDialog1.RestoreDirectory = true;
}
}
catch
{
MessageBox.Show("Cannot upload image");
}
}
private void UpdateBtn_Click_1(object sender, EventArgs e)
{
string DOM = dateTimePicker1.Value.ToShortDateString();
if (namewarning.Visible == true || picError.Visible == true || PassError.Visible == true || emailwarningImg.Visible == true)
{
MessageBox.Show("Please correct the marked fields");
}
else
{
//cmd = new SqlCommand("update Register set (Name,Password,EmailId,Address,ContactNo,Logo,DOM) values('" + nameTxt.Text.Trim() + "','" + passTxt.Text.Trim() + "','" + emailTxt.Text.Trim() + "','" + addTxt.Text.Trim() + "','" + contTxt.Text.Trim() + "',#Logo,'" + DOM+ "')", con);
str = string.Format("update Register set Name='{0}', Password='{1}',EmailID='{2}',Address='{3}',ContactNo='{4}',Logo='{5}',DOU='{6}' where UserName='{7}'", nameTxt.Text.Trim(), passTxt.Text.Trim(), emailTxt.Text.Trim(),addTxt.Text.Trim(), contTxt.Text.Trim(), #"Logo" ,DOM,uNameTxt.Text);
con_photo();
//con.Open();
cmd = new SqlCommand(str, con);
int count= cmd.ExecuteNonQuery();
if (count > 0)
MessageBox.Show("Sucsess");
else
MessageBox.Show("need to work");
}
}
void con_photo()
{
if (profPic.Image != null)
{
ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_array = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_array, 0, photo_array.Length);
cmd.Parameters.AddWithValue("#Logo", photo_array);
}
}
when i run the application it executes very well and shows me success message but when i again try to view the update user form it shows below screenshot error
http://i.stack.imgur.com/7z1Rx.png
at retriveImg ()
Please help me with resolution for this..
You're not passing the image bytes to the UPDATE command, but a string containing the word Logo.
Also: PLEASE avoid creating SQL commands using string concatenation or String.Format. Use parameterized queries instead!
Also: Do not use an NVARCHAR field to store the image bytes (unless you create a BASE64 string from them first), but use a VARBINARY or IMAGE column instead.
The problem is in the following line:
str = string.Format("update Register set ... ,Logo='{5}' ...", ..., #"Logo", ...);
As you can see, you're formatting a string, but you don't insert the bytes from the image, but the word "Logo".
Assuming the column Logo was of type IMAGE or VARBINARY, I would write something like this:
byte[] photo_array = null;
if (profPic.Image != null)
{
MemoryStream ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
photo_array = ms.GetBuffer();
}
if (photo_array != null)
{
SqlCommand cmd = new SqlCommand("UPDATE Register SET Logo=#logo", connection);
cmd.Parameters.AddWithValue("#logo", imageBytes);
cmd.ExecuteNonQuery();
}
Maybe I'm wrong but I'll try to do this
photo_array = (byte[])myRow["Logo"];
if photo_array.length.trim()>0
{
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
}
con.Close();
This error may come when the lenght of the string is 0
Another thing is that you're not saving the image in the database
//C# Code
SqlCommand cmdSelect = new SqlCommand("select ImageValue from table where ID=1", ObjCon);
ObjCon.Open();
byte[] barrImg = (byte[])cmdSelect.ExecuteScalar();
ObjCon.Close();
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream("C:\\Temp\\1.txt", FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg, 0, barrImg.Length);
fs.Flush();
fs.Close();
// 1.txt file will be created in c:\temp folder
I am developing this simple application to upload an Excel file (.xlsx) and import the data present in that Excel worksheet into a SQL Server Express database in .NET
I'm using the following code on click of the import button after browsing and selecting the file to do it.
protected void Button1_Click(object sender, EventArgs e)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
//file upload path
string path = FileUpload1.PostedFile.FileName;
//string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
But the code doesn't run when I use
string path = FileUpload1.PostedFile.FileName;`
and even
string path="C:\ Users\ Hemant\Documents\example.xlsx";`
The dReader is unable to take the path in this format.
It is only able to take path in the following format
string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
i.e. with the the \\ in the path.For which I have to hard code the path but we have to browse the file.
So,can any one please suggest a solution to use the path taken by the FileUpload1 to import the data?
You are dealing with a HttpPostedFile; this is the file that is "uploaded" to the web server. You really need to save that file somewhere and then use it, because...
...in your instance, it just so happens to be that you are hosting your website on the same machine the file resides, so the path is accessible. As soon as you deploy your site to a different machine, your code isn't going to work.
Break this down into two steps:
1) Save the file somewhere - it's very common to see this:
string saveFolder = #"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
Now you have your file locally and the real work can be done.
2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:
string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
You can then think about deleting the file you've just uploaded and imported.
To provide a more concrete example, we can refactor your code into two methods:
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
You could simply then call SaveFileToDatabase(GetLocalFilePath(#"C:\temp\uploads", FileUpload1));
Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!
Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!
Not sure why the file path is not working, I have some similar code that works fine.
But if with two "\" it works, you can always do path = path.Replace(#"\", #"\\");
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy import excel file to sql server database using SqlBulkCopy. It uses small memory because it reads by SAX(Simple API for XML) method (OpenXmlReader)
Example:
private static void DataReaderBulkCopySample()
{
using (var reader = new ExcelDataReader(#"test.xlsx"))
{
var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();
DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols);
using (var bulkCopy = new SqlBulkCopy(ConnectionString))
{
// MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess,
// optimizing memory usage by using the IDataReader streaming capabilities
bulkCopy.EnableStreaming = true;
bulkCopy.DestinationTableName = TableName;
foreach (var col in cols)
bulkCopy.ColumnMappings.Add(col, col);
bulkCopy.WriteToServer(reader);
}
}
}
Try Using
string filename = Path.GetFileName(FileUploadControl.FileName);
Then Save the file at specified location using:
FileUploadControl.PostedFile.SaveAs(strpath + filename);
public async Task<HttpResponseMessage> PostFormDataAsync() //async is used for defining an asynchronous method
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var fileLocation = "";
string root = HttpContext.Current.Server.MapPath("~/App_Data");
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root); //Helps in HTML file uploads to write data to File Stream
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name
var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path
File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it
fileLocation = file.LocalFileName + filePath; //Complete file location
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus);
return response;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public void ReadFromExcel()
{
try
{
DataTable sheet1 = new DataTable();
OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
csbuilder.DataSource = fileLocation;
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
string selectSql = #"SELECT * FROM [Sheet1$]";
using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
{
connection.Open();
adapter.Fill(sheet1);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
A proposed solution will be:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
CreateXMLFile();
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand("bulk_in", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#account_det", sw_XmlString.ToString ());
int i= cmd.ExecuteNonQuery();
if(i>0)
{
Label1.Text = "File Upload successfully";
}
else
{
Label1.Text = "File Upload unsuccessfully";
return;
}
con.Close();
}
catch(SqlException ex)
{
Label1.Text = ex.Message.ToString();
}
}
public void CreateXMLFile()
{
try
{
M_Filepath = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
fileExtn = Path.GetExtension(M_Filepath);
strGuid = System.Guid.NewGuid().ToString();
fNameArray = M_Filepath.Split('.');
fName = fNameArray[0];
xlRptName = fName + "_" + strGuid + "_" + DateTime.Now.ToShortDateString ().Replace ('/','-');
fileName = xlRptName.Trim() + fileExtn.Trim() ;
FileUpload1.PostedFile.SaveAs(ConfigurationManager.AppSettings["ImportFilePath"]+ fileName);
strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToUpper() ;
if (((strFileName) != "DEMO.XLS") && ((strFileName) != "DEMO.XLSX"))
{
Label1.Text = "Excel File Must be DEMO.XLS or DEMO.XLSX";
}
FileUpload1.PostedFile.SaveAs(System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName);
lstrFilePath = System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName;
if (strFileName == "DEMO.XLS")
{
strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
}
if (strFileName == "DEMO.XLSX")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;'";
}
strSQL = " Select [Name],[Mobile_num],[Account_number],[Amount],[date_a2] FROM [Sheet1$]";
OleDbDataAdapter mydata = new OleDbDataAdapter(strSQL, strConn);
mydata.TableMappings.Add("Table", "arul");
mydata.Fill(dsExcl);
dsExcl.DataSetName = "DocumentElement";
intRowCnt = dsExcl.Tables[0].Rows.Count;
intColCnt = dsExcl.Tables[0].Rows.Count;
if(intRowCnt <1)
{
Label1.Text = "No records in Excel File";
return;
}
if (dsExcl==null)
{
}
else
if(dsExcl.Tables[0].Rows.Count >= 1000 )
{
Label1.Text = "Excel data must be in less than 1000 ";
}
for (intCtr = 0; intCtr <= dsExcl.Tables[0].Rows.Count - 1; intCtr++)
{
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Name"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Name"].ToString();
}
if (strValid == "")
{
Label1.Text = "Name should not be empty";
return;
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Mobile_num"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Mobile_num"].ToString();
}
if (strValid == "")
{
Label1.Text = "Mobile_num should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Account_number"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Account_number"].ToString();
}
if (strValid == "")
{
Label1.Text = "Account_number should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Amount"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Amount"].ToString();
}
if (strValid == "")
{
Label1.Text = "Amount should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["date_a2"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["date_a2"].ToString();
}
if (strValid == "")
{
Label1.Text = "date_a2 should not be empty";
}
else
{
strValid = "";
}
}
}
catch
{
}
try
{
if(dsExcl.Tables[0].Rows.Count >0)
{
dr = dsExcl.Tables[0].Rows[0];
}
dsExcl.Tables[0].TableName = "arul";
dsExcl.WriteXml(sw_XmlString, XmlWriteMode.IgnoreSchema);
}
catch
{
}
}`enter code here`
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
//Upload and save the file
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Table1";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Sl", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
Copy this in web config
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html
protected void btnUpload_Click(object sender, EventArgs e)
{
divStatusMsg.Style.Add("display", "none");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "";
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "DateExcel" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/DateExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/DateExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
if ((grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE") && grdExcel.HeaderRow.Cells[1].Text.ToString() == "SAL")
{
GetExcelSheetForEmployeeCode(PathName);
}
else
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Upload Excel Sheet in header Defined Format ";
}
}
}
}
private void GetExcelSheetForEmployeeCode(string filename)
{
int count = 0;
int selectedcheckbox = 0;
string empcodeexcel = "";
string empcodegrid = "";
string excelFile = "Employee/DateExcel" + filename;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet ds = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + filename;
// Create connection.
objConn = new OleDbConnection(connString);
// Opens connection with the database.
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
// Get the data table containing the schema guid, and also sheet names.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
// And respective data will be put into dataset table
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(ds, "TABLE");
if (ds.Tables[0].ToString() != null)
{
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
for (int k = 0; k < GrdEmplist.Rows.Count; k++)
{
empcodeexcel = ds.Tables[0].Rows[j][0].ToString();
date.Value = ds.Tables[0].Rows[j][1].ToString();
Label lbl_EmpCode = (Label)GrdEmplist.Rows[k].FindControl("lblGrdCode");
empcodegrid = lbl_Code.Text;
CheckBox chk = (CheckBox)GrdEmplist.Rows[k].FindControl("chkSingle");
TextBox txt_Sal = (TextBox)GrdEmplist.Rows[k].FindControl("txtSal");
if ((empcodegrid == empcodeexcel) && (date.Value != ""))
{
chk.Checked = true;
txt_Sal.Text = date.Value;
selectedcheckbox = selectedcheckbox + 1;
lblSelectedRecord.InnerText = selectedcheckbox.ToString();
count++;
}
if (chk.Checked == true)
{
}
}
}
}
}
i++;
}
}
catch (Exception ex)
{
ShowMessage(ex.Message.ToString(), 0);
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "DateExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdExcel.DataSource = dss.Tables[0].DefaultView;
grdExcel.DataBind();
lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "Emp" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/EmpExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/EmpExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "EmpExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdByExcel.DataSource = dss.Tables[0].DefaultView;
grdByExcel.DataBind();
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdByExcel.DataSource = null;
grdByExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}