How to send uploaded Image as parameter in c# to sql - c#

Here is my code. Error message was
parameter #event_image was not supplied
How to send image name as parameter? If I keep breakpoint it's not even entering into If(fileupload1.HasFile).
I have to store the image in folder and the path must be stored into sql db
{
conn.Open();
string postdate = txtpostdate.Text;
string unpostdate = txtunpostdate.Text;
string name = txtname.Text;
string description = txtdescription.Text;
string country = dropcountry.SelectedItem.ToString();
string multidate = txtstartdae.Text;
string startend = dropstarttime.SelectedItem.ToString();
string drop1m = dropti1m.SelectedItem.ToString();
string dropme1h = droptimeend1h.SelectedItem.ToString();
string drop2m = droptime2m.SelectedItem.ToString();
string notes = txtnotes.Text;
string prevlocation = droplocation.SelectedItem.ToString();
string locationname = txtslocname.Text;
string addres1 = txtsLocAddress1.Text;
string addres2 = txtsLocAddress2.Text;
string city = txtsLocCity.Text;
string state = dropstate.SelectedItem.ToString();
string zipcode = txtsLocZip.Text;
string phonenumber = txtsLocPhone.Text;
string faxnumber = txtsLocFax.Text;
string notes2 = textnotes2.Text;
SqlCommand cmd = new SqlCommand("InsertEvents", conn);
cmd.CommandType = CommandType.StoredProcedure;
//SqlCommand cmd = new SqlCommand("insert into pa_events(event_postdate,event_unpostdate,event_canvisitorsregisters,event_eventname,event_description,event_image,event_multydateevent,event_startdate,event_enddate,event_start,event_end,event_notes,location_name,location_addres1,location_addres2,location_cites,location_state,location_zipcode,location_phonenumber,location_faxnumber,location_notes,event_country) values(#event_postdate,#event_unpostdate,#event_canvisitorsregisters,#event_eventname,#event_description,#event_image,#event_multydateevent,#event_startdate,#event_enddate,#event_start,#event_end,#event_notes,#location_name,#location_addres1,#location_addres2,#location_cites,#location_state,#location_zipcode,#location_phonenumber,#location_faxnumber,#location_notes,#event_country)", conn);
if (fileupload1.HasFile)
{
imagename = fileupload1.FileName;
int length = fileupload1.PostedFile.ContentLength;
fileupload1.SaveAs(Server.MapPath("~\\images\\" + imagename));
s = "~\\images\\" + imagename + "";
}
if (radioyes.Checked == false && !radiono.Checked == false)
{
lblmsg.Text = "Please Select canve Register Yes! or No!";
}
if (radioyes.Checked == true)
{
cmd.Parameters.AddWithValue("#event_canvisitorsregisters", SqlDbType.VarChar).Value = "Y";
}
else
{
cmd.Parameters.AddWithValue("#event_canvisitorsregisters", SqlDbType.VarChar).Value = "N";
}
if (radiomultyyes.Checked == true)
{
cmd.Parameters.AddWithValue("#event_multydateevent", SqlDbType.VarChar).Value = "Y";
}
else
{
cmd.Parameters.AddWithValue("#event_multydateevent", SqlDbType.VarChar).Value = "N";
}
**cmd.Parameters.AddWithValue("#event_image", s);**
cmd.Parameters.AddWithValue("#event_postdate", postdate);
cmd.Parameters.AddWithValue("#event_unpostdate", unpostdate);
cmd.Parameters.AddWithValue("#event_eventname", name);
cmd.Parameters.AddWithValue("#event_description", description);
cmd.Parameters.AddWithValue("#event_country", country);
cmd.Parameters.AddWithValue("#event_startdate", startend);
cmd.Parameters.AddWithValue("#event_enddate", drop1m);
cmd.Parameters.AddWithValue("#event_start", dropme1h);
cmd.Parameters.AddWithValue("#event_end", drop2m);
cmd.Parameters.AddWithValue("#event_notes", notes);
cmd.Parameters.AddWithValue("#location_name", locationname);
cmd.Parameters.AddWithValue("#location_addres1", addres1);
cmd.Parameters.AddWithValue("#location_addres2", addres2);
cmd.Parameters.AddWithValue("#location_cites", city);
cmd.Parameters.AddWithValue("#location_state", state);
cmd.Parameters.AddWithValue("#location_zipcode", zipcode);
cmd.Parameters.AddWithValue("#location_phonenumber", phonenumber);
cmd.Parameters.AddWithValue("#location_faxnumber", faxnumber);
cmd.Parameters.AddWithValue("#location_notes", notes2);
//if (fileupload1.PostedFile != null && fileupload1.PostedFile.FileName != "")
//
int i = cmd.ExecuteNonQuery();
if (i != 0)
{
lblmsg.Text = "record is inserted";
}
else
{
lblmsg.Text = "record is not inserted";
}
conn.Close();
}

