Related
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
}
}
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 creating a windows form application that generates timetable automatically. I am having a problem to write a query when a user select semester number from the dropdown(from 1-8) then what should I write in query? My Code is below.
private void button_generate_Click(object sender, EventArgs e)
{
SqlCommand com;
SqlConnection con = new SqlConnection("Data Source=MAJOR-DYNASTI;Initial Catalog=ESS;Integrated Security=True");
con.Open();
string a = comboBox_semester.SelectedText;
string str = "SELECT CourseName, TeacherName, RoomName FROM Course_teacher, RoomInfo where Semester= ORDER BY NEWID(); ";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
if (reader.HasRows)
{
Random random = new Random();
var labels = new Label[] { label1, label2, label3, label4, label5, label6, label7, label8,label9,label10,label11,label12,label13,label14,label15,label16,
label17,label18,label19,label20,label21,label22,label23,label24,label25,label26,label27,label28,label29,label30,label31,
label32,label33,label34,label35,label36,label37,label38,label39,label40,label41,label42,label43,label44,label45,label46,label47,label48,
label49,label50};
label1.Text = ""; label2.Text = ""; label3.Text = ""; label4.Text = ""; label5.Text = ""; label6.Text = "";
label7.Text = "";label8.Text = "";label9.Text = "";label10.Text = "";label11.Text = "";label12.Text = "";label13.Text = "";label14.Text = "";label15.Text = "";label16.Text = "";
label17.Text = "";label18.Text = "";label19.Text = "";label20.Text = "";label21.Text = "";label22.Text = "";label23.Text = "";label24.Text = "";label25.Text = "";label26.Text = "";label27.Text = "";label28.Text = "";label29.Text = "";label30.Text = "";label31.Text = "";
label32.Text = ""; label33.Text = ""; label34.Text = ""; label35.Text = ""; label36.Text = ""; label37.Text = ""; label38.Text = ""; label39.Text = ""; label40.Text = ""; label41.Text = ""; label42.Text = ""; label43.Text = ""; label44.Text = ""; label45.Text = ""; label46.Text = ""; label47.Text = ""; label48.Text = "";
label49.Text = "";label50.Text = "";
if (
comboBox1.SelectedItem==null ||
comboBox2.SelectedItem==null ||
comboBox_semester.SelectedItem==null)
{
MessageBox.Show("Please Select Complete Detail");
}
else
{
while (reader.Read())
{
int randomNumber = random.Next(1, 50);
labels[randomNumber].Text = String.Format("{0},\r\n{1},\r\n{2}", reader["CourseName"], reader["TeacherName"], reader["RoomName"]);
}
}
}
I want query for these two lines.
string a = comboBox_semester.SelectedText;
string str = "SELECT CourseName, TeacherName, RoomName FROM Course_teacher, RoomInfo where Semester=(what should I need to write here) ORDER BY NEWID(););
Please Help
You need to put your variable a into your query like so:
string str = "SELECT CourseName, TeacherName, RoomName FROM Course_teacher, " +
"RoomInfo WHERE Semester = #Semester ORDER BY NEWID()";
com.Parameters.Add(new SqlParameter("Semester", a));
Just note that I cleaned up your query a little bit, and I introduced parameterized queries in case you're unfamiliar with them.
The best way to do this is going to look something like this:
"Where Semester = #Semester"
Then, on a following line, you add a Parameter to your SqlCommand object like so:
com.Parameters.AddWithValue("#Semester", a);
This lets the SQLCommand object know to substitute your variable (I've named it #Semester for now) with the value you have received from the user.
I got trouble handling no row at position 0 any idea how can i fix this?
MY CODE:
public void FillAPModify()
{
sqliteConUserData.connection.Close();
sqliteConUserData.connection.Open();
var _command = sqliteConUserData.connection.CreateCommand();
var query = string.Format("SELECT * FROM tblTracking Where FileNumber = '" + StaticModel.clickNumValue + "' COLLATE NOCASE");
string commandText = query;
var _dataAdapter = new SQLiteDataAdapter(commandText, sqliteConUserData.connection);
DataSet _dataSet = new DataSet();
DataTable _dataTable = new DataTable();
_dataSet.Reset();
_dataAdapter.Fill(_dataSet);
_dataTable = _dataSet.Tables[0];
var rows = _dataTable.Rows;
string fileNumber = rows[0].ItemArray[0] as string; \\error
var shiftDate = rows[0].ItemArray[1];
var timeCreated = rows[0].ItemArray[2];
string remarks = rows[0].ItemArray[3] as string;
UserDataVar = new UserDataProperties
{
FileNumber = fileNumber,
ShiftDate = shiftDate.ToString(),
TimeCreated = timeCreated.ToString(),
Remarks = remarks
};
sqliteConUserData.connection.Close();
}
I tried this but no wokring:
if (_dataSet.Tables.Count > 0)
{
if (_dataSet.Tables[0].Rows.Count > 0)
{
\\my stuff
}
}
Your fix should work, but I always check to make sure the dataset isn't null as well and make it all one if statement.
if (_dataSet!= null && _dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
{
_dataTable = _dataSet.Tables[0];
var rows = _dataTable.Rows;
string fileNumber = rows[0].ItemArray[0] as string; \\error
var shiftDate = rows[0].ItemArray[1];
var timeCreated = rows[0].ItemArray[2];
string remarks = rows[0].ItemArray[3] as string;
UserDataVar = new UserDataProperties
{
FileNumber = fileNumber,
ShiftDate = shiftDate.ToString(),
TimeCreated = timeCreated.ToString(),
Remarks = remarks
};
}
I am trying to migrate data from Oracle to SQL.
I already created Table name and field Name.
Type and Size are same on both: e.g.
at Oracle Varchar2(11), On SQL VARCHAR(11)
at Oracle Date, On SQL datetime2(0).
In my application I'm using SqlBulkCopy function. But I face the above error on Date filed.
private void Processing(string sPath)
{
string AppPath = Application.StartupPath.ToString();
IniFile myIni = new IniFile(sPath);
string allTable = myIni.IniReadValue("TABLENAME", "TABLE");
string[] alltables = allTable.Split(',');
foreach (var tableName in alltables)
{
string whereSqlQuery = string.Empty;
string sOrderBySqlQuery = string.Empty;
string sSQLSelect = string.Empty;
string sRCount = string.Empty;
whereSqlQuery = myIni.IniReadValue(tableName, "WHERE");
TableName = tableName;
sOrderBySqlQuery = myIni.IniReadValue(tableName, "ORDERBY");
sSQLSelect = myIni.IniReadValue(tableName, "SQLSELECT");
//sRCount = myIni.IniReadValue(tableName, "RCOUNT");
if (radAuto.Checked == true)
ConnectAndQuery(tableName, whereSqlQuery, sOrderBySqlQuery, sSQLSelect, sRCount);
else
ConnectAndQuery(tableName, whereSqlQuery, sOrderBySqlQuery);
}
}
private void ConnectAndQuery(string strTableName, string strWhere, string strOrderBy, string sSqlSelect, string sRcount)
{
Cursor.Current = Cursors.WaitCursor;
string connectionString = GetConnectionString();
// Using
OracleConnection connection = new OracleConnection();
SqlConnection oConn = default(SqlConnection);
DataTable dtSQL = null;
DateTime dtLog = DateTime.Now;
try
{
//Opening Oracle DB Connection
connection.ConnectionString = connectionString;
connection.Open();
ShownLog(string.Format("Table = {0} , -- STARTING --", strTableName));
ShownLog("Oracle Connection Opened, OK");
OracleCommand command = connection.CreateCommand();
if (!string.IsNullOrEmpty(strWhere))
SqlQuery = "SELECT * FROM " + strTableName + " WHERE "+ strWhere;
else
SqlQuery = string.Format("SELECT * FROM {0} ", strTableName);
if (!string.IsNullOrEmpty(strOrderBy))
SqlQuery += " ORDER BY " + strOrderBy;
command.CommandText = SqlQuery;
System.DateTime startTime = System.DateTime.Now;
ShownLog("Starting Date Time : " + startTime);
DataTable dtTotalInsertCount = new DataTable(strTableName);
if (!string.IsNullOrEmpty(sRcount))
{
//OracleDataAdapter adpCount = new OracleDataAdapter(sRcount, connectionString);
////adpCount.FillSchema(dtTotalInsertCount, SchemaType.Source);
//adpCount.Fill(dtTotalInsertCount);
}
OracleDataAdapter adapter = new OracleDataAdapter(SqlQuery, connectionString);
DataTable dt = new DataTable(strTableName);
adapter.FillSchema(dt, SchemaType.Source);
bool valid = true;
bool bCheck = true;
int count = 1000;
int start = 0;
string sLogQuery = SqlQuery.Replace("'", "");
dtLog = DateTime.Now;
//Insert to SQL Log Table
Insert(strTableName, dtLog, sLogQuery);
int iLogCount = 0;
int iActualCount = 0;
do
{
int iEnd = 0;
adapter.Fill(start, count, dt);
valid = dt.Rows.Count > 0 ? true : false;
if (valid)
{
iLogCount += dt.Rows.Count;
iEnd = start + dt.Rows.Count;
ShownLog("No of data Rows retrieved from Oracle, Count = " + dt.Rows.Count);
//Create the SQL Server Table
oConn = new SqlConnection(txtDestinationConnString.Text);
oConn.Open();
ShownLog("SQL Connection Opened, OK");
if (string.IsNullOrEmpty(sSqlSelect))
bCheck = false;
if (bCheck)
{
ShownLog("Data Comparision Start : " + System.DateTime.Now);
//If SQL Select Statement has
if (!string.IsNullOrEmpty(sSqlSelect))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sSqlSelect;
cmd.Connection = oConn;
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
dtSQL = new DataTable();
dtSQL.Load(reader);
cmd = null;
reader = null;
//Return record has more than 0
ShownLog("Start Duplicate Checking : " + System.DateTime.Now);
if (dtSQL.Rows.Count > 0)
{
foreach (DataRow dr in dtSQL.Rows)
{
DataRow[] result;
if (strTableName == "ITK_STAFF" || strTableName == "ITK_FLIGHT")
{
result = dt.Select("URNO='" + dr[0].ToString() + "'");
}
else
result = dt.Select("URNO=" + dr[0]);
if (result.Length > 0)
{
foreach (var drRemove in result)
{
dt.Rows.Remove(drRemove);
}
}
}
}
ShownLog("End Duplicate Checking : " + System.DateTime.Now);
}
ShownLog("Actual No.s of records to insert : " + dt.Rows.Count);
if (dt.Rows.Count == count)
bCheck = false;
ShownLog("Data Comparision End : " + System.DateTime.Now);
}
if (valid)
{
ShownLog(System.DateTime.Now + " Copying " + strTableName + " From : " + start.ToString() + " To : " + iEnd);
}
start += count;
if (dt.Rows.Count > 0)
{
iActualCount += dt.Rows.Count;
CopyData(dt, oConn);
dt.Rows.Clear();
}
oConn.Close();
oConn = null;
}
} while (valid);
System.DateTime endTime = System.DateTime.Now;
ShownLog("Ending DateTime: " + endTime);
//msgOut("No of rows copied from oracle to SQL Server , Count = " + dt.Rows.Count);
TimeSpan diffTime = endTime.Subtract(startTime);
ShownLog(String.Format("Time Difference is Days : {0}, Hours : {1}, Minites : {2}, seconds : {3} ,Milliseconds : {4}", diffTime.Days, diffTime.Hours, diffTime.Minutes, diffTime.Seconds, diffTime.Milliseconds));
ShownLog(string.Format("Table = {0} , -- FINISHED --", strTableName));
ShownLog(string.Empty);
Update(iLogCount, iActualCount, strTableName, dtLog, sLogQuery, " ", true);
Cursor.Current = Cursors.Default;
}
catch (Exception ex)
{
Cursor.Current = Cursors.Default;
ShownLog(ex.ToString());
ShownLog(string.Empty);
Update(0, 0, strTableName, dtLog, "", ex.ToString(), false);
((IDisposable)connection).Dispose();
if (oConn != null)
oConn.Close();
RadioButtonControl();
}
finally
{
Cursor.Current = Cursors.Default;
((IDisposable)connection).Dispose();
if (oConn != null)
oConn.Close();
RadioButtonControl();
}
}
private void CopyData(DataTable sourceTable, SqlConnection destConnection)
{
// Using
SqlBulkCopy s = new SqlBulkCopy(destConnection);
try
{
s.DestinationTableName = TableName;
s.NotifyAfter = 10000;
s.SqlRowsCopied += new SqlRowsCopiedEventHandler(s_SqlRowsCopied);
s.WriteToServer(sourceTable);
s.Close();
}
finally
{
((IDisposable)s).Dispose();
}
}