I am working on a school project and for some reason my mysql database doesn't update despite no of row changed is more than 0 and triggering the Update sucessful alert. It also manage to only update my image data from my fileupload.
**admin_products_details_edit.aspx.cs**
protected void btn_ProdEdit_Click(object sender, EventArgs e)
{
int result = 0;
string image = "";
if (FileUpload_ProdImg.HasFile == true)
{
image = "images\\" + FileUpload_ProdImg.FileName;
img_result.ImageUrl = FileUpload_ProdImg.FileName;
}
else
{
image = img_result.ImageUrl;
}
Product Prod = new Product();
string datProdID = lbl_ProdID.Text;
string datProdName = tb_ProdName.Text;
string datProdDesc = tb_ProdDesc.Text;
string datProdImg = img_result.ImageUrl;
decimal datProdPrice = decimal.Parse(tb_ProdPrice.Text);
int datProdCal = int.Parse(tb_ProdCal.Text);
int datStockLvl = int.Parse(tb_StockLvl.Text);
result = Prod.ProductUpdate(datProdID, datProdName, datProdDesc, datProdImg, datProdPrice, datProdCal, datStockLvl);
if (result > 0)
{
string saveimg = Server.MapPath(" ") + "\\" + image;
FileUpload_ProdImg.SaveAs(saveimg);
Response.Write("<script>alert('Update successful');</script>");
Response.Redirect("admin_products_details.aspx?ProdID=" + datProdID);
}
else
{
Response.Write("<script>alert('Update fail');</script>");
}
}<-The code for the button edit event trigger
**Product.cs**
...public int ProductUpdate(string upID, string upName, string upDesc, string upImg, decimal upPrice, int upCal, int upstkLvl)
{
string queryStr = "UPDATE Products SET" + " ProdName = #productName, " + " ProdDesc = #productDesc, " + " ProdImg = #productImage, " + " ProdPrice = #productPrice, " + " ProdCalorie = #productCal, " + " StockLevel = #productStkLvl " + " WHERE ProdID = #productID";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#productID", upID);
cmd.Parameters.AddWithValue("#productName", upName);
cmd.Parameters.AddWithValue("#productDesc", upDesc);
cmd.Parameters.AddWithValue("#productImage", upImg);
cmd.Parameters.AddWithValue("#productPrice", upPrice);
cmd.Parameters.AddWithValue("#productCal", upCal);
cmd.Parameters.AddWithValue("#productStkLvl", upstkLvl);
conn.Open();
int nofRow = 0;
nofRow = cmd.ExecuteNonQuery();
conn.Close();
return nofRow;
}<-The code for updating the mysql database,located in a different cs file,titled Product.cs
My mysql database table is called Products
Thank you very much for your help in advance.
I have some scripts that appear when a field is left blank or with a 0 in an asp.net web form. The warnings are triggering correctly, however the submission does not stop when the script appears. The save button continues to saving the item after it send the "please enter option order" warning. So the prompt appears, but the webform continues processing the save request. I think my brackets may be off. I can't seem to find the issue, does anyone see where I am making a mistake? I'm fairly confident it has something to do with my brackets, but I have not used a textbox inside of a repeater to set a warning/scriptblock before, so may be wrong.I need the page to stop processing the save once the "please enter option order" message appears. The page does stop when the "please enter a stem" triggers if that field is blank, hence my belief it's about the bracket location.
protected void saveButton_Click(object sender, EventArgs e)
{
con.Open();
var dtOptionsData = (DataSet)ViewState["dtOption"];
for (var i = 0; i < RptOptions.Items.Count; i++)
{
var tbOptionOrder = (RptOptions.Items[i].FindControl("OptionOrder") as TextBox);
//dtOptionsData.Tables[0].Rows[i]["Option Order"] = tbOptionOrder.Text;
if (tbOptionOrder.Text == "")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter Option Order');", true);
}
if (tbOptionOrder.Text == "0")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter Option Order');", true);
}
}
if (stemTextBox.Text == "")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter a Stem');", true);
}
else
try
{
//get revision header id to insert on original item
SqlCommand cmdOriginalHeaderID = new SqlCommand("select distinct item_header_id from item_header where item_id = #item_id", con);
cmdOriginalHeaderID.Parameters.AddWithValue("#item_id", cloneItemID.Text);
var OriginalHeaderID = cmdOriginalHeaderID.ExecuteScalar();
//sql cmd1 is for item header info
SqlCommand cmd1 = new SqlCommand("Update item_header set item_id = #item_id, old_item_id = #old_item_id, item_stem = #item_stem, modified_by = #modified_by, modified_datetime = getdate(), language = #language,solution = #solution, item_status_id = (select distinct s.item_status_id from item_status s left join item_header h on h.item_status_id = s.item_status_id where s.item_status_desc = #status), item_ownership_type_id = (select distinct o.item_ownership_id from item_ownership_type o left join item_header h on o.item_ownership_id = h.item_ownership_type_id where o.item_ownership_desc = #ownership) ,market_segment_id = (select distinct m.market_segment_id from market_segment m left join item_header h on m.market_segment_id = h.market_segment_id where m.market_segment_name = #marketsegment) , mcs_code_id = (select distinct m.mcs_code_id from mcs_code m left join item_header h on m.mcs_code_id = h.mcs_code_id where m.mcs_code = #mcsid), item_type_id = (select distinct t.item_type_id from type_item t left join item_header h on t.item_type_id = h.item_type_id where t.item_type_desc = #typeid)," +
"author_person_id = (Select person_id from [persons] p where p.first_Name +' ' + p.last_Name= #specialist) where item_header_id = #OriginalHeaderID", con);
cmd1.Parameters.AddWithValue("#item_id", newIdTextBox.Text);
cmd1.Parameters.AddWithValue("#item_stem", stemTextBox.Text);
cmd1.Parameters.AddWithValue("#modified_by", createdByTextBox.Text);
cmd1.Parameters.AddWithValue("#old_item_id", oldItemIDTextBox.Text);
cmd1.Parameters.AddWithValue("#language", txtLanguage.Text);
cmd1.Parameters.AddWithValue("#status", itemStatusDDL.SelectedValue);
cmd1.Parameters.AddWithValue("#ownership", ownershipDDL.SelectedValue);
cmd1.Parameters.AddWithValue("#marketsegment", marketDDL.SelectedValue);
cmd1.Parameters.AddWithValue("#mcsid", txtMCSid.Text);
cmd1.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
cmd1.Parameters.AddWithValue("#specialist", authorTextBox.Text);
cmd1.Parameters.AddWithValue("#typeid", ddlType.SelectedValue);
cmd1.Parameters.AddWithValue("#solution", solutionTextBox.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
foreach (RepeaterItem item in RptOptions.Items)
{
var Option = (item.FindControl("Option") as TextBox).Text;
var OptionOrder = (item.FindControl("OptionOrder") as TextBox).Text.Replace("'", "''");
var Key = (item.FindControl("Key") as CheckBox).Checked;
var itemDetailID = (item.FindControl("DetailID") as TextBox).Text;
//var ItemRefID = (item.FindControl("ItemRefID") as TextBox).Text.Replace("'", "''");
var optionsCmd = new SqlCommand("MERGE item_detail AS [target] USING (VALUES(#OriginalHeaderID, #Option, #OptionOrder, #Key, #ItemDetailID)) AS source(sitemheaderid, soption, soptionorder, soptionkey, sItemDetailID) ON [target].item_header_id = source.sItemHeaderID AND [target].item_detail_id = source.sItemDetailID WHEN MATCHED THEN UPDATE SET [target].[option] = source.soption, [target].option_order = source.soptionorder, [target].option_key = source.soptionkey, [target].[weight] = source.soptionkey, [target].modified_datetime = GETDATE() WHEN NOT MATCHED THEN INSERT(item_header_id, [option], option_order, option_key,[weight], created_datetime) VALUES(source.sItemHeaderID, source.soption, source.soptionorder, source.soptionkey,source.soptionkey, getdate());", con);
optionsCmd.Parameters.AddWithValue("#ItemDetailID", itemDetailID);
optionsCmd.Parameters.AddWithValue("#Option", Option);
optionsCmd.Parameters.AddWithValue("#OptionOrder", OptionOrder);
optionsCmd.Parameters.AddWithValue("#Key", Key);
optionsCmd.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
//refsCmd.Parameters.AddWithValue("#ItemRefID", ItemRefID);
optionsCmd.ExecuteNonQuery();
}
var deletedOptions = ViewState["deleteOptions"] as string;
if (!string.IsNullOrEmpty(deletedOptions))
{
var deleteOptionsCmd = new SqlCommand("delete from item_detail where item_detail_id in (" + deletedOptions.Trim(',') + ")", con);
deleteOptionsCmd.ExecuteNonQuery();
}
foreach (RepeaterItem item in RptRefs.Items)
{
var referenceid = (item.FindControl("refID") as TextBox).Text.Replace("'", "''");
var pages = (item.FindControl("Pages") as TextBox).Text.Replace("'", "''");
var Verification = (item.FindControl("Verification") as TextBox).Text.Replace("'", "''");
var ItemRefID = (item.FindControl("ItemRefID") as TextBox).Text.Replace("'", "''");
var refsCmd = new SqlCommand("MERGE item_reference AS [target] USING (VALUES(#OriginalHeaderID, #refID, #Pages, #Verification, #ItemRefID)) AS source(sItemHeaderID, sRefID, sPages, sVerification, sItemReferenceID) ON [target].item_header_id = source.sItemHeaderID AND [target].reference_id = source.sRefID AND [target].item_reference_id = source.sItemReferenceID WHEN MATCHED THEN UPDATE SET [target].[pages] = source.sPages, [target].verification = source.sVerification, [target].modified_datetime = GETDATE() WHEN NOT MATCHED THEN INSERT(item_header_id, reference_id, [pages], verification, created_datetime)VALUES(source.sItemHeaderID, source.sRefID, source.sPages, source.sVerification, getdate());", con);
refsCmd.Parameters.AddWithValue("#refID", referenceid);
refsCmd.Parameters.AddWithValue("#Pages", pages);
refsCmd.Parameters.AddWithValue("#Verification", Verification);
refsCmd.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
refsCmd.Parameters.AddWithValue("#ItemRefID", ItemRefID);
refsCmd.ExecuteNonQuery();
}
var deletedRefs = ViewState["deleteRefs"] as string;
if (!string.IsNullOrEmpty(deletedRefs))
{
var deleteRefsCmd = new SqlCommand("delete from item_reference where item_reference_id in (" + deletedRefs.Trim(',') + ")", con);
deleteRefsCmd.ExecuteNonQuery();
}
foreach (RepeaterItem item in RptComments.Items)
{
//var commentid = (item.Controls[0] as TextBox).Text;
var comments = (item.FindControl("comments") as TextBox).Text.Replace("'", "''");
var Specialist = (item.FindControl("Specialist") as TextBox).Text.Replace("'", "''");
var ComID = (item.FindControl("ComID") as TextBox).Text.Replace("'", "''");
var commentsCmd = new SqlCommand("MERGE item_comment AS target USING (Values (#ComID)) AS source(sItemCommentID) ON target.item_comment_id = source.sItemCommentID WHEN MATCHED THEN UPDATE SET target.comment = #comments WHEN NOT MATCHED THEN INSERT (item_header_id, comment, specialist_person_id, created_datetime) VALUES(#originalheaderid,#comments,(Select person_id from [persons] p where p.first_Name +' ' + p.last_Name = #Specialist),getdate());", con);
commentsCmd.Parameters.AddWithValue("#comments", comments);
commentsCmd.Parameters.AddWithValue("#Specialist", Specialist);
commentsCmd.Parameters.AddWithValue("#ComID", ComID);
commentsCmd.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
commentsCmd.ExecuteNonQuery();
}
var deletedComments = ViewState["deleteComments"] as string;
if (!string.IsNullOrEmpty(deletedComments))
{
var deleteCommentsCmd = new SqlCommand("delete from item_comment where item_comment_id in (" + deletedComments.Trim(',') + ")", con);
deleteCommentsCmd.ExecuteNonQuery();
}
foreach (RepeaterItem item in RptEnemy.Items)
{
var enemyID = (item.FindControl("EnemyID") as TextBox).Text.Replace("'", "''");
var enemyHeaderID = (item.FindControl("EnemyHeaderID") as TextBox).Text.Replace("'", "''");
var ItemStem = (item.FindControl("ItemStem") as TextBox).Text.Replace("'", "''");
var Type = (item.FindControl("Type") as TextBox).Text.Replace("'", "''");
var TypeID = (item.FindControl("TypeID") as TextBox).Text.Replace("'", "''");
var SocID = (item.FindControl("SocID") as TextBox).Text.Replace("'", "''");
var enemyCmd = new SqlCommand("MERGE social_order AS target USING (VALUES (#OriginalHeaderID,#SocID, #EnemyHeaderID, #TypeID)) AS source(sItemHeaderID, sSocID, sEnemyItemHeaderID, sSocialOrderTypeID) ON target.item_header_id = source.sItemHeaderID AND target.related_item_header_id = source.sEnemyItemHeaderID WHEN MATCHED THEN UPDATE SET target.social_order_type_id = #TypeID, target.modified_datetime = GETDATE() WHEN NOT MATCHED THEN INSERT (item_header_id, related_item_header_id, social_order_type_id, created_datetime) VALUES (#OriginalHeaderID, #EnemyHeaderID, #TypeID, GETDATE());", con);
//enemyCmd.Parameters.AddWithValue("#EnemyID", enemyID);
enemyCmd.Parameters.AddWithValue("#EnemyHeaderID", enemyHeaderID);
//enemyCmd.Parameters.AddWithValue("#ItemStem", ItemStem);
//enemyCmd.Parameters.AddWithValue("#Type", Type);
enemyCmd.Parameters.AddWithValue("#TypeID", TypeID);
enemyCmd.Parameters.AddWithValue("#SocID", SocID);
enemyCmd.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
enemyCmd.ExecuteNonQuery();
}
var deletedEnemies = ViewState["deleteEnemies"] as string;
if (!string.IsNullOrEmpty(deletedEnemies))
{
var deleteEnemiesCmd = new SqlCommand("delete from social_order where soc_entry_id in (" + deletedEnemies.Trim(',') + ")", con);
deleteEnemiesCmd.ExecuteNonQuery();
}
foreach (RepeaterItem item in RptExhibits.Items)
{
//var commentid = (item.Controls[0] as TextBox).Text;
var exhibitID = (item.FindControl("exhibitID") as TextBox).Text.Replace("'", "''");
var itemExhibitID = (item.FindControl("ItemExID") as TextBox).Text.Replace("'", "''");
//exhibitentry += "(" + headerid + "," + "'" + exhibitID + "'),";
var CmdExhibits = new SqlCommand("MERGE item_exhibit AS target USING (VALUES (#OriginalHeaderID, #exhibitID, #itemExhibitID)) AS source(sItemHeaderID, sExhibitID, sItemExID) ON target.item_header_id = source.sItemHeaderID AND target.exhibit_id = source.sExhibitID and target.item_exhibit_id = source.sItemExID WHEN NOT MATCHED THEN INSERT (item_header_id, exhibit_id, created_datetime) VALUES (#OriginalHeaderID, #exhibitID, getdate());", con);
CmdExhibits.Parameters.AddWithValue("#exhibitID", exhibitID);
CmdExhibits.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
CmdExhibits.Parameters.AddWithValue("#itemExhibitID", itemExhibitID);
CmdExhibits.ExecuteNonQuery();
}
var deletedExhibits = ViewState["deleteExhibits"] as string;
if (!string.IsNullOrEmpty(deletedExhibits))
{
var deleteExhibitsCMD = new SqlCommand("delete from item_exhibit where item_exhibit_id in (" + deletedExhibits.Trim(',') + ")", con);
deleteExhibitsCMD.ExecuteNonQuery();
}
//string reventry = "";
//var cmdRevs = new SqlCommand("select item_header_id from item_header where item_id = #item_id", con);
//cmdRevs.Parameters.AddWithValue("#item_id", newIdTextBox.Text);
foreach (RepeaterItem item in RptRevision.Items)
{
var Change = (item.FindControl("Change") as TextBox).Text;
var Reason = (item.FindControl("Reason") as TextBox).Text;
var PersonID = (item.FindControl("PersonID") as TextBox).Text;
var Specialist = (item.FindControl("Specialist") as TextBox).Text;
var ItemRevID = (item.FindControl("IrID") as TextBox).Text;
var cmdRevisions = new SqlCommand("MERGE item_revision AS target USING (Values (#ItemRevID)) AS source(sItemRevisionID) ON target.item_revision_id = source.sItemRevisionID WHEN MATCHED THEN UPDATE SET target.change = #change, target.reason = #reason, target.specialist_person_id = (Select person_id from [persons] p where p.first_Name +' ' + p.last_Name = #Specialist) , target.modified_datetime = GETDATE() WHEN NOT MATCHED THEN INSERT (item_header_id, change, reason, specialist_person_id, created_datetime) VALUES(#OriginalHeaderID, #Change, #Reason, (Select person_id from [persons] p where p.first_Name +' ' + p.last_Name = #Specialist),getdate());", con);
cmdRevisions.Parameters.AddWithValue("#Change", Change);
cmdRevisions.Parameters.AddWithValue("#Reason", Reason);
cmdRevisions.Parameters.AddWithValue("#PersonID", PersonID);
cmdRevisions.Parameters.AddWithValue("#Specialist", Specialist);
cmdRevisions.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
cmdRevisions.Parameters.AddWithValue("#ItemRevID", ItemRevID);
cmdRevisions.ExecuteNonQuery();
//reventry += "(" + headerid + "," + "'" + Change + "'," + "'" + Reason + "'," + "" + PersonID + "),";
}
var deletedRevisions = ViewState["deleteRevisions"] as string;
if (!string.IsNullOrEmpty(deletedRevisions))
{
var deleteRevisionsCmd = new SqlCommand("delete from item_revision where item_revision_id in (" + deletedRevisions.Trim(',') + ")", con);
deleteRevisionsCmd.ExecuteNonQuery();
}
//confirmation message and clear form after hitting save.
string msgstring = "You Have Successfully Edited this item";
string content = "window.onload=function(){ alert('";
content += msgstring;
content += "');";
content += "window.location='";
content += Request.Url.AbsoluteUri;
content += "';}";
ClientScript.RegisterStartupScript(this.GetType(), "SucessMessage", content, true);
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", "alert('" + ex.Message.Replace("'", "") + "'); ", true);
}
finally
{
con.Close();
}
}
So I figured out a way to get this to work, adding the answer in case anyone else ever encounters a similar issue.
var dtOptionsData = (DataSet)ViewState["dtOption"];
for (var i = 0; i < RptOptions.Items.Count; i++)
{
var tbOptionOrder = (RptOptions.Items[i].FindControl("OptionOrder") as TextBox);
dtOptionsData.Tables[0].Rows[i]["Option Order"] = tbOptionOrder.Text;
if (tbOptionOrder.Text == "")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter Option Order');", true);
return;
}
if (tbOptionOrder.Text == "0")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter Option Order');", true);
return;
}
}
if (stemTextBox.Text == "")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter a Stem');", true);
return;
}
try
I am trying to make this code work fine as i can but i couldnt,i am using cookie and i want to rebind my ListView depending on cookie Location but i am getting error message: "Must declare the scalar variable "#Location"."
protected void Sortcarbtn_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies.Get("Location");
using (SqlConnection carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
if (cookie != null)
{
string CarSqlST = #"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit,
SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads Where 1=1 AND Category=#CATE AND Country = #Location ";
var Location = Convert.ToString(cookie["Location"]);
var cat = Convert.ToString(Request.QueryString["cat"]);
string condition = "";
if (barndcardrlst.SelectedValue != "")
{
condition += " and Maker='" + barndcardrlst.SelectedValue + "'";
}
if (GearDrDw.SelectedValue != "")
{
condition += " and Gear='" + GearDrDw.SelectedValue + "'";
}
if (carstatedrdolst.SelectedValue != "")
{
condition += " and State='" + carstatedrdolst.SelectedValue + "'";
}
if (citiesdrdolst.SelectedValue != "")
{
condition += " and City='" + citiesdrdolst.SelectedValue + "'";
}
if (CarCondDrDw.SelectedValue != "")
{
condition += " and Condition='" + CarCondDrDw.SelectedValue + "'";
}
if (CarstusDRDL.SelectedValue != "")
{
condition += " and Status='" + CarstusDRDL.SelectedValue + "'";
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
condition += " and AdsPrice BETWEEN " + CarPriceFrmDrDw.SelectedValue + " AND " + CarPriceToDrDw.SelectedValue;
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
condition += " and Year BETWEEN " + CarYearfrmDrDw.SelectedValue + " AND " + CarYeartoDrDw.SelectedValue;
}
DataTable cdt = new DataTable();
carcon.Open();
SqlCommand ccmd = new SqlCommand();
ccmd.Connection = carcon;
ccmd.CommandType = CommandType.Text;
ccmd.Parameters.AddWithValue("#Country", Location);
ccmd.Parameters.AddWithValue("#CATE", cat);
ccmd.CommandText = CarSqlST + condition;
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
ad.Fill(cdt);
cateshowlistview.DataSource = cdt;
cateshowlistview.DataBind();
}
}
Change "#Country" in
ccmd.Parameters.AddWithValue("#Country", Location);
to be "#Location"
ccmd.Parameters.AddWithValue("#Location", Location);
you defined the Country in the SQL Statement to be #Location
string CarSqlST = #"SELECT ... AND Category=#CATE AND Country = #Location ";
Update
To prevent SQL Injection hacks and to allow for SQL to reuse the query options all the fileters where you are concat the string together you should just use SQL Parameters. To make it easy I create a parameters dictionary to add to. Then at the end loop through the dictionary to fill in the SQL Parameters. I also switched it to string builder since could be doing a lot of string concats. I didn't test this code because I don't have your objects or tables or connections.
using (var carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString)))
{
if (cookie != null)
{
// Parameters for SQL
var parameters = new Dictionary<string, object>();
// string builder to build up SQL Statement
var CarSqlST = new StringBuilder(
"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit, " +
"SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads " +
"Where Category = #pCATE AND Country = #pLocation ");
parameters.Add("#pCATE", Request.QueryString["cat"].ToString());
parameters.Add("#pLocation", cookie["Location"]);
if (barndcardrlst.SelectedValue != "")
{
CarSqlST.Append(" and Maker= #pMaker");
parameters.Add("#pMaker", barndcardrlst.SelectedValue);
}
if (GearDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Gear= #pGear");
parameters.Add("#pGear", GearDrDw.SelectedValue);
}
if (carstatedrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pState");
parameters.Add("#pState", carstatedrdolst.SelectedValue);
}
if (citiesdrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pCity");
parameters.Add("#pCity", citiesdrdolst.SelectedValue);
}
if (CarCondDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Condition= #pCondition");
parameters.Add("#pCondition", CarCondDrDw.SelectedValue);
}
if (CarstusDRDL.SelectedValue != "")
{
CarSqlST.Append(" and Status= #pStatus");
parameters.Add("#pStatus", CarstusDRDL.SelectedValue);
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and AdsPrice BETWEEN #pLowPrice AND #pHighPrice");
parameters.Add("#pLowPrice", CarPriceFrmDrDw.SelectedValue);
parameters.Add("#pHighPrice", CarPriceToDrDw.SelectedValue);
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and Year BETWEEN #pLowYear AND #pHighYear");
parameters.Add("#pLowYear", CarYearfrmDrDw.SelectedValue);
parameters.Add("#pHighYear", CarYeartoDrDw.SelectedValue);
}
DataTable cdt = new DataTable();
SqlCommand ccmd = carcon.CreateCommand();;
ccmd.CommandType = CommandType.Text;
// Add all the parameters into this command
foreach (var parameter in parameters)
{
ccmd.Parameters.Add(parameter.Key, parameter.Value);
}
// set the command text from string builder
ccmd.CommandText = CarSqlST.ToString();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
}
}
You could have created the command at the top and filled in the sql parameters right away instead of the dictionary but I like the dictionary approach better in case something happens - exception or we need to bail we never created the SQL Command.
hi I am trying to load data into sql from an excel spreadsheet from a web page, I am getting a "Cannot implicitly convert type 'string' to 'decimal" error I have tried different ways to correct this but nothing is working.
namespace CarpartsStore.Dealers
{
partial class DealerHome : System.Web.UI.Page
{
protected void ButtonUpload_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible = true;
PanelView.Visible = false;
PanelImport.Visible = false;
}
protected OleDbCommand ExcelConnection()
{
// Connect to the Excel Spreadsheet
string xConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/ExcelImport.xls") + ";" + "Extended Properties=Excel 8.0;";
// create your excel connection object using the connection string
OleDbConnection objXConn = new OleDbConnection(xConnStr);
objXConn.Open();
// use a SQL Select command to retrieve the data from the Excel Spreadsheet
// the "table name" is the name of the worksheet within the spreadsheet
// in this case, the worksheet name is "Members" and is coded as: [Members$]
OleDbCommand objCommand = new OleDbCommand("SELECT * FROM [Products$]", objXConn);
return objCommand;
}
protected void ButtonView_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible = false;
PanelView.Visible = true;
PanelImport.Visible = false;
// Create a new Adapter
OleDbDataAdapter objDataAdapter = new OleDbDataAdapter();
// retrieve the Select command for the Spreadsheet
objDataAdapter.SelectCommand = ExcelConnection();
// Create a DataSet
DataSet objDataSet = new DataSet();
// Populate the DataSet with the spreadsheet worksheet data
objDataAdapter.Fill(objDataSet);
// Bind the data to the GridView
GridViewExcel.DataSource = objDataSet.Tables[0].DefaultView;
GridViewExcel.DataBind();
}
protected void ButtonImport_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible = false;
PanelView.Visible = false;
PanelImport.Visible = true;
LabelImport.Text = "";
// reset to blank
// retrieve the Select Command for the worksheet data
OleDbCommand objCommand = new OleDbCommand();
objCommand = ExcelConnection();
// create a DataReader
OleDbDataReader reader;
reader = objCommand.ExecuteReader();
// create variables for the spreadsheet columns
int ProductID = 0;
int MakeID = 0;
int DealerID = 0;
string PartNumber = "";
string Description = "";
decimal UnitCost = 0.00M;
decimal Postage = 0.00M;
int QtyAvailable = 0;
string UserName = "";
string Make = "";
int counter = 0;
// used for testing your import in smaller increments
while (reader.Read())
{
counter = counter + 1;
// counter to exit early for testing...
// set default values for loop
ProductID = 0;
MakeID = 0;
DealerID = 0;
PartNumber = GetValueFromReader(reader,"PartNumber");
Description = GetValueFromReader(reader,"Description");
UnitCost = GetValueFromReader(reader,"UnitCost");
Postage = GetValueFromReader(reader, "Postage");
QtyAvailable = GetValueFromReader(reader,"QtyAvailable");
UserName = GetValueFromReader(reader,"UserName");
Make = GetValueFromReader(reader,"Make");
// Insert any required validations here...
MakeID = GetMakeID(Make);
DealerID = GetDealerID(UserName);
//retrieve the MakeID
ProductID = ImportIntoProducts(PartNumber, Description, UnitCost, Postage, QtyAvailable, MakeID, DealerID);
LabelImport.Text = LabelImport.Text + ProductID + PartNumber + " " + Description + " " + UnitCost + " " + Postage + " " + QtyAvailable + " " + UserName + " Make_id: " + MakeID + " " + Make + "<br>";
//If counter > 2 Then ' exit early for testing, comment later...
// Exit While
//End If
}
reader.Close();
}
protected string GetValueFromReader(OleDbDataReader myreader, string stringValue)
{
object val = myreader[stringValue];
if (val != DBNull.Value)
return val.ToString();
else
return "";
}
protected void ButtonUploadFile_Click(object sender, System.EventArgs e)
{
if (FileUploadExcel.HasFile)
{
try
{
// alter path for your project
FileUploadExcel.SaveAs(Server.MapPath("~/ExcelImport.xls"));
LabelUpload.Text = "Upload File Name: " +
FileUploadExcel.PostedFile.FileName + "<br>" +
"Type: " + FileUploadExcel.PostedFile.ContentType +
" File Size: " + FileUploadExcel.PostedFile.ContentLength +
" kb<br>";
}
catch (System.NullReferenceException ex)
{
LabelUpload.Text = "Error: " + ex.Message;
}
}
else
{
LabelUpload.Text = "Please select a file to upload.";
}
}
protected int GetMakeID(string MakeName)
{
int makeID = 0;
try
{
CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.MakesTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.MakesTableAdapter();
SSSProductsDataSet.MakesDataTable SSDataTable = null;
SSDataTable = SSAdapter.GetMakeByName(MakeName);
// see if the category already exists in the table, if not insert it
if (SSDataTable != null)
{
if (SSDataTable.Rows.Count > 0)
{
if (SSDataTable[0].MakeID > 0)
{
makeID = SSDataTable[0].MakeID;
}
}
}
if (makeID == 0)
{
// if it is still 0, then insert it into the table
// retrieve the identity key category_id from the insert
makeID = (int)SSAdapter.InsertMakeQuery(MakeName);
// if this fails to return the proper category_id, make sure to
// set the InsertCategoryQuery ExecuteMode Property to Scalar
}
return makeID;
}
catch (System.NullReferenceException ex)
{
LabelImport.Text = LabelImport.Text + ex.Message;
return 0;
}
}
protected int GetDealerID(string UserName)
{
int DealerID = 0;
try
{
CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.DealersTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.DealersTableAdapter();
SSSProductsDataSet.DealersDataTable SSDataTable = null;
SSDataTable = SSAdapter.GetDealersByUserName(UserName);
// see if the User already exists in the table, if not insert it
if (SSDataTable != null)
{
if (SSDataTable.Rows.Count > 0)
{
if (SSDataTable[0].DealerID > 0)
{
DealerID = SSDataTable[0].DealerID;
}
}
}
if (DealerID == 0)
{
// if it is still 0, then insert it into the table
// retrieve the identity key category_id from the insert
DealerID = 0;
// if this fails to return the proper category_id, make sure to
// set the InsertCategoryQuery ExecuteMode Property to Scalar
}
return DealerID;
}
catch (System.NullReferenceException ex)
{
LabelImport.Text = LabelImport.Text + ex.Message;
return 0;
}
}
protected int ImportIntoProducts(string PartNumber, string Description, decimal UnitCost, decimal Postage, int QtyAvailable, int MakeID, int DealerID)
{
// make sure values don't exceed column limits
PartNumber = Left(PartNumber, 50);
Description = Left(Description, 300);
UnitCost = Convert.ToDecimal(UnitCost);
int ProductID = 0;
try
{
CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.ProductsTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.ProductsTableAdapter();
SSSProductsDataSet.ProductsDataTable SSDataTable = null;
SSDataTable = SSAdapter.GetProductsByPartNumberDealer(PartNumber, DealerID);
// see if the category already exists in the table, if not insert it
if (SSDataTable != null)
{
if (SSDataTable.Rows.Count > 0)
{
if (SSDataTable[0].ProductID > 0)
{
ProductID = SSDataTable[0].ProductID;
LabelImport.Text = LabelImport.Text + "<font color=blue>PartNumber Found, Not Imported: " + " ID: " + ProductID + " " + PartNumber + " " + Description + "" + UnitCost + "" + Postage + ".</font><br>";
}
}
}
if (ProductID == 0)
{
// if it is still 0, then insert it into the table
// retrieve the identity key ProductID from the insert
ProductID = Convert.ToInt32(SSAdapter.InsertProductQuery(PartNumber, Description,UnitCost, Postage, QtyAvailable, MakeID, DealerID));
LabelImport.Text = LabelImport.Text + "<font color=white>Part Number Imported: " + " ID: " + ProductID + " " + PartNumber + " " + Description + " Cost: " + UnitCost + ".</font><br>";
}
return ProductID;
}
catch (System.NullReferenceException ex)
{
LabelImport.Text = LabelImport.Text + "<font color=red>" + ex.Message + "</font><br>";
return 0;
}
}
// http://www.mgbrown.com/PermaLink68.aspx
public static string Left(string text, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException("length", length, "length must be > 0");
else if (length == 0 || text.Length == 0)
return "";
else if (text.Length <= length)
return text;
else
return text.Substring(0, length);
}
}
}
The following code change will allow your code to run:
try
{
UnitCost = GetValueFromReader(reader,"UnitCost");
}
catch(Exception)
{
// put a breakpoint here to find the problem using the debugger
}
try
{
Postage = GetValueFromReader(reader, "Postage");
}
catch(Exception)
{
// put a breakpoint here to find the problem using the debugger
}
What you really want to do is understand how the source data is causing the error. (Maybe you have a null or a non-numeric value in the source data.)
Leaving the code like this could (and probably will) introduce data errors into other parts of your system.
I have a function like this
///
/// This function binds the emplist drop down for mentor user.
///
private void BindEmpDropDownForMentor()
{
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
OleDbConnection oleConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
OleDbCommand oleCommand = new OleDbCommand(strSelectMentorQuery, oleConnection);
try
{
//Open Connection
oleConnection.Open();
//Set Datasource and close connection
cmbempList.DataSource = oleCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
cmbempList.DataValueField = "";
cmbempList.DataTextField = "NAME";
//Bind the Dropdown
cmbempList.DataBind();
//Add a new item 'ALL TEAM MEMBERS' to the member list
cmbempList.Items.Insert(0, new ListItem("ALL TEAM MEMBERS", "0"));
cmbempList.SelectedIndex = 0;
GridViewDataShowBy = cmbempList.SelectedValue;
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
}
finally
{
// Close the connection when done with it.
oleConnection.Close();
}
}
But on selected change event of cmbempList, format exception error is being caught saying this that input string was not in correct form in the bold line below
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
gvLeaveList.CurrentPageIndex = 0;
dgDaysAbsent.CurrentPageIndex = 0;
**if (!(Convert.ToInt32(cmbempList.SelectedValue) > 0))
{**
if (this.Session["RoleID"].ToString() == "1")
{
cmbLeads.ClearSelection();
cmbLeads.SelectedIndex = cmbLeads.Items.IndexOf(cmbLeads.Items.FindByValue(this.Session["UserID"].ToString()));
}
}
GridViewDataShowBy = cmbempList.SelectedValue.ToString();
if (cmbempList.SelectedValue != "0" && cmbempList.SelectedValue != "")
{
Page.Title = cmbempList.SelectedItem.Text + " | Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
else
{
Page.Title = "Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
PopulateLeaveList(GridViewDataShowBy, "0");
BindLeaveListGrid(GridViewDataShowBy, cmbLeads.SelectedValue.ToString());
}
It is because cmbempList's DataValueField is being set to an empty string in the BindEmpDropDownForMentor method.
cmbempList.DataValueField = "";
This will cause cmbempList's values to be bound to the values in the DataTextField which are strings. When the SelectedIndexChange event is called it tries to parse the strings to an Int32 which is throwing the exception.
Convert.ToInt32(cmbempList.SelectedValue) > 0
To fix it you can add an aliased ID field in the SQL query and set the cmbempList.DataValueField to that ID name which is probably your intent.
For example in BindEmpDropDownForMentor make this edit to your query:
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME, MLL.LED_ID AS ID FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
And assign your DataValueField to this:
cmbempList.DataValueField = "ID";
try this.
if it still fails look in the debugger what value cmbempList.SelectedValue contains.
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
// ...
object selectedValue = cmbempList.SelectedValue;
if ((selectedValue != null) && (selectedValue != DBNull.Value) && (!(Convert.ToInt32(selectedValue) > 0))
{
// ...