Select Tab on form initialization - c#

This is stupid and I did it before, but now its not working and I cant find a solution online. I have a form and one tab page. on the tab page there are 4 tabs. how can I make the 4th tab selected when the form loads? I also want to use the tab's text, or name, and not the tab index.

Just select the tab in your form constructor. The boilerplate code is:
public Form1() {
InitializeComponent();
tabControl1.SelectedTab = tabPage4;
// or:
tabControl1.SelectedIndex = 3;
}

You need to loop through the tabs to find the one you want, then set the TabControl's SelectedTab property.

Related

How to show an ErrorProvider error icon next to a TabPage header?

Edit:
This is not a duplicate of Icons in TabControl C# - How?. The question there is about adding icons to tab pages. Here it is about how the change the error provider error icon position to be inside the header instead of to the right of the tab page itself. Also, the error provider error icon has the functionality that when you hover the mouse on it, you see the error text, which you do not see if you simply add an icon to the header.
I have a form with a TabControl. The form has also an ErrorProvider. When I try to use the following code:
errorProvider1.SetError(tabPage1, "error");
The error icon is shown to the right of the tab page, and it is cut-off by the tab control itself:
I would like the icon to be shown next to the tab page header. Something like this (made with Photoshop):
I do not know where to start, or how to approach this.
Edit:
I have a class responsible for adding errors to a control, and showing them using an error provider. This class is used for TextBoxes, NumericUpDowns etc. I would like to use it also for TabPages. The problem is that when I use it for tab pages I get the result shown above. The trick of adding an error icon to the header using an ImageList and then add a tooltip is not good, because it is specific to tab pages, and I cannot implement it in my class which is general to all controls. So I really need to change the settings of the tab page so when I use errorProvider.SetError(...) it is shown in the header.
ErrorProvider shows error icon of the TabPage in tab page's client area.
By playing with IconAlignment or IconPadding, you can show error icon of TabControl on one of the tab pages' headers, but it's error icon for the whole TabControl.
In a real application each of the tab pages can contain controls which are not valid and you may want to show the validation icon on tab pages not for the tab control.
My suggestion is using tab page icon by setting ImageList containing the error icon as image list of the TabControl and by setting ImageIndex of the TabPage, show or hide the image icon. This way you can show the error icon for every tab page which needs it:
Example
To setup the example, follow these steps:
Create a Form.
Drop a TabControl, an ErrorProvider and an ImageList on the Form.
Set ImageList property of tabControl1 to imageList1.
Drop two TextBox on tabPage1.
I assume, just for example, you are going to validate these two text box controls using Validating event. The key point is here. When you validate any control, check if it's hosted in a TabPage, check validity of all children of TabPage and set the error icon based on that:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.AutoValidate = AutoValidate.EnableAllowFocusChange;
imageList1.ColorDepth = ColorDepth.Depth32Bit;
imageList1.Images.Add(errorProvider1.Icon);
tabControl1.ImageList = imageList1;
textBox1.Validating += textBox_Validating;
textBox2.Validating += textBox_Validating;
}
private void textBox_Validating(object sender, CancelEventArgs e)
{
var textBox = (TextBox)sender;
if (string.IsNullOrEmpty(textBox.Text))
{
this.errorProvider1.SetError(textBox, "Value is required.");
e.Cancel = true;
}
else
this.errorProvider1.SetError(textBox, null);
var tabPage = textBox.Parent as TabPage;
if (tabPage != null)
ValidateTabPage(tabPage);
}
void ValidateTabPage(TabPage tabPage)
{
var tabIsValid = tabPage.Controls.Cast<Control>()
.All(x => string.IsNullOrEmpty(errorProvider1.GetError(x)));
if (tabIsValid)
tabPage.ImageIndex = -1;
else
tabPage.ImageIndex = 0;
}
You can do the following.
Rectangle rc = tabControl1.GetTabRect(0); // Replace with the index of Tab required
errorProvider1.SetIconPadding(tabControl1, -rc.Left-20);;
errorProvider1.SetError(tabControl1, "Error String");
You also need to set
errorProvider1.SetIconAlignment(tabControl1, ErrorIconAlignment.TopLeft);
Sample (With Second Tab Selected - based on comments),
You would need to prepend whitespace to your TabPage Text to ensure there is sufficient space for showing the icon
With Icon on Second Tab

refresh label text in another form after button click C#

