如何在C#.net webforms中的不同条件下将焦点设置为特定的文本框?

时间:2014-08-23 17:52:33

标签: c# webforms textbox focus

我有四个文本框分组为两个:

  • txtbox_date_start
  • txtbox_date_end
  • txtbox_value_start
  • txtbox_value_end

enter image description here

所有这四个文本框都有AutoPostBack = true。

if (Page.IsPostBack)
{
    //copy value of txtbox_date_start to txtbox_date_end
    if ((txtbox_date_start.Text != "") && (txtbox_date_end.Text == ""))
    {
        txtbox_date_end.Text = txtbox_date_start.Text;

        // How?
        // if txtbox_date_start was focused, then set focus to txtbox_date_end
    }

    //copy value of txtbox_value_start to txtbox_value_end
    if ((txtbox_value_start.Text != "") && (txtbox_value_end.Text == ""))
    {
        txtbox_value_end.Text = txtbox_value_start.Text;

        // How?
        //if txtbox_value_start was focused, then set focus to txtbox_value_end
    }
}

我原来的pseucode是这样的:

if txtbox_date_start is not empty and is focused,

--> then when press tab,

----> txtbox_date_end will be = to txtbox_date_start

------> and txtbox_date_end will be focused

txtbox_value_start&的目的相同txtbox_value_end。

我也尝试使用

if ( txtbox_date_start.Focused == true)

但是Focuse()不能在if语句中使用。

1 个答案:

答案 0 :(得分:1)

首先,使用string.Empty而不是“”。

我会按照以下方式做一些事情并根据输入进行关注:

//copy value of txtbox_date_start to txtbox_date_end
var startDate = txtbox_date_start.Text;
var endDate = txtbox_date_end.Text;

if ((startDate != string.Empty) && (endDate.Text == string.Empty))
{
    txtbox_date_end.Text = startDate;

    // How?
    // if txtbox_date_start was focused, then set focus to txtbox_date_end
    if(startDate != string.Empty && endDate == string.Empty){
        txtbox_date_end.Focus();
    }
    else if(endDate != string.Empty && startDate == string.Empty){
        txtbox_start_end.Focus();
    }
}