The error isn't with your SQL insert, it's with however your file upload is set up. You're getting that error because, as you stated, you're not even entering the if statement that creates the SQL parameter.
Could you post code related to the image upload? That's your root issue.

honestly your code is not clear but hope it works with you:
add parameter with file upload
if (fileupload1.HasFile)
{
imagename = fileupload1.FileName;
int length = fileupload1.PostedFile.ContentLength;
fileupload1.SaveAs(Server.MapPath("~\\images\\" + imagename));
s = "~\\images\\" + imagename + "";
cmd.Parameters.AddWithValue("#event_image", s);
}

Related

Stop Upload when a some data already exists

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();

Save picture into specific row in database MySQL using C#

I have project from my lecture to make application that save biodata (Student ID, Name, Departement, etc.) into database. And also I want to save picture profile into database MySQL.
Here's the function to save all data (except picture):
public bool isSignUp (String nim, String nama, String jenisKelamin, String prodi, String angkatan, String pass, String verifPass )
{
if (nim==null || nama==null || jenisKelamin==null || prodi==null || angkatan==null
|| pass==null || verifPass==null)
{
return false;
}
else if(pass.Equals(verifPass)==false)
{
return false;
}
else
{
String query = "insert into dbmahasiswa VALUES (#NIM, #Nama, #JenisKelamin, #ProgramStudi, #Angkatan, #Password)";
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(query, connect);
cmd.Parameters.AddWithValue("#NIM", nim);
cmd.Parameters.AddWithValue("#Nama", nama);
cmd.Parameters.AddWithValue("#JenisKelamin", jenisKelamin);
cmd.Parameters.AddWithValue("#ProgramStudi", prodi);
cmd.Parameters.AddWithValue("#Angkatan", angkatan);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Warning");
return false;
}
finally
{
connect.Close();
}
return true;
}
}
How to add function to insert picture (that will be profile picture) in this method?
Something like:
string filename = Path.GetFileName(imageToSave.FileName);
string fileExtension = Path.GetExtension(filename);
int fileSize = imageToSave.ContentLength;
if (fileExtension.ToLower() == ".jpg" ) /*you could add a check for what type of image you want to be allowed to save*/
{
Stream stream = postedFile.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
Byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
SqlParameter paramImageData = new SqlParameter()
{
ParameterName = "#ImageData",
Value = bytes
};
cmd.ExecuteNonQuery();
}

Importing data from excelsheet file into the mysql database C#

