Switching to a tab in TabControl using code - c#

I have a tabcontrol in my application that has several tabs in it.
I want to automatically switch to another tab when the "Next" button is pressed.
I cannot figure out how to change which tab is visible programmatically.
private void Next_Click(object sender, EventArgs e)
{
// Change to the next tab
tabControl1.???;
}

Use the TabControl.SelectedTab property. MSDN.
tabControl1.SelectedTab = anotherTab;
But you can also use the TabControl.SelectedIndex property. MSDN.
try
{
tabControl1.SelectedIndex += 1;
}
catch
{
//This prevents the ArgumentOutOfRangeException.
}

For this particular scenario you can use SelectedIndex property of the TabControl. This gives you an integer representing the index of the currently selected tab. Likewise you can set a tab as selected by setting an integer value to this property.
private void btnNext_Click(object sender, EventArgs e)
{
int currentTabIndex = tabControl1.SelectedIndex;
currentTabIndex++;
if (currentTabIndex < tabControl1.TabCount)
{
tabControl1.SelectedIndex = currentTabIndex;
}
else
{
btnNext.Enabled=false;
}
}

Related

C# WinForms contextmenu focus issue when textbox is added

In a C# WinForms application I need to create a ContextMenuStrip with dropdown and textbox:
private System.Windows.Forms.ContextMenuStrip ct1;
private void button_Click(object sender, EventArgs e)
{
var header = new ToolStripMenuItem("Header");
header.Enabled = false;
var options = new ToolStripMenuItem("Options");
for (int i = 0; i < 5; i++)
{
var checkoption = new ToolStripMenuItem("Check Me " + i + "!");
checkoption.CheckOnClick = true;
options.DropDownItems.Add(checkoption);
}
var txt = new ToolStripTextBox();
txt.Text = "changeme";
options.DropDownItems.Add(txt);
options.DropDown.Closing += DropDown_Closing;
ct1.Items.Clear();
ct1.Items.Add(header);
ct1.Items.Add(options);
ct1.Show(this, button.Left, button.Top);
}
private void DropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
e.Cancel = (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked);
}
Now, e.Cancel will prevent closing the dropdown if the reason is ItemClicked, so I can select more items without having to open the menu again:
Please note that "changeme" is a ToolStripTextBox!
Once I focus it (click on it), I can edit the text inside:
After finish editing the textbox, I still can change the checkbox items, but there is no focus indicator:
How can I get back the focus indicator just as shown on the first picure?
Note: if I move the mouse onto "Header", the dropdown will close, and then moving it back to "Options", will reopen the dropdown and then the focus indicator is good again:
How can I do this without closing and reopening the dropdown?
I have tried Select() for the options item, but it did not help, neither Invalidate() on ct1.
Just have found it:
First needs to add a click handler on the dropdown:
options.DropDown.Click += DropDown_Click;
Then in the click handler it needs to be focused:
private void DropDown_Click(object sender, EventArgs e)
{
var dropdown = (ToolStripDropDown)sender;
dropdown.Focus();
}

Preserve control's visibility on condition

This is probably an easy one for some of you.
I have a TextBox and a ListBox. ListBox provides options for the TextBox and copies selected item's text to TextBox on DoubleClick event. ListBox becomes visible only when TextBox fires Enter event. I do not want to discuss my reasons for selecting this control combination.
I want ListBox to disappear when any other control within the Form gets focus. So I capture Leave event of TextBox and call ListBox.Visible = fale The problem is that TextBox will also loose focus when I click on ListBox to select provided option thus preventing me from selecting that option.
What event combination should I use to preserve ListBox to select option but hide it whenever other controls get focus?
In the Leave method, you can check to see if the ListBox is the focused control or not before changing its Visibility:
private void myTextBox_Leave(object sender, EventArgs e)
{
if (!myListBox.Focused)
{
myListBox.Visible = false;
}
}
This example will provide you with the desired outcome:
public Form1()
{
InitializeComponent();
textBox1.LostFocus += new EventHandler(textBox1_LostFocus);
textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
}
void textBox1_GotFocus(object sender, EventArgs e)
{
listBox1.Visible = true;
}
void textBox1_LostFocus(object sender, EventArgs e)
{
if(!listBox1.Focused)
listBox1.Visible = false;
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
textBox1.Text = listBox1.SelectedItem.ToString();
}
private void Form1_Shown(object sender, EventArgs e)
{
//if your textbox as focus when the form shows
//this is the place to switch focus to another control
listBox1.Visible = false;
}

How to open a specific tab in windows form

