Not getting the Total Amount(Without VAT) - c#

Country: Bahrain( i am selecting)
Amount:1000
Bank charges: 100(i am entering)
Vat:5%(entering) result:50(autogenerate)
Discount:6%(entering) result:60(autogenerate)
Total:1070(autogenerate)
This is working fine.I am getting the Total(with VAT).
Country:India(i am selecting)
Amount:1000
Bank charges: 100(i am entering)
Discount:5%(entering) result:50(autogenerate)
Total:(here i am not getting the amount)(may be because i set the visibility of VAT field false)
Here i am hidding the field VAT by using vattr.Visible=false. What should i do in order to sort out this issue?
Code behind:
protected void lstCountryy_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstCountryy.SelectedItem.Text == "U.A.E" || lstCountryy.SelectedItem.Text == "BAHRAIN" || lstCountryy.SelectedItem.Text=="SAUDI ARABIA")
{
vattr.Visible = true;
trdeclaration.Visible = false;
}
else
{
vattr.Visible = false;
trdeclaration.Visible = true;
}
}
Javascript:
function calculate(amount) {
var bankcharge = document.getElementById("<%=txtBankCharge.ClientID%>").value;
var vat = document.getElementById("<%=txtvatt.ClientID%>").value;
var discount = document.getElementById("<%=txtDiscount.ClientID%>").value;
var sum = 0;
$(".amt").each(function () {
if (isNaN(this.value))
{
alert("Please enter numbers only");
return false;
}
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
if (bankcharge.length > 0) {
if (isNaN(bankcharge)) {
alert("Bank charge should be numbers only !!");
return false;
}
else {
sum = sum + parseFloat(bankcharge);
}
}
if (vat.length > 0)
{
if (isNaN(vat)) {
alert("VAT should be numbers only !!");
return false;
}
else {
sum = sum + parseFloat(vat);
}
}
if (discount.length > 0) {
if (isNaN(discount)) {
alert("Discount amount should be numbers only !!");
return false;
}
else {
sum = sum - parseFloat(discount);
}
}
var atemp = sum.toString().split(".");
if (atemp.length > 1) {
sum = sum.toFixed(2);
}
document.getElementById("<%=txtTotal.ClientID%>").value = sum;
document.getElementById("<%=txtAmountInWords.ClientID%>").value = convertNumberToWords(sum);
}
function vatCalc()//added by chetan
{
var sum = 0;
$(".amt").each(function () {
if (isNaN(this.value)) {
alert("Please enter numbers only");
return false;
}
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
var _txt2 = document.getElementById('<%= txtvat.ClientID %>');
var _txt3 = document.getElementById('<%= txtvatt.ClientID %>');
var t1=0, t2=0;
//if(_txt1.value != "") t1=_txt1.value;
if(_txt2.value != "") t2=_txt2.value;
_txt3.value = (sum * parseFloat(t2) )/ 100;
}
function discountCalc()
{
var sum = 0;
$(".amt").each(function () {
if (isNaN(this.value)) {
alert("Please enter numbers only");
return false;
}
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
var _txt2 = document.getElementById('<%= txtDiscountText.ClientID %>');
var _txt3 = document.getElementById('<%= txtDiscount.ClientID %>');
var t1=0, t2=0;
//if(_txt1.value != "") t1=_txt1.value;
if(_txt2.value != "") t2=_txt2.value;
_txt3.value = (sum * parseFloat(t2)) / 100;
}
The problem is here:
if (vat.length > 0)
{
if (isNaN(vat)) {
alert("VAT should be numbers only !!");
return false;
}
else {
sum = sum + parseFloat(vat);
}
}
I wanted to write this condition in such a way that when use selects bahrain,vat should be visible and should be calculated.
when user selects india,vat should be hidden and will yield the total amount.

Finally i got solution.This w orked perfectly.
if (lstCountryy.SelectedValue == "U.A.E" || lstCountryy.SelectedValue == "BAHRAIN" || lstCountryy.SelectedValue == "SAUDI ARABIA")
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "float");
trdeclaration.Visible = false;
//txtvat.Enabled = true;
}
else
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "none");
trdeclaration.Visible = true;
}

Related

How to trigger TreeView NodeMouseClick and CursorChanged events with a method. I am getting error on parameter `e` due to incompatible parameters

I managed to create a TreeView method for NodeMouseClick and CursorChanged events.
private void Node_Selection_Action(object sender, TreeNodeMouseClickEventArgs e)
{
// my action code here...
}
private void TvwPanel_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
Node_Selection_Action(sender, e);
}
However, I am getting an error on e parameter when I applied the method to the CursorChanged:
private void TvwPanel_CursorChanged(object sender, EventArgs e)
{
Node_Selection_Action(sender, e); //error on `e` here
}
I supposed this is due to the parameter EventArgs that is not compatible with my method parameter TreeNodeMouseClickEventArgs.
Is there any workaround that I could use to trigger the CursorChanged event with my method?
UPDATE 1:
As requested, here's the bunch of code for the Node_Selection_Action method:
private void Node_Selection_Action(object sender, TreeNodeMouseClickEventArgs e)
{
TvwPanel.SelectedNode = e.Node;
if (Convert.ToString(e.Node.Tag) == "a") //profile Convert.ToInt16()
{
TsmNewPr.Enabled = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Enabled = true;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Enabled = true;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "b") //database
{
TsmNewPr.Visible = false;
TsmNewDb.Enabled = true;
// arbitrary control if database already exists. If exists disable, otherwise enable.
#region TsmNewDb.Enabled (true/false)
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement enc in profNode)
{
// get the attribute texts
var childrenTexts = enc.Elements("node").Attributes("text");
foreach (var childText in childrenTexts)
{
if (childText.Value != "Type" || childText.Value != "Name" || childText.Value != "Connection")
{
// enable TsmNewDb ContextMenu button if does not exists yet
TsmNewDb.Enabled = false;
}
}
// initialize the attribute tags to null
string TypeTag = null;
string NameTag = null;
string ConnTag = null;
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
TypeTag = childTag.Value;
}
else if (count == 1)
{
NameTag = childTag.Value;
}
else if (count == 2)
{
ConnTag = childTag.Value;
}
count++;
}
// check if database exists
if (db.Databases_Exists(ConnTag) == true)
{
// convert the password to "*" for display purposes
string s = ConnTag;
int start = s.LastIndexOf("pwd=") + "pwd=".Length;
int end = s.IndexOf(";", start);
string result = s.Substring(start, end - start);
s = s.Replace(result, "********");
ConnTag = s;
// transfer data FrmDatabase form to main form tabcontrol panel
LblDbTypeDef.Text = TypeTag;
LblDbNameDef.Text = NameTag;
LblDbConnDef.Text = ConnTag;
// make the main tabcontrol panel visible to true
TbcMain.SelectedIndex = 0;
TbcMain.Visible = true;
}
else
{
// make the main tabcontrol panel visible to false
TbcMain.SelectedIndex = 0;
TbcMain.Visible = false;
}
}
}
#endregion
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Enabled = true;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Enabled = true;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "c") //company file
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Enabled = true;
// arbitrary control if company file already exists. If exists, disable, otherwise enable.
#region TsmNewCo.Enabled (true/false)
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement enc in profNode)
{
// get the attribute texts
var childrenTexts = enc.Elements("node").Attributes("text");
foreach (var childText in childrenTexts)
{
if (childText.Value != "Company Name" || childText.Value != "File Path")
{
// enable TsmNewCo ContextMenu button if does not exists yet
TsmNewCo.Enabled = false;
}
}
// initialize the attribute tags to null
string CoFileTag = null;
string FilePathTag = null;
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
CoFileTag = childTag.Value;
}
else if (count == 1)
{
FilePathTag = childTag.Value;
}
count++;
}
// show db details on the right panel of the main form
if (CoFileTag != null || FilePathTag != null)
{
TbcMain.SelectedIndex = 1;
TbcMain.Visible = true;
LblCompanyFileDef.Text = CoFileTag;
LblFilePathDef.Text = FilePathTag;
}
else
{
TbcMain.SelectedIndex = 1;
TbcMain.Visible = false;
}
}
}
#endregion
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Enabled = true;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Enabled = true;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "d") //tasks
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Enabled = true;
#region Enable/Disable "New" if database and company file are not saved yet
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeDbSiblingName = TvwPanel.SelectedNode.PrevNode.PrevNode.Text;
selNodeCoSiblingName = TvwPanel.SelectedNode.PrevNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
// inquire if database has child or db already, if not this node is disabled
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeDbSiblingName
select en;
if (profNode.Descendants().Count() == 0)
{
TsmNewTk.Enabled = false;
}
}
// inquire if company file has child or has file already, if not this node is disabled
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeCoSiblingName
select en;
if (profNode.Descendants().Count() == 0)
{
TsmNewTk.Enabled = false;
}
else
{
foreach (XElement enc in profNode)
{
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get company details for showing on the right panel of the main form specified below for task creation
foreach (var childTag in childrenTags)
{
if (count == 1)
{
qbFilePath = childTag.Value;
}
count++;
}
}
}
}
#endregion
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Enabled = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Enabled = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
// arbitrary control for showing up tasks summary
#region Extract data from Xml and show in the main form tabcontrol
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
if (Xml_Extract_Data_TaskSum(selNodeParentName, selNodeName) == true)
{
TbcMain.SelectedIndex = 2;
TbcMain.Visible = true;
}
else
{
TbcMain.SelectedIndex = 2;
TbcMain.Visible = false;
}
#endregion
}
else // for the task credentials
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Enabled = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Enabled = true;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Enabled = true;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = true;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
// arbitrary control for showing up tasks details
#region Extract data from Xml and show in the main form tabcontrol
selNodeGrandParentName = TvwPanel.SelectedNode.Parent.Parent.Text;
selNodeDbSiblingName = TvwPanel.SelectedNode.Parent.PrevNode.PrevNode.Text;
selNodeCoSiblingName = TvwPanel.SelectedNode.Parent.PrevNode.Text;
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profileTask =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeGrandParentName
select ep;
foreach (XElement ep in profileTask)
{
IEnumerable<XElement> profNodeTask =
from en in ep.Elements("node")
where (string)en.Attribute("text") == selNodeParentName
select en;
foreach (XElement ept in profNodeTask)
{
IEnumerable<XElement> profNodeTaskCred =
from en in ept.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement eptc in profNodeTaskCred)
{
// initialize the attribute tags to null
string ActionTag = null;
string TablesTag = null;
string FiltersTag = null;
string ScheduleTag = null;
// get the attribute tags
var childrenTags = eptc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
ActionTag = childTag.Value;
}
else if (count == 1)
{
TablesTag = childTag.Value;
}
else if (count == 2)
{
FiltersTag = childTag.Value;
}
else if (count == 3)
{
ScheduleTag = childTag.Value;
}
count++;
}
// show db details on the right panel of the main form
if (ActionTag != null || FiltersTag != null || ScheduleTag != null)
{
LblActionDef.Text = ActionTag;
// TablesTag
string[] TablesTagArray = TablesTag.Split(','); //(new char[] { ',', ' ' });
LvwTables.Items.Clear();
foreach (string tt in TablesTagArray)
{
string table = tt.TrimStart();
ListViewItem lvi = new ListViewItem(table);
LvwTables.Items.Add(lvi);
}
// FiltersTag
// filter period
string filterPeriod;
int Pos1 = FiltersTag.IndexOf("Transactions: ") + "Transactions: ".Length;
int Pos2 = FiltersTag.IndexOf(" | Migration");
filterPeriod = FiltersTag.Substring(Pos1, Pos2 - Pos1);
LblFtrPeriodDef.Text = filterPeriod;
// migration type
string migrationType;
int Pos3 = FiltersTag.IndexOf("Type: ") + "Type: ".Length;
int Pos4 = FiltersTag.IndexOf(" | No");
migrationType = FiltersTag.Substring(Pos3, Pos4 - Pos3);
LblFtrMigTypeDef.Text = migrationType;
// no of record per query
string numberRecords;
int Pos5 = FiltersTag.IndexOf("Query: ") + "Query: ".Length;
numberRecords = FiltersTag.Substring(Pos5);
LblFtrRpqDef.Text = numberRecords;
// filter head
if (filterPeriod == "All" && migrationType == "Overwrite" && numberRecords == "0")
{
LblFiltersDef.Text = "Default";
}
else
{
LblFiltersDef.Text = "Custom";
}
LblSchedDef.Text = ScheduleTag;
TbcMain.SelectedIndex = 3;
TbcMain.Visible = true;
}
else
{
TbcMain.SelectedIndex = 3;
TbcMain.Visible = false;
}
}
}
}
// capture the db credentials for task running
Capture_DB_Credentials_for_NodeMouseClick_And_Task_Saving(selNodeGrandParentName, selNodeDbSiblingName, selNodeCoSiblingName);
#endregion
}
if (e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X, e.Y);
TreeNode ClickNode = TvwPanel.GetNodeAt(ClickPoint);
if (ClickNode == null) return;
// Convert from Tree coordinates to Screen coordinates
Point ScreenPoint = TvwPanel.PointToScreen(ClickPoint);
// Convert from Screen coordinates to Form coordinates
Point FormPoint = this.PointToClient(ScreenPoint);
CmsPanel.Show(this, FormPoint);
}
}
In the Node_Selection_Action method, the last if statement block:
if (e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X, e.Y);
TreeNode ClickNode = TvwPanel.GetNodeAt(ClickPoint);
if (ClickNode == null) return;
// Convert from Tree coordinates to Screen coordinates
Point ScreenPoint = TvwPanel.PointToScreen(ClickPoint);
// Convert from Screen coordinates to Form coordinates
Point FormPoint = this.PointToClient(ScreenPoint);
CmsPanel.Show(this, FormPoint);
}
is the only block of code that needs the TreeNodeMouseClickEventArgs properties. If you really need to pass this type of argument to the method then create one:
// Still no idea what is the relation, however...
private void TvwPanel_CursorChanged(object sender, EventArgs e)
{
var s = sender as TreeView;
var p = s.PointToClient(Cursor.Position);
var ht = s.HitTest(p);
if (ht.Node != null)
{
var args = new TreeNodeMouseClickEventArgs(ht.Node, MouseButtons, 1, p.X, p.Y);
Node_Selection_Action(s, args);
}
}
Unless I'm missing an access to the sender param in your code, you can omit it to simplify the method signature:
private void Node_Selection_Action(TreeNodeMouseClickEventArgs e) { }
Also, you can determine which mouse button is pressed anywhere in your code through the Control.MouseButtons property. The Control.MousePosition property gets the cursor's position in screen coordinates. So, maybe these two properties are all what you need.
Maybe the mentioned above last if block is in the wrong method and moving it into a new method or elsewhere in the context could be better.
Hope that helps.