I have the following lines of code:
protected void btnUpload_Click(object sender, EventArgs e)
{
MySqlTransaction transaction;
string ex_id = "";
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();//just added
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if (dtExceldata.Rows.Count > 0)
{
//foreach (DataRow row in dtExceldata.Rows)
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
//string ex_dir = row["website_a"].ToString();
string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
// string ex_email = row["email_id"].ToString();
string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
//string ex_email1 = row["email_id2"].ToString();
string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
//string ex_email2 = row["email_id3"].ToString();
string ex_company = dtExceldata.Rows[i]["company"].ToString();
//string ex_company = row["company"].ToString();
string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
//string ex_contact = row["contact_name"].ToString();
string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
// string ex_proposal = row["proposal_status"].ToString();
string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
//string ex_reason = row["reason"].ToString();
int chk = 0;
int type = 0;
int dup = 0;
int dir = 0;
if (ddlwebsites.SelectedIndex != 0)
{
dir = Convert.ToInt32(ddlwebsites.SelectedValue);
if (dir == 8)
{
type = 1;
}
}
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
chk = 1;
}
}
if (type == 1 && chk == 0)
{
evyerror.Text = "Please Select the Event!!";
return;
}
else
{
string querycomp = "", compID = "";
querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr);
connect.Open();
transaction = connect.BeginTransaction();
try
{
ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
DataTable dt = clsDtResult.GetDataTable(querycomp);
if (dt.Rows.Count > 0)
{
compID = dt.Rows[0]["comp_id"].ToString();
ViewState["comp_id"] = compID;
if (type == 1)
{
dup = checkforDuplicates(Convert.ToInt32(compID));
if (dup == 1)
{
//Confirm_MP.Show();
// ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
}
}
//return;
}
else
{
string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?website", ex_dir);
cmd.ExecuteNonQuery();
cmd.CommandText = "Select LAST_INSERT_ID()";
compID = cmd.ExecuteScalar().ToString();
transaction.Commit();
connect.Close();
}
}
catch
{
transaction.Rollback();
}
if (dup == 0)
{
// create a connection string with your sql database
string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr1);
connect.Open();
DateTime date = new DateTime();
date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
//DateTime date = new DateTime();
//if (!string.IsNullOrEmpty(ex_date))
// {
//DateTime date = new DateTime();//added by chetan
//ex_date = ex_date.Split(' ')[0];//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
//string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
//DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
//// DateTime date = DateTime.Parse(ex_date);//added by chetan
// }
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
// string SentDateString = date.ToString("yyyy/MM/dd");
transaction = connect.BeginTransaction();
try
{
string ex_uid = Session["session_barterUser_id"].ToString();
MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);
cmd.Parameters.AddWithValue("?uid", ex_uid);
cmd.Parameters.AddWithValue("?comp", compID);
cmd.Parameters.AddWithValue("?sentdate", SentDateString);
// command.Parameters.AddWithValue("?event", eventname);
cmd.Parameters.AddWithValue("?dir", dir);
// command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
// command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
//cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?cont_name", ex_contact);
cmd.Parameters.AddWithValue("?email", ex_email);
cmd.Parameters.AddWithValue("?email2", ex_email1);
cmd.Parameters.AddWithValue("?email3", ex_email2);
cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
cmd.Parameters.AddWithValue("?reason", ex_reason);
cmd.Parameters.AddWithValue("?type", type);
// command.Parameters.AddWithValue("?type", type);
cmd.ExecuteNonQuery();
if (type == 1)
{
cmd.CommandText = "Select LAST_INSERT_ID()";
Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
int eventAssignID;
string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
eventAssignID = Convert.ToInt32(lstAssign.Value);
cmd.Parameters.AddWithValue("?event_id", eventAssignID);
cmd.ExecuteNonQuery();
}
}
}//end of if
transaction.Commit();
connect.Close();
Response.Write("<script type=\"text/javascript\">alert('Proposal Added Successfully!!!');</script>");
}//end of try
catch (Exception ex)
{
transaction.Rollback();
Response.Write("<script>alert('There is an Error Ocurred:" + Server.HtmlEncode(ex.Message) + "')</script>");
}
finally
{
connect.Close();
}
}//ifdupzero
}//else
}//for//foreach
}//while //if
// dr.Close();//commented by chetan
my_con.Close();
if (System.IO.File.Exists(Excel_path))
{
System.IO.File.Delete(Excel_path);
}
}
suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.
Instead of checking if there are rows left (dr.Read()) as your loop condition, you could check if the first cell of the row is blank (dr[0].ToString() != String.Empty)
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", my_con);
OleDbDataReader dr = command.ExecuteReader();
dr.Read();
while (dr[0].ToString() != String.Empty)
{
ex_id = dr[0].ToString();
string ex_uid = dr[1].ToString();
//get second row data and assign it ex_name variable
string ex_date = dr[2].ToString();
//get thirdt row data and assign it ex_name variable
string ex_dir = dr[3].ToString();
//get first row data and assign it ex_location variable
string ex_email = dr[4].ToString();
string ex_email1 = dr[5].ToString();
string ex_email2 = dr[6].ToString();
//string ex_company = dr[7].ToString();
string ex_company = dr[7].ToString();
string ex_contact = dr[8].ToString();
string ex_proposal = dr[9].ToString();
string ex_reason = dr[10].ToString();
...............
//Insert operation
...............
dr.Read();
}
dr.close();
my_con.close();
The premise of course is, that the first column is always filled if the rest of the row isn't blank.
If that isn't the case you can also check other columns in the loop condition.
there is various way of doing that
you can load excel data to datatable and then you can for loop for each row with perticular column name like this
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended
Properties=Excel 8.0;Persist Security Info=False");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if(dtExceldata.Rows.Count>0)
{
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}
see this excel file
and the datatable in c#
this loop will repeat for only number of row in datatable then also i practically tried this and it only loop for number of row (e.g two times) but i found a bug that if you will enter two row then five blank row then some data it will give you blank value in data table check your excel file there may some blank value as shown in attechment
then also you can skip blank value by checking null value in row like this
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
if (!String.IsNullOrEmpty(Convert.ToString(dtExceldata.Rows[i]["fieldvalues"])))
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}

Not able to insert. Doesn't show any errors but doesn't insert as well