all these tab are created dynamically in windows form . I want to open specific tab page on button click.
For example when clicking on a button(button is not tab page button ,its some other execution button), i want to display tab3 .
I am able to get no of tab pages, but unable to open specific tab..
private void toolStripButton1_Click(object sender, EventArgs e)
{
int tabcount = Main_tab.TabCount;
MessageBox.Show(tabcount.ToString());
}
TabControl.SelectTab Method
this.tabControl1.SelectTab(1); // by index
this.tabControl1.SelectTab("tab3"); // by tabPageName
this.tabControl1.SelectTab(tabPage); // by tab page
Or
TabControl.SelectedIndex Property
this.tabControl1.SelectedIndex = 1; //Selects second tab of the tab control
or
TabControl.SelectedTab Property
this.tabControl1.SelectedTab = tabPage2;
You can access it through its index and call its methods for showing.
Main_tab.GetControl(index_of_your_tab);
You can find the tabs under Controls of the TabControl.
Use Find to find the specific tab by name
Main_tab.SelectedTab = (TabPage)Main_tab.Controls.Find("tab3", searchAllChildren: false).First();
private void toolStripButton1_Click(object sender, EventArgs e)
{
int tabcount = Main_tab.TabCount;
for (int count = 0; count < class_new_tab.tab_count; count++)
{
Main_tab.SelectTab(count);
//perform tab operation
}
}

Tabpage control leave

I have a tab control and 3 tabpages in it. ( C#)
if i am in tab 2, and edit a text box value
and then click tab 3, i need to validate what was enetered in the text box.
if correct i should allow to to switch to tab 3 else should remain in tab 2 it self
how do i achieve this?
iam curently handling the "leave" event of the tabpage2,
i validate the text box value there and if found invalid
i set as tabcontrol.Selectedtab = tabpage2; this does
the validation but switches to new tab! how could i restrict the navigation.
I am a novice to C#, so may be i am handling a wrong event!
Here is the relevant code:
private void tabpage2_Leave(object sender, EventArgs e)
{
if (Validatetabpage2() == -1)
{
this.tabcontrol.SelectedTab =this.tabpage2;
}
}
While the other approaches may work, the Validating event is designed specifically for this.
Here's how it works. When the SelectedIndex of the tab control changes, set the focus to the newly selected page and as well as CausesValidation = true. This ensures the Validating event will called if the user tries to leave the tab in any way.
Then do your normal validation in a page specific Validating event and cancel if required.
You need to make sure to set the initial selected tab page in the Form Shown event (Form_Load will not work) and also wire up the tab page specific validating events.
Here's an example:
private void Form_Shown(object sender, System.EventArgs e)
{
// Focus on the first tab page
tabControl1.TabPages[0].Focus();
tabControl1.TabPages[0].CausesValidation = true;
tabControl1.TabPages[0].Validating += new CancelEventHandler(Page1_Validating);
tabControl1.TabPages[1].Validating += new CancelEventHandler(Page2_Validating);
}
void Page1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == "")
{
e.Cancel = true;
}
}
void Page2_Validating(object sender, CancelEventArgs e)
{
if (checkBox1.Checked == false)
{
e.Cancel = true;
}
}
private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Whenever the current tab page changes
tabControl1.TabPages[tabControl1.SelectedIndex].Focus();
tabControl1.TabPages[tabControl1.SelectedIndex].CausesValidation = true;
}
You can use the TabControl Selecting event to cancel switching pages. Setting e.Cancel to true in the event stops the tabcontrol from selecting a different tab.
private bool _cancelLeaving = false;
private void tabpage2_Leave(object sender, EventArgs e)
{
_cancelLeaving = Validatetabpage2() == -1;
}
private void tabcontrol_Selecting(object sender, TabControlCancelEventArgs e)
{
e.Cancel = _cancelLeaving;
_cancelLeaving = false;
}

Keep selection when clicking into textbox

I need to have the text in a TextBox become selected when a user clicks into the box. If the text is already selected, it needs to be a regular cursor. So on the click event of all the textboxes I have this code:
TextBox t = (TextBox)sender;
bool alreadyselected = t.SelectedText == t.Text;
if (!alreadyselected) t.SelectAll();
the problem is, by the time the click event is reached, t.SelectedText is empty
so the full text always becomes selected even when clicking multiple times
I would appreciate a solution that can be for all the textboxes at once if possible
You're correct, the default Click for the TextBox is changing the position of the caret and thus clearing any selected text. But you can restore it.
First add 2 int vars to store the selection Start and Length and initialize Start as -1 to signal not set:
private int SelectedStart = -1;
private int SelectedLength = 0;
then make a handler for the TextBox's Leave event and save the Start and Length for the currently selected text when we lose focus.
private void textBox1_Leave (object sender, EventArgs e)
{
SelectedStart = textBox1.SelectionStart;
SelectedLength = textBox1.SelectionLength;
}
Finally, make a handler for the TextBox's Click event and, if we previously saved the Start and Length, restore them to the TextBox and then set Start to -1 to signal not set again (this allows for normal click behavior within textbox when it is focused).
private void textBox1_Click (object sender, EventArgs e)
{
if (SelectedStart != -1) {
textBox1.SelectionStart = SelectedStart;
textBox1.SelectionLength = SelectedLength;
SelectedStart = -1;
}
}
Use the Control.Tag property to set a bool flag to select or deselect the TextBox text:
private void TextBox_Click(object sender, EventArgs e)
{
TextBox txtBox = (TextBox)sender;
txtBox.SelectionStart = 0;
// First click will select the text
if (txtBox.Tag == null)
{
txtBox.Tag = true;
txtBox.SelectionLength = txtBox.Text.Length;
}
// Second click will deselect the text
else
{
txtBox.Tag = null;
txtBox.SelectionLength = 0;
}
}

Categories