Word Interop - How to determine if a word doc has page number in Header/footer

I want to know if a Word Document has page number in the Header/Footer using Interop.Word in C#.
I have gone this far
try
{
foreach (Section SectionObj in DocObj.Sections)
{
foreach (HeaderFooter HeaderObj in SectionObj.Footers)
{
if (HeaderObj.Exists && (HeaderObj.Shapes.Count > 0 || !(string.IsNullOrEmpty(HeaderObj.Range.Text) || HeaderObj.Range.Text.Equals("\r"))))
{
if(HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleNumberInDash
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleUppercaseLetter
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleUppercaseRoman
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleNumberInCircle
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleLowercaseRoman
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleLowercaseLetter
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleHindiLetter1)
{
PageNumber = true;
}
}
}
}
}
catch (Exception e) { }
But the checks cannot determine if it is Page number or not. What should I do to determine if it has page numbers?
You should check the Header and the Footer of Section using the PageNumbers.Count propertie.
private bool HeaderOrFooterHasPageNumber(Word.HeaderFooter headOrFooter)
{
if (headOrFooter != null)
return headOrFooter.PageNumbers.Count > 0;
else
return false;
}
And you can call this like...
bool hasNumberPages = false;
Word.Document doc = WordApp.ActiveDocument;
try
{
Word.HeaderFooter headOrFooter = null;
Word.Section section = null;
for (int i = 1; i <= doc.Sections.Count; i++)
{
try
{
section = doc.Sections[i];
if(section != null)
{
headOrFooter = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
}
}
finally
{
if(headOrFooter != null)
{
Marshal.ReleaseComObject(headOrFooter);
headOrFooter = null;
}
if (section != null)
Marshal.ReleaseComObject(section);
}
}
}
finally
{
if (doc != null)
Marshal.ReleaseComObject(doc);
}

