从tabbar控件中的winform获取控件

时间:2014-10-28 06:27:31

标签: c# winforms textbox tabbar

我有一个标签栏控件,在第一个标签页面中我有一个文本框。我想要的是,当选择第一个标签时,文本框将自动对焦。

我可以访问tabbar选择的索引更改事件但无法访问文本框以进行自动聚焦。有什么想法吗?

在添加到tabbar时,我正在执行此操作:

            capture = new CaptureForm(photoGrapherName);
            capture.TopLevel = false;
            capture.Visible = true;
            capture.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            capture.Dock = DockStyle.Fill;
            tabControl1.TabPages[0].Controls.Add(capture); capture = new CaptureForm(photoGrapherName);
            capture.TopLevel = false;
            capture.Visible = true;
            capture.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            capture.Dock = DockStyle.Fill;
            tabControl1.TabPages[0].Controls.Add(capture);

这是我的标签更改事件:

    private void TabControl1_SelectedIndexChanged(Object sender, EventArgs e)
    {
        switch(tabControl1.SelectedIndex)
        {
            case 0:
                //I want to access the textbox from here.
                break;
            case 1:

                break;
        }

    }

CaptureForm有一个名为' ClientCode'的文本框,我想在任何人选择Capture标签时使这个文本框成为焦点。

1 个答案:

答案 0 :(得分:2)

您是否尝试使用 SelectedIndexChanged 事件?如果您谈论 TabControl ,我们可以在切换案例的帮助下使用 selectedIndexChanged 事件执行此操作。

    private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch ((sender as TabControl).SelectedIndex)
        {
            case 0:
                //nothing to do.. or you can, if you want.. :)
                break;
            case 1:                    
                tbFName.Focus();
                break;
        }
    }

<强>更新

当你修改我知道你是动态添加控件到TabPage所以使用下面的代码片段来获取动态添加的TextBox

    public Form1()
    {
        InitializeComponent();
        TextBox tb = new TextBox();
        tb.Name = "dynamic";
        tb.Text = "Text dynamic";
        tabControl1.TabPages[1].Controls.Add(tb);
    }

    private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        TabControl tc = (sender as TabControl);
        switch (tc.SelectedIndex)
        {
            case 0:

                break;
            case 1:
                Control[] temp = tc.TabPages[1].Controls.Find("dynamic", true);
                if (temp.Length == 1)
                {
                    (temp[0] as TextBox).Focus();
                }
                break;
        }
    }

希望你有意义..!