i have 2 project in 1 solution and each project have 1 form. In form 1 i have label and button, and i want when i click on button it will show in form 2 labeltext in form 1.
my code in form 1:
WindowsFormsApplication1.Form1 layarForm1 = new WindowsFormsApplication1.Form1();
layarForm1.Show();
layarForm1.LabelText = no_antrian.Text;
//layarForm1.LabelText = this.Refresh();
form2(in other project but in same solutions, and i have reference to form 1):
public string LabelText
{
get
{
return this.ruang_1.Text;
}
set
{
this.ruang_1.Text = value;
}
}
my code work for first time but when i click button again it will show new form. is there any ways that label text in form 2 will refresh after button click. And i dont want to use dispose form because in form 2 i have video played that will start again if i use dispose() and show()
Two projects = 2 executable you need to use shared memory or named pipes to send the data across from one exe to another, or use winapi such as SendMessage once you get the window handle of the other window and the find the child window handle via EnumChildWindows.
Why not use the two forms in the same project?
The problem is every time the button is clicked, an instance of the form is created. You need to check whether the form is already open and if not create an instance, show the form and update the label.
If the form is already open, all you need to do is to update the label and set focus on the form.
You can use Application.OpenForms to iterate through all one forms and check whether the form is in that collection.
Something like
foreach (Form frm in WindowsFormsApplication1.OpenForms)
{
if (frm.Name == "MY_FORM_NAME") then
frm.LabelText = no_antrian.Text;
else
{
WindowsFormsApplication1.Form1 layarForm1 = new
WindowsFormsApplication1.Form1();
layarForm1.Show();
layarForm1.LabelText = no_antrian.Text;
}
}

Add tooltip to a dynamically created tabpage

I'm having a difficult time trying to work with tooltips.
I'm trying to add a tooltip with different text to each dynamically created tab in a tabcontrol.
It's important to note that this tab is created from a form that contains a docked form where the tabcontrol is in.
This is, a main Form with a docking area, in where I have docked a results form, which contains an - initially empty - tabcontrol.
When you start the application this results form doesnt exists, I also create it dynamically whenever the user press certains parts of the main form, each one created as a new tab in the results form tabcontrol.
This is how I generate the tabs:
generateResultForm();
TabPage newtp = new TabPage("Nuevo paciente")
_result.TabControl.TabPages.Add(newtp);
newtp.Name = setTabName("np");
Now, I've tried putting a tooltip in the results form, then tried to first generate the tooltip by adding below something like _result.ResultsTooltip.SetToolTip(newtp, "Creación de un nuevo paciente.");, which didn't work. Then, since once the tab is created, it becomes selected, I tried to add it in the results class by something like WorkareaTooltip.SetToolTip(tabControl.SelectedTab, "Cosas"); in the selectedindexchange event from the tabcontrol.
I don't think it would have been a great solution, but I don't know what else to try.
Of course the tabcontrol has its ShowToolTips property set to true.
If anyone could help me that'll be great.
Thanks for reading, and sorry if there are any language mistakes :)
//EDITED
This is the code i'm actually using (and doesn't work)
TabPage newtp = new TabPage("Nuevo paciente");
_workareaform.TabControl.TabPages.Add(newtp);
newtp.Name = "np";
var tooltip = new ToolTip();
tooltip.SetToolTip(newtp, "Creación de un nuevo paciente.");
Now, it doesn't work, might be because of the whole configuration.
Just to be clear, this tab is in a TabControl which is in a Form docked into a dockContainer in another Form.
Here is an image if it.
http://i.imgur.com/fVz6e06.png
As you can see, no tooltip at all.
Have you tried setting ToolTipText property as shown below?. It worked for me.
_result.TabControl.ShowToolTips = true;
TabPage newtp = new TabPage("Nuevo paciente");
_result.TabControl.TabPages.Add(newtp);
newtp.ToolTipText = "this is tooltip";
If you're working with another form you need to reference the other form TabControl
In this sample I create a Form1 instance (with TabControl in it) from my Form2 and then add page and tooltip.
private void Form2_Load(object sender, EventArgs e)
{
//instantiate another form
var f1 = new Form1();
//find tabcontrol on new form
var tc = (TabControl) f1.Controls["tabControl1"];
//create page
TabPage newtp = new TabPage("Nuevo paciente");
newtp.Name = "Paciente1";
tc.TabPages.Add(newtp);
//add tooltip
var tt1 = new ToolTip();
tt1.SetToolTip(newtp, "paciente 1 tooltip");
//show other form
f1.Show();
}

How to close tab page on tabcontrol by tab page's name

In c# how can I destroy a tab on a tab control by targeting it's name? I've a tab named "Hello!" and I'd like to close it programatically. There's no guarantee that it will be the selected tab at the time.
The TabControl class provides a TabPages property that returns a TabPageCollection containing all of the TabPages in the control.
So you can use the Item property to retrieve the TabPage with the specified name.
For example, if the tab page you want is named "Hello!", you would write:
var tabPage = myTabControl.TabPages["Hello!"];
To remove the TabPage from the control, use the RemoveByKey method:
myTabControl.TabPages.RemoveByKey("Hello!");
Of course, in order for this to work, you'll need to make sure that you've set the keys of your TabPages to match the caption text they display.
You can try something like this:
for (int i = tabControl1.TabPages.Count - 1; i >= 0; i--) {
if (tabControl1.TabPages[i].Text == "Hello!")
tabControl1.TabPages[i].Dispose();
}
I'm assuming you meant the "Text" of the TabPage, since "Hello!" wouldn't be a valid name for a control.
Note: this code will dispose of any TabPage that says "Hello!"