This is my insert statement. Records are not inserting but no errors showing also. Please help
protected void btn_Add_Click(object sender, EventArgs e)
{
if (btn_Add.Text == "Submit")
{
string Height = txtHeight.Text;
string TopDia = Convert.ToString(txtTopDiaMeter.Text);
string BottomDia = Convert.ToString(txtBottomDiaMeter.Text);
string ShaftThick = Convert.ToString(txtShaftThick.Text);
string BlackWt = Convert.ToString(txtBlackWeight.Text);
string TotManHrPerPole = Convert.ToString(txtTotManHrPoleData.Text);
string Plate_Length = Convert.ToString(txtPlateLength.Text);
string PLATE_DIA = Convert.ToString(txtPlateDia.Text);
string PLATE_THICKNESS = Convert.ToString(txtPlateThick.Text);
System.Collections.Hashtable ht = (System.Collections.Hashtable)Session["UserDetails"];
Int64 UsrId = (Int64)ht["UserID"];
string CreatedBy = Convert.ToString(UsrId);
string FoundBoltId = Convert.ToString(ddlFoundationBolt.SelectedValue);
string PoleTypeId = Convert.ToString(ddlPoltype.SelectedValue);
string ProductTypeID = Convert.ToString(ddlPdtType.SelectedValue);
string Status = chkActive.Checked ? "True" : "False";
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
fileuploadimages.SaveAs(Server.MapPath("~/Images/Pole Data/" + filename));
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["valmont"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("Insert into DEF_POLE_DATA_MST(Height,TopDia,BottomDia,ShaftThick,BlackWt,TotManHrPerPole,Plate_Length,PLATE_DIA,PLATE_THICKNESS,CreatedBy,FoundBoltId,PoleTypeID,ProductTypeID,Status,ImagePath) values(#Height,#TopDia,#BottomDia,#ShaftThick,#BlackWt,#TotManHrPerPole,#Plate_Length,#PLATE_DIA,#PLATE_THICKNESS,#CreatedBy,#FoundBoltId,#PoleTypeId,#ProductTypeID,#Status,#ImagePath)", con);
cmd.Parameters.AddWithValue("#Height", Height);
cmd.Parameters.AddWithValue("#TopDia", TopDia);
cmd.Parameters.AddWithValue("#BottomDia", BottomDia);
cmd.Parameters.AddWithValue("#ShaftThick", ShaftThick);
cmd.Parameters.AddWithValue("#BlackWt", BlackWt);
cmd.Parameters.AddWithValue("#TotManHrPerPole", TotManHrPerPole);
cmd.Parameters.AddWithValue("#Plate_Length", Plate_Length);
cmd.Parameters.AddWithValue("#PLATE_DIA", PLATE_DIA);
cmd.Parameters.AddWithValue("#PLATE_THICKNESS", PLATE_THICKNESS);
cmd.Parameters.AddWithValue("#CreatedBy", CreatedBy);
cmd.Parameters.AddWithValue("#FoundBoltId", FoundBoltId);
cmd.Parameters.AddWithValue("#PoleTypeId", PoleTypeId);
cmd.Parameters.AddWithValue("#ProductTypeID", ProductTypeID);
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#ImagePath", "~/Images/Pole Data/" + filename);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
Accordian.SelectedIndex = 1;
JQUERYDisplay.ShowAlertMessage("Record Inserted Successfully");
CleraFields();
}
catch (Exception ex)
{
JQUERYDisplay.ShowAlertMessage(ex.Message);
}
finally
{
}
}
Here's the table:

Getting data from database to textbox?

i have this code, but it doesn't work
try
{
con.Open();
using (SqlCommand command = new SqlCommand("select nev, telefonszam, felhasznalonev, lakcim,email from Felhasznalo where felhasznalonev='"+cbUsername.Text+"' ", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string name = reader.GetString(0);
string phone = reader.GetInt32(1).ToString();
string username = reader.GetString(2);
string address = reader.GetString(3);
string email = reader.GetString(4);
tbUsername.Text = username;
tbName.Text = name;
//tbPhoneNumber.Text = phoneNumber.ToString();
tbAddress.Text = address;
tbEmail.Text = email;
}
}
}
catch (Exception ex)
{
MessageBox.Show(""+ex);
}
finally
{
con.Close();
}
the error is: Specified cast is not valid.
What is wrong?
i got the solution from here:https://www.youtube.com/watch?v=sKealDA-Wr8
I would suggest that you do this for all the fields that you are returning.
string phone = (string)reader["telefonszam"].ToString();
What if the Database structure changes or you add new columns and change the index / order.. using GetString(4) for example would be fail if the datatype in that column position were to change that is why I recommended that you use the actual column names.

Categories