Disabling a ToolStripMenuItem vs. disabling a MenuStrip.Item - c#

When a user logs into my application, there are some menu items that I don't want every user to see. So I would like to either disable or make invisible the menu item. For example fileToolStripMenuItem is the first item in my menuStrip, when I try:
fileToolStripMenuItem.Enabled = false; - this does not work
menuStrip.Items[0].Enabled = false; - this does work
Can anyone enlighten me as to the difference here?
Also, I would like to be able to disable a drop down item from one of the menu items, but I cannot do that either.
Here's the code:
public Form1()
{
InitializeComponent();
// bunch of other code here
if (!login.ValidatedUser)
{
menuStrip1.Items[0].Visible = false; // this works
toolsToolStripMenuItem.Visible = false; // this does not
btnStartResourceManager.Enabled = false;
listAvailableSizes.Enabled = true;
panelPicSet.Enabled = true;
}
}

fileToolStripMenuItem.Enabled = false; works as expected. I think you trying to disable it before InitializeComponent(); call.
public form()
{
InitializeComponent();
fileToolStripMenuItem.Enabled = false;//disables all file menu
saveasToolStripMenuItem.Enabled = false; //disables save as menu item in file menu list
}

Use the specific name of your menu item and change its Visible property. i.e.
private void toggleToolStripMenuItem_Click(object sender, EventArgs e)
{
if (shown)
saveToolStripMenuItem.Visible = false;
else
saveToolStripMenuItem.Visible = true;
shown = !shown;
}

For Sub Items, just right click on the item and see its name In Design Section in Properties Window. In my case below addNewToolStripMenuItem1.
public Form()
{
InitializeComponent();
menuStrip1.Items[1].Visible = false; // For Main Item // Bold Letters
addNewToolStripMenuItem1.Visible = false; //For Sub Items
}

Related

Xamarin Navigation Bar Hide Hamburger Menu

I need to hide the hamburger menu on certain pages but still display information in then navbar. I don’t know of any way to accomplish this.
Also, I need the navbar to stay fixed to the top of the screen but it’s getting cut off when the keyboard pops up.
How can I go about this?
FlyoutPage.ShouldShowToolbarButton method is used to determine whether to show/hide hamburger icon , and it is triggered every time when selecting pages.
We can define a bool field ,change its value when directing to specific pages.
FlyoutPage
public override bool ShouldShowToolbarButton()
{
return showIcon;
}
private bool showIcon = true;
private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as FlyoutPage1FlyoutMenuItem;
if (item == null)
return;
var page = (Page)Activator.CreateInstance(item.TargetType);
page.Title = item.Title;
Detail = new NavigationPage(page);
IsPresented = false;
FlyoutPage.ListView.SelectedItem = null;
//add this logic
showIcon = (item.Id == 1) ? false : true; //only the second page do not show hamburger icon
}

Can't see Loaded, Initialized, Visible window