Looping datatable for assigning values to a string

I have a gridview, in which there are multiple columns and rows.
While debugging it generates datatable as below
and its query is
DataTable dttable2 = new DataTable();
dttable2 = CF.ExecuteDT("select cr.Mkey, cr.Rating1,cr.Rating2,cr.Rating3,cr.Rating4 from p_emp_Company_Rating cr "+
"join p_emp_Exit_Interview ei on ei.Mkey=cr.Mkey where ei.mkey='" + HidMKey.Value + "'");
I want to loop it as much as it contains rows.
I tried with below code but it is going once and coming out.
string strgrid1 = string.Empty;
if (dttable2.Rows.Count > 0)
{
/** Job security **/
if (dttable2.Rows[0]["Rating1"].ToString() == "Y")
{
strgrid1 = "Poor";
}
if (dttable2.Rows[0]["Rating2"].ToString() == "Y")
{
strgrid1 = "Satisfactory";
}
if (dttable2.Rows[0]["Rating3"].ToString() == "Y")
{
strgrid1 = "Good";
}
if (dttable2.Rows[0]["Rating4"].ToString() == "Y")
{
strgrid1 = "Excellent";
}
}
Below is screenshot of the gridview
how to loop it ?
Try a foreach loop instead of an if statement.
string strgrid1 = string.Empty;
foreach (DataRow row in dttable2.Rows)
{
/** Job security **/
if (row["Rating1"].ToString() == "Y")
{
strgrid1 = "Poor";
}
if (row["Rating2"].ToString() == "Y")
{
strgrid1 = "Satisfactory";
}
if (row["Rating3"].ToString() == "Y")
{
strgrid1 = "Good";
}
if (row["Rating4"].ToString() == "Y")
{
strgrid1 = "Excellent";
}
}
You can also try For Loop to achieve desired results.
string strgrid1 = string.Empty;
if (dttable2.Rows.Count > 0)
{
/** Job security **/
for(int i = 0; i < dttable2.Rows.Count - 1; i++)
{
if (dttable2.Rows[i]["Rating1"].ToString() == "Y")
{
strgrid1 = "Poor";
}
if (dttable2.Rows[i]["Rating2"].ToString() == "Y")
{
strgrid1 = "Satisfactory";
}
if (dttable2.Rows[i]["Rating3"].ToString() == "Y")
{
strgrid1 = "Good";
}
if (dttable2.Rows[i]["Rating4"].ToString() == "Y")
{
strgrid1 = "Excellent";
}
}
}

