Excel Upload in asp.net - asp.net

I am uploading excel in asp.net. but one column not read .
protected void btnUpload_Click(object sender, EventArgs e)
{
SqlConnection myconn = new SqlConnection(sqlConnectionString);
if (FileUpload1.HasFile)
{
string paramExcelSheetName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.Equals(Server.MapPath("~/UploadExcel/" + paramExcelSheetName));
string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
string path = string.Concat(Server.MapPath("~/UploadExcel/" + FileUpload1.FileName));
if (File.Exists(path))
{
File.Delete(path);
}
if (strFileType.Trim() == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Persist Security Info=False;Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
FileUpload1.SaveAs(path);
OleDbConnection conn = new OleDbConnection(excelConnectionString);
query = "SELECT * FROM [Sheet1$] ";
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataReader oledbdr = cmd.ExecuteReader();
#region readline by line
if (oledbdr.HasRows)
{
while (oledbdr.Read())
{
if (!oledbdr.IsDBNull(0))
{
if (!oledbdr.IsDBNull(0))
{
sr =Convert.ToInt32( oledbdr["SrNo"].ToString());
}
else
{
}
if (!oledbdr.IsDBNull(0))
{
certificate = oledbdr["CertificateNo"].ToString();
}
else
{
}
if (!oledbdr.IsDBNull(0))
{
cr = oledbdr["CR"].ToString();
}
else
{
}
//if (!oledbdr.IsDBNull(0))
//{
// cr = oledbdr["Pass"].ToString();
//}
//else
//{
//}
#region
SqlCommand myCommand = new SqlCommand("INSERT INTO test1 (SrNo,CertificateNo,CR) VALUES('" + sr + "','" +certificate+ "','" + cr + "')", myconn);
try
{
myconn.Open();
myCommand.ExecuteNonQuery();
myconn.Close();
}
catch (Exception ex)
{
myconn.Close();
}
#endregion
}
}
}
#endregion
conn.Close();
}
}
one column certificate not read certificate value like 737737373737/En2

try this code.
query = "SELECT SrNo,CertificateNo,CR FROM [Sheet1$] ";
FileUpload1.SaveAs(Server.MapPath("~/uploadmedicine/") + FileUpload1.FileName);
if (FileUpload1.PostedFile != null)
{
string path = FileUpload1.PostedFile.FileName;
string connectString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/uploadmedicine/") + FileUpload1.FileName + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("SELECT SrNo,CertificateNo,CR from [Sheet1$]", conn);
}

Related

Adding an ImageUrl to an ImageControl

I need help how to add an ImageUrl to an ImageControl programmatically. I got this code, but I can't (I don't know how) add path that is stored in database.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//images//" + str);
string path = "~//images//" + str.ToString();
con.Open();
SqlCommand cmd = new SqlCommand("insert into upload values('" + TextBox1.Text + "','" + path + "')", con);
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image uploaded";
SqlDataAdapter da = new SqlDataAdapter("Select img from upload", con);
DataTable dt = new DataTable();
da.Fill(dt);
Image1.ImageUrl =
}
else
{
Label1.Text = "Please select image";
}
}
For that particular scenario, you already have an image filename and path. All you need is Image1.ImageUrl = ResolveUrl("~/images/" + fileName);.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;
string path = string.Format("{0}\\images\\{1}",
HttpRuntime.AppDomainAppPath, fileName);
FileUpload1.PostedFile.SaveAs(path);
/* Save image information to database */
Image1.ImageUrl = ResolveUrl("~/images/" + fileName);
}
else
{
Label1.Text = "Please select image";
}
}
FYI: Your code is prone to SQL Injection attack. Make sure you use Parameterized Query.

The type or namespace GlobalVar could not be found