Programmatically change the tab order

How do I programmatically reorder the tabs in a TabControl? I need to sort the tabs depending on some conditions.
If it's possible to do the reordering through the designer, i guess we must be able to do it through code at runtime too.
Create a new Form.
Create a new TabControl.
Notice it has two TabPage controls, and TabPage1 is the first tab.
In form's Load event, add
this.TabControl1.TabPages.Remove(this.TabPage2)
this.TabControl1.TabPages.Insert(0, this.TabPage2)
Run the form.
Notice TabPage2 is now the first tab.
Note that if you fail to remove the tab page, it will still show at its old location. In other words, you will have two tabs of the same tab page.
You have to redefine your tab page collection, in order to change the index of your tab pages.
The following lines of code can also do the trick, this kind of solution also works for other kind of data that has no direct way of sorting:
- convert to a list
- sort the list
- put it back
public static void Sort(TabControl tabControl)
{
var tabList = tabControl.TabPages.Cast<TabPage>().ToList();
tabList.Sort(new TabPageComparer());
tabControl.TabPages.Clear();
tabControl.TabPages.AddRange(tabList.ToArray());
}
public class TabPageComparer : IComparer<TabPage>
{
public int Compare(TabPage x, TabPage y)
{
return string.Compare(x.Text, y.Text);
}
}
thelost is right. Below is a quick sample code.
I have a tab control with 2 tabs (tabpage1, tabpag2)
Then I declare two tabpages and store the existing tabs in the tabcontrol in it.
abPage tbp1 = new TabPage();
TabPage tbp2 = new TabPage();
tbp1 = tabControl1.TabPages[0];
tbp2 = tabControl1.TabPages[1];
Then on a button click I removed the tabs using
tabControl1.TabPages.Remove(tabControl1.TabPages[0]);
Now if you want to change the order then you will have top add it to the tab in that order
//Order changed
tabControl1.TabPages.Add(tbp2);
tabControl1.TabPages.Add(tbp1);
Note: This is untested quick code.
Go inside Designer.cs file
There you will find
/// [Your TabControl Name]
yourTabControl.Controls.Add(yourPage1);
yourTabControl.Controls.Add(yourPage2);
yourTabControl.Controls.Add(yourPage3);
The adding order is your tabpages' order in the tabcontrol. Change the order how you wish. Remove and Add functions of TabControl.Controls will help you as Shoban answered.
try this after Initilizacomponent(). this code will give you freedom to change it programmatically in .cs file.
this.tabReceive.Controls.Remove(this.metroTabPage4);
this.tabReceive.Controls.Remove(this.metroTabPage5);
this.tabReceive.Controls.Add(this.metroTabPage4);
this.tabReceive.Controls.Add(this.metroTabPage5);
Sometimes I have tabControls with several tabPages. At runtime tabPages are made invisible (by removing them) an added later again.
After this the tabPages may be in wrong order. I use this code to redorder them again:
public void ReorderTabPages()
{
// Demo code to reorder tabControl with tabPages
// where some tabPages may be unwanted at the moment
// caution: events like "SelectedIndexChanged" does fire!
// List of wanted tab pages
List<TabPage> wantedTabPages = new List<TabPage>();
// remember the current selected tab
TabPage currentTabPage = this.tabControl.SelectedTab;
// check if all possibly active tabs are currently visible
// check it in the order they should be displayed
// after that they are in the correct order in "wantedTabPages"
if (this.tabControl.TabPages.IndexOf(this.tabPage_01) >= 0)
wantedTabPages.Add(this.tabPage_01);
if (this.tabControl.TabPages.IndexOf(this.tabPage_02) >= 0)
wantedTabPages.Add(this.tabPage_02);
if (this.tabControl.TabPages.IndexOf(this.tabPage_03) >= 0)
wantedTabPages.Add(this.tabPage_03);
if (this.tabControl.TabPages.IndexOf(this.tabPage_04) >= 0)
wantedTabPages.Add(this.tabPage_04);
this.tabControl.SuspendLayout();
// remove all currently visible tab pages
for (int i = this.tabControl.TabPages.Count - 1; i >= 0; i--)
this.tabControl.TabPages.RemoveAt(i);
// add the tabPages in the correct order
foreach (var wantedPage in wantedTabPages)
this.tabControl.TabPages.Add(wantedPage);
// restore the currently selected tabPage
this.tabControl.SelectedTab = currentTabPage;
this.tabControl.ResumeLayout();
}

Categories