回发后将焦点设置在文本框上

Set focus on textbox after postback(回发后将焦点设置在文本框上)
本文介绍了回发后将焦点设置在文本框上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 3 个文本框的搜索页面,用户可以使用这些文本框过滤搜索.

I have a search page with 3 TextBoxes that users can filter a search with.

我已将焦点放在包含文本的 TextBox 上.如果多个文本包含文本,则只关注最后一个 TextBox.

I have put the focus on the TextBox that contains text. If more than one contains text just focus on last TextBox.

private void SetFocusOnTextBox(ControlCollection ctrlCollection)
{
    foreach (Control ctrl in ctrlCollection)
    {
        if (ctrl.GetType() == typeof(TextBox))
        {
            if (((TextBox)ctrl).Text != string.Empty)
            {
                SetFocus(ctrl);
            }
        }
    }
}

在代码运行并且用户搜索之后,焦点会出现在 TextBox 的开头,而不是假定的结尾.如何将插入标记在该文本框的末尾?

After the code runs and a user searches, the focus comes to the beginning of the TextBox, not the end where it would be presumed. How to put insert marked at the end of that TextBox?

推荐答案

我想答案就在这里:使用 JavaScript 将光标置于文本输入元素中的文本末尾.

取自链接的解决方案:您必须将 onfocus="this.value = this.value" 添加到标记文件中的三个控件.这在 ASP.NET 中并不像应有的那么容易,但一种解决方案是在代码隐藏文件中添加属性.

Taken from the linked solution: You have to add onfocus="this.value = this.value" to the three controls in the markup file. This is not so easy in ASP.NET as it should be, but one solution is to add the attribute in the code behind file.

protected void Page_Init(object sender, EventArgs e)
{
    // MoveCursorToEndOnFocus is called in Page_Init and not Page_Load to avoid
    // filling the ViewState with unnecessary data.
    // TODO: Call MoveCursorToEndOnFocus here.
}

private void MoveCursorToEndOnFocus(ControlCollection controlCollection)
{
    foreach (TextBox textBox in controlCollection
        .Where(control => control.GetType() == typeof(TextBox)))
    {
        textBox.Attributes.Add("onchange", "this.value = this.value");
    }
}

这篇关于回发后将焦点设置在文本框上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
How to minify in .net core mvc view?(如何在.Net核心MVC视图中缩小?)