Data list binding with some text and validating datalist - c#

I am using this code for datalist validation.
I am binding the image in datalist after that i am trying to give the caption to each image suppose there is 3 image is datalist then for the first image i am able to give but for the other one i am unable to.. i think there is some error in conditions help me in this. code is following..
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images and captions for each image";
msgError.Focus();
}
else
AddCaption();
bool IsEmptyCaption = false;
Hashtable htble = (Hashtable)ViewState["imgIdCapHtbl"];
List<int> imgIds = (List<int>)ViewState["imgIds"];
if (htble != null && imgIds != null)
{
foreach (int id in imgIds)
{
if (htble[id] == "")
{
IsEmptyCaption = true;
break;
}
else
IsEmptyCaption = false;
}
}
else
IsEmptyCaption = true;
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images";
msgError.Focus();
}
else if (IsEmptyCaption)
{
msgError.Text = "Please add captions for each image";
msgError.Focus();
}
else
{
Args[0] = "Section1";
Args[1] = "";
Args[2] = FindingId.ToString();
Args[3] = FindingIdIns.ToString();
AnotherHeading = false;
//AddCaption();
objGetBaseCase.UpdateImageCaptions((Hashtable)ViewState["imgIdCapHtbl"]);
if (AddFindingsViewerDetails != null)
AddFindingsViewerDetails(Args, e);
ClearImages();
PageContent pg = (PageContent)this.Parent.FindControl("PageContent");
if (pg != null)
pg.LoadWorkflowForCase();
if (Display != null)
Display(null, EventArgs.Empty);
}

if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images and captions for each image";
msgError.Focus();
}
else
AddCaption();
bool IsEmptyCaption = false;
Hashtable htble = (Hashtable)ViewState["imgIdCapHtbl"];
List<int> imgIds = (List<int>)ViewState["imgIds"];
if (htble != null && imgIds != null)
{
foreach (int id in imgIds)
{
if (htble[id] == "" || htble[id] == null) // New code implemented here
{
IsEmptyCaption = true;
break;
}
else
IsEmptyCaption = false;
}
}
else
IsEmptyCaption = true;
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images";
msgError.Focus();
}
else if (IsEmptyCaption)
{
msgError.Text = "Please add captions for each image";
msgError.Focus();
}
else
{
Args[0] = "Section1";
Args[1] = "";
Args[2] = FindingId.ToString();
Args[3] = FindingIdIns.ToString();
AnotherHeading = false;
//AddCaption();
objGetBaseCase.UpdateImageCaptions((Hashtable)ViewState["imgIdCapHtbl"]);
if (AddFindingsViewerDetails != null)
AddFindingsViewerDetails(Args, e);
ClearImages();
PageContent pg = (PageContent)this.Parent.FindControl("PageContent");
if (pg != null)
pg.LoadWorkflowForCase();
if (Display != null)
Display(null, EventArgs.Empty);
}
Now its working fine...

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.

How to create complex filter for DataGrid WPF

I want to create filrer for 4 fields. But I get too many code.
I need filter when just one field choosen or a few (2,3 or 4) fields at the same time. How to create logic for it?
My ugly code:
void ViewSource_Filter(object sender, FilterEventArgs e)
{
if (e.Item is Event evnt)
{
bool selectedModel = filterEventsControl.ComboBoxModels.SelectedIndex != 0 && filterEventsControl.ComboBoxModels.SelectedItem != null;
bool selectedIp = filterEventsControl.ComboBoxIPs.SelectedIndex != 0 && filterEventsControl.ComboBoxIPs.SelectedItem != null;
bool selectedParameter = filterEventsControl.ComboBoxParameters.SelectedIndex != 0 && filterEventsControl.ComboBoxParameters.SelectedItem != null;
bool selectedStatus = filterEventsControl.ComboBoxStatus.SelectedIndex != 0 && filterEventsControl.ComboBoxStatus.SelectedItem != null;
if (selectedModel && !selectedIp && !selectedParameter && !selectedStatus)
{
var model = filterEventsControl.ComboBoxModels.SelectedItem.ToString();
if (evnt.DeviceName == model)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
else if (selectedModel && selectedIp && !selectedParameter && !selectedStatus)
{
var model = filterEventsControl.ComboBoxModels.SelectedItem.ToString();
var ip = filterEventsControl.ComboBoxIPs.SelectedItem.ToString();
if (evnt.DeviceName == model && evnt.Ip == ip)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
...
else
{
e.Accepted = true;
}
}
}
It can be something like this:
bool FilterByName(Event evnt)
{
var model = filterEventsControl.ComboBoxModels.SelectedItem?.ToString();
return evnt.DeviceName == model;
}
bool FilterByIp(Event evnt)
{
var ip = filterEventsControl.ComboBoxIPs.SelectedItem?.ToString();
return evnt.Ip == ip;
}
void ViewSource_Filter(object sender, FilterEventArgs e)
{
...
bool res = true;
if (selectedModel)
res = res && FilterByName();
if (selectedIp)
res = res && FilterByIp();
...
}

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

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

Hide/Show radio buttons on a questionnaire application

I am doing an assignment involving the creation of a simple Quiz type form application. However, whenever I run the program, only the first answer shows for a multiple question and I cannot for the life of me figure out why.
This is the contstructor:
MultipleChoice dlg =
new MultipleChoice(
new Question("What is the capital of Zimbabwe?",
new Answer("Paris", false),
new Answer("Washington D.C.", false),
new Answer("Harare", true),
new Answer("Cairo", false),
new Answer("N'Djamena", false)));
if (dlg.ShowDialog() == DialogResult.OK)
{
if (dlg.Correct) MessageBox.Show("You got something right!");
else MessageBox.Show("You couldn't be more wrong");
}
And this is the Question Form Code:
private Question Q;
public MultipleChoice (Question q)
{
Q = q;
InitializeComponent();
textPrompt.Text = Q.Prompt;
if (Q.A != null)
{
radioA.Text = Q.A.Prompt;
}
else radioA.Hide();
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide();
if (Q.C != null)
{
radioC.Text = Q.C.Prompt;
}
radioC.Hide();
if (Q.D != null)
{
radioD.Text = Q.D.Prompt;
}
radioD.Hide();
if (Q.E != null)
{
radioE.Text = Q.E.Prompt;
}
radioE.Hide();
}
public bool Correct
{
get
{
if (Q == null) return false;
if (Q.A != null && Q.A.Correct && radioA.Checked) return true;
if (Q.B != null && Q.B.Correct && radioB.Checked) return true;
if (Q.C != null && Q.C.Correct && radioC.Checked) return true;
if (Q.D != null && Q.D.Correct && radioD.Checked) return true;
if (Q.E != null && Q.E.Correct && radioE.Checked) return true;
return false;
}
}
Where have I gone wrong?
There is no else for any option after A:
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide(); //This is **always** going to be called - hiding radioB :)
Should be:
if (Q.B != null)
radioB.Text = Q.B.Prompt;
else
radioB.Hide();

Categories