Please dear this is my code and everything is fine but the GlobalVar is not being declared any suggestions.
[WebMethod(MessageName = "OpenAccount", Description = "This method is to add new account")]
[System.Xml.Serialization.XmlInclude(typeof(ContactResult))]
public ContactResult openaccount(String FullName, String Phone)
{
ContactResult cr = new ContactResult();
**GlobalVar var = new GlobalVar();**
try
{
using (SqlConnection openconn = new SqlConnection(var.connectionstring))
{
string save = "INSERT into AndroidContact (AndroidContactName,AndroidContactPhone) VALUES ('" + FullName + "' ,'" + Phone + "')";
using (SqlCommand query = new SqlCommand(save))
{
query.Connection = openconn;
query.Parameters.Add("#AndroidContactName", SqlDbType.NVarChar, 50).Value = FullName;
query.Parameters.Add("#AndroidContactPhone", SqlDbType.NVarChar, 50).Value = Phone;
openconn.Open();
query.ExecuteNonQuery();
openconn.Close();
}
}
cr.ErrorID = 0;
cr.ErrorMessage = "Contact Added";
return cr;
}
catch (Exception ex){
cr.ErrorID = 1;
cr.ErrorMessage = ex.Message;
return cr;
}
}
}
}
Thanks, but i fixed mine like that :
public class WebService1 : System.Web.Services.WebService
{
[WebMethod(MessageName = "OpenAccount", Description = "This method is to add new account")]
[System.Xml.Serialization.XmlInclude(typeof(ContactResult))]
public ContactResult openaccount(String FullName, String Phone)
{
ContactResult cr = new ContactResult();
SqlConnection Connection = new SqlConnection();
try
{
Connection.ConnectionString = ConfigurationManager.ConnectionStrings["webConnectionString"].ToString();
Connection.Open();
SqlCommand save = new SqlCommand ("INSERT into AndroidContact (AndroidContactName,AndroidContactPhone) VALUES ('" + FullName + "' ,'" + Phone + "')",Connection);
save.ExecuteNonQuery();
cr.ErrorID = 0;
cr.ErrorMessage = "Contact Added";
return cr;
}
catch (Exception ex)
{
cr.ErrorID = 1;
cr.ErrorMessage = ex.Message;
return cr;
}
}
}

the table is not updated, it only does "insert" to the text i put in the textbox

The table is not updated, it only does "insert" to the text I put in the textbox. Can someone tell me what's wrong? Here is my code:
protected void update_b_Click(object sender, EventArgs e)
{
//Update employee details
try
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update employees set Emp_number='" + emp_num.Text + "',First_name='" + emp_fname.Text + "', Last_name='" + emp_lname.Text + "',Phone_num='" + emp_phone.Text + "',Email='" + emp_email.Text + "'where Emp_number='" + emp_num.Text + "'";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("employee details updated successfuly");
emp_num.Text = "";
emp_fname.Text = "";
emp_lname.Text = "";
emp_phone.Text = "";
emp_email.Text = "";
Bind1();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Check Email is register or not while register in Asp.net c#?

I am trying to check whilist registrating. When an enterd email exists and then try to register it untill the registration is successfull but I don't want that.
protected void btnRegister_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand ("Select count(*) from tblUsers where Email = '" + txtEmail.Text + "' ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
p.UserName = txtUsername.Text;
p.Email = txtEmail.Text;
p.DOB = Convert.ToDateTime(txtDob.Text);
p.Password = txtPass.Text;
p.InsertUser(p);
Response.Write("Registration Successfull..");
}
else {
Response.Write("This Email is Already Exist...!!");
}
}
else
{
Response.Write("Fail...");
}
}

Why isn't my database logic throwing an exception when I enter data that already exists?

I have a small ASP.NET registration page linked to a database. If the user enters the username that already exists in the database, then it should display "user already exists", but it is not doing that:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists!!");
}
conn.Close();
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Country and age!");
}
else if(this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue != "-Select-")
{
Response.Write("Select Country!");
}
else if (this.DropDownListCountry.SelectedValue != "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Age!");
}
else
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}
}
}
}
I think you should try first
If ( temp > 0)
{
}
also debug to see what is returned by the sql query
Few Things.
You need to check this before inserting the data.
You are not preventing entering the same data if the username still exists
You can check top 1 instead of count.
private bool IsUserExists()
{
bool UserExists = false;
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp >= 1)
{
UserExists = true;
Response.Write("User already exists!!");
}
conn.Close();
}
return UserExists ;
}
Check this before inserting the data.
try
{
if(UserExists())
return; //Skips further code when user exists.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}

Resources