How to get selected value or index of a dropdownlist upon entering a page?

I have a product ordering page with various product option dropdownlists which are inside a repeater. The "Add To Cart" button is "inactive" until all the options have a selection. Technically, the "Add To Cart" button has two images: a grey one which is used when the user has not selected choices for all options available to a product and an orange one which is used when the user has made a selection from each dropdownlist field.These images are set by the ShowAddToBasket and HideAddToBasket functions.
The dropdownlist fields are connected in that a selection from the first field will determine a selection for the second and sometimes third field. If the second field is NOT pre-set by the first field, then the second field will determine the value for the third field. The first dropdownlist field is never disabled, but the other two can be based on what options have been selected.
There are a few products that have all 3 of their dropdownlists pre-set to certain choices upon entering their page. This means they are all disabled and cannot be changed by the user. Regardless of whether the user enters in a quantity or not, the "Add To Cart" button NEVER activates. I cannot for the life of me figure out how to change it so that, in these rare circumstances, the "Add to Cart" button is automatically set to active once a quantity has been entered. The dropdownlists still have options selected in these pages--it's just that they are fixed and cannot be changed by the user.
Is there anyway I can get the selected value or selected index of these dropdownlist fields upon entering a product page? I want to be able to check to see if they are truly "empty" or if they do have selections made so I can set the "Add to Cart" button accordingly.
Any help would be great because I'm really stuck on this one! :(
Here is the code behind (I removed a lot of the unimportant functions):
protected void Page_Init(object sender, System.EventArgs e)
{
string MyPath = HttpContext.Current.Request.Url.AbsolutePath;
MyPath = MyPath.ToLower();
_Basket = AbleContext.Current.User.Basket;
RedirQryStr = "";
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
if (Request.QueryString["LineID"] != null)
{
int LineID = Convert.ToInt32(Request.QueryString["LineID"].ToString());
int itemIndex = _Basket.Items.IndexOf(LineID);
BasketItem item = _Basket.Items[itemIndex];
OldWeight.Text = item.Weight.ToString();
OldQty.Text = item.Quantity.ToString();
OldPrice.Text = item.Price.ToString();
}
int UnitMeasure = 0;
SetBaidCustoms(ref UnitMeasure);
GetPrefinishNote();
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
_Product = ProductDataSource.Load(_ProductId);
if (_Product != null)
{
//GetPercentage();
int _PieceCount = 0;
double _SurchargePercent = 0;
CheckoutHelper.GetItemSurcargePercent(_Product, ref _PieceCount, ref _SurchargePercent);
SurchargePieceCount.Text = _PieceCount.ToString();
SurchargePercent.Text = _SurchargePercent.ToString();
//add weight
BaseWeight.Value = _Product.Weight.ToString();
//DISABLE PURCHASE CONTROLS BY DEFAULT
AddToBasketButton.Visible = false;
rowQuantity.Visible = false;
//HANDLE SKU ROW
trSku.Visible = (ShowSku && (_Product.Sku != string.Empty));
if (trSku.Visible)
{
Sku.Text = _Product.Sku;
}
//HANDLE PART/MODEL NUMBER ROW
trPartNumber.Visible = (ShowPartNumber && (_Product.ModelNumber != string.Empty));
if (trPartNumber.Visible)
{
PartNumber.Text = _Product.ModelNumber;
}
//HANDLE REGPRICE ROW
if (ShowMSRP)
{
decimal msrpWithVAT = TaxHelper.GetShopPrice(_Product.MSRP, _Product.TaxCode != null ? _Product.TaxCode.Id : 0);
if (msrpWithVAT > 0)
{
trRegPrice.Visible = true;
RegPrice.Text = msrpWithVAT.LSCurrencyFormat("ulc");
}
else trRegPrice.Visible = false;
}
else trRegPrice.Visible = false;
// HANDLE PRICES VISIBILITY
if (ShowPrice)
{
if (!_Product.UseVariablePrice)
{
trBasePrice.Visible = true;
BasePrice.Text = _Product.Price.ToString("F2") + BairdLookUp.UnitOfMeasure(UnitMeasure);
trOurPrice.Visible = true;
trVariablePrice.Visible = false;
}
else
{
trOurPrice.Visible = false;
trVariablePrice.Visible = true;
VariablePrice.Text = _Product.Price.ToString("F2");
string varPriceText = string.Empty;
Currency userCurrency = AbleContext.Current.User.UserCurrency;
decimal userLocalMinimum = userCurrency.ConvertFromBase(_Product.MinimumPrice.HasValue ? _Product.MinimumPrice.Value : 0);
decimal userLocalMaximum = userCurrency.ConvertFromBase(_Product.MaximumPrice.HasValue ? _Product.MaximumPrice.Value : 0);
if (userLocalMinimum > 0)
{
if (userLocalMaximum > 0)
{
varPriceText = string.Format("(between {0} and {1})", userLocalMinimum.LSCurrencyFormat("ulcf"), userLocalMaximum.LSCurrencyFormat("ulcf"));
}
else
{
varPriceText = string.Format("(at least {0})", userLocalMinimum.LSCurrencyFormat("ulcf"));
}
}
else if (userLocalMaximum > 0)
{
varPriceText = string.Format("({0} maximum)", userLocalMaximum.LSCurrencyFormat("ulcf"));
}
phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
}
}
//UPDATE QUANTITY LIMITS
if ((_Product.MinQuantity > 0) && (_Product.MaxQuantity > 0))
{
string format = " (min {0}, max {1})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity, _Product.MaxQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
QuantityX.MaxValue = _Product.MaxQuantity;
}
else if (_Product.MinQuantity > 0)
{
string format = " (min {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
}
else if (_Product.MaxQuantity > 0)
{
string format = " (max {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MaxQuantity)));
QuantityX.MaxValue = _Product.MaxQuantity;
}
if (QuantityX.MinValue > 0) QuantityX.Text = QuantityX.MinValue.ToString();
AddToWishlistButton.Visible = AbleContext.Current.StoreMode == StoreMode.Standard;
}
else
{
this.Controls.Clear();
}
if (!Page.IsPostBack)
{
if (Request.QueryString["Action"] != null)
{
if (Request.QueryString["Action"].ToString().ToLower() == "edit")
{
SetEdit();
}
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (_Product != null)
{
if (ViewState["OptionDropDownIds"] != null)
{
_OptionDropDownIds = (Hashtable)ViewState["OptionDropDownIds"];
}
else
{
_OptionDropDownIds = new Hashtable();
}
if (ViewState["OptionPickerIds"] != null)
{
_OptionPickerIds = (Hashtable)ViewState["OptionPickerIds"];
}
else
{
_OptionPickerIds = new Hashtable();
}
_SelectedOptionChoices = GetSelectedOptionChoices();
OptionsList.DataSource = GetProductOptions();
OptionsList.DataBind();
//set all to the first value
foreach (RepeaterItem rptItem in OptionsList.Items)
{
DropDownList OptionChoices = (DropDownList)rptItem.FindControl("OptionChoices");
OptionChoices.SelectedIndex = 1;
}
TemplatesList.DataSource = GetProductTemplateFields();
TemplatesList.DataBind();
KitsList.DataSource = GetProductKitComponents();
KitsList.DataBind();
}
if (!Page.IsPostBack)
{
if (_Product.MSRP != 0)
{
salePrice.Visible = true;
RetailPrice.Text = _Product.MSRP.ToString("$0.00");
}
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("CatTable");
ResultTable.Columns.Add("OptionID", Type.GetType("System.String"));
ResultTable.Columns.Add("OptionName", Type.GetType("System.String"));
ResultTable.Columns.Add("LinkHeader", Type.GetType("System.String"));
foreach (ProductOption PhOpt in _Product.ProductOptions)
{
string MasterList = GetProductMaster(_ProductId, PhOpt.OptionId);
string PerFootVal = "";
string LinkHeader = "";
string DefaultOption = "no";
string PrefinishMin = "0";
bool VisPlaceholder = true;
ProductDisplayHelper.TestForVariantDependency(ref SlaveHide, _ProductId, PhOpt, ref PrefinishMin, ref PerFootVal, ref LinkHeader, ref VisPlaceholder, ref HasDefault, ref DefaultOption);
if (PrefinishMin == "")
PrefinishMin = "0";
DataRow dr = ResultTable.NewRow();
dr["OptionID"] = PhOpt.OptionId + ":" + MasterList + ":" + PerFootVal + ":" + DefaultOption + ":" + PrefinishMin;
Option _Option = OptionDataSource.Load(PhOpt.OptionId);
dr["OptionName"] = _Option.Name;
dr["LinkHeader"] = LinkHeader;
ResultTable.Rows.Add(dr);
}
//Bind the data to the Repeater
ItemOptions.DataSource = ds;
ItemOptions.DataMember = "CatTable";
ItemOptions.DataBind();
//determine if buttons show
if (ItemOptions.Items.Count == 0)
{
ShowAddToBasket(1);
resetBtn.Visible = true;
}
else
{
HideAddToBasket(3);
}
if (Request.QueryString["Action"] != null)
{
ShowAddToBasket(1);
SetDllAssociation(false);
}
ShowHideDrops();
}
}
private void HideAddToBasket(int Location)
{
AddToBasketButton.Visible = false;
AddToWishlistButton.Visible = false;
resetBtn.Visible = false;
if (Request.QueryString["Action"] == null)
{
SelectAll.Visible = true;
WishGray.Visible = true;
if (Request.QueryString["OrderItemID"] == null)
BasketGray.Visible = true;
else
UpdateButton.Visible = false;
}
else
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
}
}
private void ShowAddToBasket(int place)
{
resetBtn.Visible = true;
if (Request.QueryString["Action"] != null)
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
else
{
UpdateButton.Visible = false;
SelectAll.Visible = false;
WishGray.Visible = false;
BasketGray.Visible = false;
if (Request.QueryString["OrderItemID"] == null)
{
AddToBasketButton.Visible = true;
resetBtn.Visible = true;
AddToWishlistButton.Visible = true;
}
else
{
UpdateButton.Visible = true;
AddToBasketButton.Visible = false;
}
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
resetBtn.Visible = true;
}
}
protected void OptionChoices_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
if (ddl != null)
{
//bb5.Text = "ddl !=null<br />"; works
List<OptionChoiceItem> ds = (List<OptionChoiceItem>)ddl.DataSource;
if (ds != null && ds.Count > 0)
{
int optionId = ds[0].OptionId;
Option opt = OptionDataSource.Load(optionId);
ShowAddToBasket(4);
OptionChoiceItem oci = ds.FirstOrDefault<OptionChoiceItem>(c => c.Selected);
if (oci != null)
{
ListItem item = ddl.Items.FindByValue(oci.ChoiceId.ToString());
if (item != null)
{
ddl.ClearSelection();
item.Selected = true;
}
}
if (opt != null && !opt.ShowThumbnails)
{
if (!_OptionDropDownIds.Contains(optionId))
{
// bb5.Text = "!_OptionDropDownIds.Contains(optionId)<br />"; works
_OptionDropDownIds.Add(optionId, ddl.UniqueID);
}
if (_SelectedOptionChoices.ContainsKey(optionId))
{
ListItem selectedItem = ddl.Items.FindByValue(_SelectedOptionChoices[optionId].ToString());
if (selectedItem != null)
{
ddl.ClearSelection();
selectedItem.Selected = true;
//bb5.Text = "true: " + selectedItem.Selected.ToString()+"<br />"; doesn't work
}
}
StringBuilder imageScript = new StringBuilder();
imageScript.Append("<script type=\"text/javascript\">\n");
imageScript.Append(" var " + ddl.ClientID + "_Images = {};\n");
foreach (OptionChoice choice in opt.Choices)
{
if (!string.IsNullOrEmpty(choice.ImageUrl))
{
imageScript.Append(" " + ddl.ClientID + "_Images[" + choice.Id.ToString() + "] = '" + this.Page.ResolveUrl(choice.ImageUrl) + "';\n");
}
}
imageScript.Append("</script>\n");
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), ddl.ClientID, imageScript.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), ddl.ClientID, imageScript.ToString());
}
}
}
ddl.Attributes.Add("onChange", "OptionSelectionChanged('" + ddl.ClientID + "');");
}
}
protected Dictionary<int, int> GetSelectedOptionChoices()
{
HttpRequest request = HttpContext.Current.Request;
Dictionary<int, int> selectedChoices = new Dictionary<int, int>();
if (Page.IsPostBack)
{
foreach (int key in _OptionDropDownIds.Keys)
{
string value = (string)_OptionDropDownIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} DropDownId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
foreach (int key in _OptionPickerIds.Keys)
{
string value = (string)_OptionPickerIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} PickerId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
}
else
{
string optionList = Request.QueryString["Options"];
ShowAddToBasket(2);
if (!string.IsNullOrEmpty(optionList))
{
string[] optionChoices = optionList.Split(',');
if (optionChoices != null)
{
foreach (string optionChoice in optionChoices)
{
OptionChoice choice = OptionChoiceDataSource.Load(AlwaysConvert.ToInt(optionChoice));
if (choice != null)
{
_SelectedOptionChoices.Add(choice.OptionId, choice.Id);
}
}
return _SelectedOptionChoices;
}
}
}
return selectedChoices;
}
protected void SetDDLs(object sender, EventArgs e)
{
bool isRandom = false;
if (LengthDDL.Text != "")
isRandom = true;
SetDllAssociation(isRandom);
}
Try accessing the values in the Page_Load event. I don't believe the values are bound yet in Page_Init