Simplified version
ParentWindow.ShowDialog()
Click default/Bring Up Child Window button in ParentWindow
Click event handler for default/Bring Up Child Window button does ParentWindow.Hide()
ChildWindow.ShowDialog()
Click ChildWindow's cancel/Go Back button
ParentWindow.Visibility = Visibility.Visible
ParentWindow is nowhere to be found.
I checked, and ParentWindow returns true for IsInitialized, IsLoaded, and IsVisible. I also Alt-Tabbed my way through all my windows to look for it - it's not hiding under anything.
Why can't I see ParentWindow anywhere?
Full version
parseSettingsWindow.ShowDialog()
Click default/Bring Up Fix Selector button in parseSettingsWindow
Click event handler for default/Bring Up Fix Selector button does:
a. ParentWindow.Hide()
b. parseSettingsWindow.GoToNextWindow flag set to true (Next window is Fix Selector)
while loop does fixSelector.ShowDialog() because it's not yet loaded
Click ChildWindow's cancel/Go Back button
while loop is entered again, goes to `case "Parse Settings" section
parseSettingsWindow.Visibility = Visibility.Visible
parseSettingsWindow is nowhere to be found
I checked, and parseSettingsWindow returns true for IsInitialized, IsLoaded, and IsVisible in the Immediate Window when pausing execution on the break; line of the "Parse Settings" while loop section. I also Alt-Tabbed my way through all my windows to look for it - it's not hiding under anything.
Why can't I see parseSettingsWindow anywhere?
Main class
public static bool UserPromptedSettingsWereWrittenToModel(ref Model model, ref ActiveFixes activeFixes, ref ActiveReports activeReports)
{
var viewModel = new ViewModel();
var parseSettingsWindow = new ViewPlusViewModel.ParseSettings();
parseSettingsWindow.InitializeComponent();
var fixSelector = new ViewPlusViewModel.FixSelector(viewModel);
fixSelector.InitializeComponent();
var seeAllFixesReports = new ViewPlusViewModel.SeeAllFixesReports();
seeAllFixesReports.InitializeComponent();
parseSettingsWindow.ShowDialog();
var nextWindowToOpen = "Fix Selector";
while (parseSettingsWindow.GoToNextWindow == true && fixSelector.GoToNextWindow == false)
{
switch(nextWindowToOpen)
{
case "Fix Selector":
if (fixSelector.IsLoaded)
{
fixSelector.Visibility = Visibility.Visible;
}
else
{
fixSelector.ShowDialog();
}
nextWindowToOpen = "Parse Settings";
break;
case "Parse Settings":
parseSettingsWindow.GoToNextWindow = false;
parseSettingsWindow.Visibility = Visibility.Visible;
nextWindowToOpen = "Fix Selector";
break;
}
}
if (parseSettingsWindow.GoToNextWindow == false)
{
parseSettingsWindow.Close();
if (fixSelector.IsLoaded) fixSelector.Close();
if (seeAllFixesReports.IsLoaded) { seeAllFixesReports.Close(); }
return false;
}
parseSettingsWindow.Close();
fixSelector.Close();
if (seeAllFixesReports.IsLoaded) { seeAllFixesReports.Close(); }
return true;
}
ParseSettingsWindow.cs
private void GoToNextWindow_Click(object sender, RoutedEventArgs e)
{
this.GoToNextWindow = true;
this.Hide();
}
You can't bring a hidden .ShowDialog() window back again via Window.Visibility. You need to use .ShowDialog() on it again. In addition, any buttons given the IsCancel = True property will no longer have that functionality even when using ShowDialog() again, so presses on that button will need to be handled manually.

How to change opacity of certain number of button(x) while not writing them out one by one? (C#)

I don't think I asked the question quite well, so here's an explanation. I want to create buttons invisibly when Form1 loads, instead of changing them each individually, is there a way to change all of them with fewer lines of code?
Note: I do not want to change all buttons, only a certain range of them.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Visible = true;
button2.Visible = true;
button3.Visible = true;
button4.Visible = true;
button5.Visible = true;
button6.Visible = true;
button7.Visible = true;
}
By that I mean, is it possible to change those buttons visibility to true without writing them out one by one?
button1 - button7.Visible = true;
something like this..
If you're trying to change only a certain range of buttons, assuming they're all simply called button[x] you could create a function like this:
private void toggleButtons(int start, int end, bool trueOrFalse)
{
for(int x=start; x <= end; x++)
{
this.Controls.OfType<Button>().Where(b => b.Name == "button" + x.ToString()).SingleOrDefault().Visible = trueOrFalse;
}
}
Then you can call it like this using (startNo,endNo,true/false for visibility)
toggleButtons(1, 7, false);
You can use the Controls property to get all of the controls on a form. For example:
foreach(var button in this.Controls.OfType<Button>())
{
button.Visible = false;
}
If you want to change visibility of all buttons in the form, you could do so.
foreach(var button in Controls.OfType<Button>())
{
button.Visible = false; // or true, depending what you want to set
}
If you do no want to change visibility of all Buttons in Form and if you need to filter buttons, based on some criteria, you could do so as well.
For example, if you want to filter buttons whose names starts with "specialButton",
foreach(var button in this.Controls.OfType<Button>().Where(x=>x.Name.StartsWith("specialButton")))
{
button.Visible = false;
}
Similarly, you can filter based on other properties as well.
Another option is to enlist the buttons that needs to be changed in a list. For example, if you need to change only button1 and button2 from a form comprising of 10 buttons, you could
var list = new[] { button1, button2 };
foreach (var item in list)
{
item.Visible = false;
}

How to check a box in CheckedListBox while the items in the list are custom objects in a C# window form application?

I am creating an "export to excel" windows form in c#.
The class contains a CheckedListBox and a "check all" button.
When clicking on the button I want to check all the items in the list in case that at least one checkbox is not checked or uncheck all the checkboxes in case they are all already checked.
I added a small complication, the list of the items is a list of custom objects (see private class inside): "ObjectToExport" class.
public partial class ExcelCustomExportForm : Form
{
private class ObjectToExport
{
private readonly IExcelExportable _form;
public ObjectToExport(IExcelExportable form)
{
_form = form;
}
public override string ToString()
{
return $"{_form.FormName} ({_form.CreatedDate.ToShortDateString()} {_form.CreatedDate.ToShortTimeString()})";
}
}
// each form in the list contains a gridview which will be exported to excel
public ExcelCustomExportForm(List<IExcelExportable> forms)
{
InitializeComponent();
Init(forms);
}
private void Init(List<IExcelExportable> forms)
{
foreach (IExcelExportable form in forms)
{
// Checked List Box creation
FormsCheckedListBox.Items.Add(new ObjectToExport(form));
}
}
private void CheckAllButton_Click(object sender, EventArgs e)
{
// checking if all the items in the list are checked
var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);
CheckItems(!isAllChecked);
}
private void CheckItems(bool checkAll)
{
if (checkAll)
{
CheckAllButton.Text = "Uncheck All";
}
else
{
CheckAllButton.Text = "Check All";
}
FormsCheckedListBox.CheckedItems.OfType<CheckBox>().ToList().ForEach(c => c.Checked = checkAll);
}
}
The problem is that the following line returns true even if not check box is checked:
var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);
Similar issue with the following line, if checkAll is true, no check box is checked:
FormsCheckedListBox.CheckedItems.OfType<CheckBox>().ToList().ForEach(c => c.Checked = checkAll);
What is the correct way to fix those two lines of code?
Your Problem begins here.
FormsCheckedListBox.Items.Add(new ObjectToExport(form));
and
var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);
You are adding instances of 'ObjectToExport' to the FormsCheckedListBox, but while filtering, you are checking filtering with CheckBox.
This means, your filtered query always return empty, and query never reaches All. This can be demonstrated with following example.
var list = new [] { 1,2,3,4};
var result = list.OfType<string>().All(x=> {Console.WriteLine("Inside All"); return false;});
The result of above would be True, and it would never print the "Inside All" text. This is what is happening with your queries.
You can find if any of the checkbox is checked using
var ifAnyChecked = checkedListBox1.CheckedItems.Count !=0;
To change state, you could do the following.
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
// Do something
}
}

How do I add form on tab control in c#

I have a form page with text boxes and data grid view and other forms that contain a tab control. I want to add the first form tab in the second form. I tried to write the code for the form to appear but it is larger than the tab container and doesn't fit. Only half of the form appears.
This is my code:
private void tcMainPage_SelectedIndexChanged(object sender, EventArgs e)
{
if (tcMainPage.SelectedIndex == 0)
{
GTOWN.PrintingPage BookInfo = new PrintingPage();
BookInfo.TopLevel = false;
BookInfo.FormBorderStyle = FormBorderStyle.None;
BookInfo.Dock = DockStyle.Fill;
tpSearch.Controls.Add(BookInfo);
BookInfo.Show();
}
}
this is the form
and that is what appears
Set your main FORM as a Container.
yourForm.IsMdiContainer = true;
Then add the child form to the tabPage:
private void tcMainPage_SelectedIndexChanged(object sender, EventArgs e)
{
if (tcMainPage.SelectedIndex == 0)
{
PrintingPage newFrm = new PrintingPage
{
MdiParent = this,
// This set the form parent as the tabClicked
Parent = tcMainPage.TabPages[0]
};
newFrm.Show();
}
}
my tab form work good in the same code
thank you all my code was correct but the problem was in tab property i deleted the tab and add another one and the code is working now
thank you
I face this issue and I create this if may help
public void addform(TabPage tp, Form f)
{
f.TopLevel = false;
//no border if needed
f.FormBorderStyle = FormBorderStyle.None;
f.AutoScaleMode = AutoScaleMode.Dpi;
if (!tp.Controls.Contains(f))
{
tp.Controls.Add(f);
f.Dock = DockStyle.Fill;
f.Show();
Refresh();
}
Refresh();
}
Forms are top-most objects and cannot be placed inside of other containers.
You may want to refactor your code so that the items on your Form are on a UserControl instead. At that point you can then add that UserControl to both a Form and a TabControl
public UserControl myControl(){ /* copy your current view code here */}
public Form myForm(){
Controls.Add(new myControl());
}
public Form myTabbedForm(){
var tabControl = new TabControl();
var page1 = new TabPage();
page1.Controls.Add(new myControl());
tabControl.TabPages.Add(page1);
this.Controls.Add(tabControl);
}

Categories