C# Conditional Pricing issue (+=)

I have some code here:
(It basically checks if a product is a kit product or not then applys the New Price with the Price Modification)
if (!newItem.m_IsAKit)
{
NewPR = AppLogic.DetermineLevelPrice(newItem.m_VariantID, m_ThisCustomer.CustomerLevelID, out IsOnSale);
Decimal PrMod = AppLogic.GetColorAndSizePriceDelta(DB.RSField(rs, "ChosenColor"), DB.RSField(rs, "ChosenSize"), DB.RSFieldInt(rs, "TaxClassID"), ThisCustomer, true, false);
if (PrMod != System.Decimal.Zero)
{
NewPR += PrMod;
}
}
else
{
NewPR = DB.RSFieldDecimal(rs, "ProductPrice");
if (LevelDiscountPercent != 0.0M)
{
NewPR = AppLogic.GetKitTotalPrice(m_ThisCustomer.CustomerID, m_ThisCustomer.CustomerLevelID, newItem.m_ProductID, newItem.m_VariantID, newItem.m_ShoppingCartRecordID);
}
}
I have a product which IS a kit product so i am refering to the code after the else statement.
I need to apply NewPr += PrMod.
NewPr = 22
PrMod = 5
I have tried adding this code:
Decimal PrMod = AppLogic.GetColorAndSizePriceDelta(DB.RSField(rs, "ChosenColor"), DB.RSField(rs, "ChosenSize"), DB.RSFieldInt(rs, "TaxClassID"), ThisCustomer, true, false);
if (PrMod != System.Decimal.Zero)
{
NewPR += PrMod;
}
But during debugging the PrMod doesnt seem to hold a value.
Can you help point me in the right direction?
Thanks
I have the following method but i cant seem to see where the problem is. When the product IS a kit product it works fine.
static public decimal GetColorAndSizePriceDelta(String ChosenColor, String ChosenSize, int TaxClassID, Customer ThisCustomer, bool WithDiscount, bool WithVAT)
{
bool VATEnabled = AppLogic.ProductIsMLExpress() == false && AppLogic.AppConfigBool("VAT.Enabled");
bool VATOn = (VATEnabled && ThisCustomer.VATSettingReconciled == VATSettingEnum.ShowPricesInclusiveOfVAT);
decimal CustLevelDiscountPct = 1.0M;
decimal price = System.Decimal.Zero;
String ColorPriceModifier = String.Empty;
String SizePriceModifier = String.Empty;
if (ThisCustomer.CustomerLevelID > 0 && WithDiscount)
{
decimal LevelDiscountPercent = System.Decimal.Zero;
using (SqlConnection dbconn = new SqlConnection(DB.GetDBConn()))
{
dbconn.Open();
string sSql = string.Format("select LevelDiscountPercent from CustomerLevel with (NOLOCK) where CustomerLevelID={0}", ThisCustomer.CustomerLevelID);
using (IDataReader rs = DB.GetRS(sSql, dbconn))
{
if (rs.Read())
{
LevelDiscountPercent = DB.RSFieldDecimal(rs, "LevelDiscountPercent");
}
}
}
if (LevelDiscountPercent != System.Decimal.Zero)
{
CustLevelDiscountPct -= LevelDiscountPercent / 100.0M;
}
}
if (ChosenColor.IndexOf("[") != -1)
{
int i1 = ChosenColor.IndexOf("[");
int i2 = ChosenColor.IndexOf("]");
if (i1 != -1 && i2 != -1)
{
ColorPriceModifier = ChosenColor.Substring(i1 + 1, i2 - i1 - 1);
}
}
if (ChosenSize.IndexOf("[") != -1)
{
int i1 = ChosenSize.IndexOf("[");
int i2 = ChosenSize.IndexOf("]");
if (i1 != -1 && i2 != -1)
{
SizePriceModifier = ChosenSize.Substring(i1 + 1, i2 - i1 - 1);
}
}
if (ColorPriceModifier.Length != 0)
{
price += Localization.ParseDBDecimal(ColorPriceModifier);
}
if (SizePriceModifier.Length != 0)
{
price += Localization.ParseDBDecimal(SizePriceModifier);
}
if (VATOn && WithVAT)
{
decimal TaxRate = 0.0M;
TaxRate = ThisCustomer.TaxRate(TaxClassID);
Decimal TaxMultiplier = (1.0M + (TaxRate / 100.00M));
price = TaxMultiplier * price;
}
return price * CustLevelDiscountPct;
}
Why dont you initialize the varaible PrMod tp Zero
You need to debbug AppLogic.GetColorAndSizePriceDelta method because if the return type is Decimal, it should atleast return a deafult value as 0.0M

Categories