C # Сохранить фокус TextBox с двумя панелями обновления - PullRequest
0 голосов
/ 19 сентября 2018

У меня есть две панели обновления.Первый содержит текстовое поле.Когда вводится текст, он вызывает хранимую процедуру для заполнения списка, который содержится на второй панели обновлений, возвращенными данными таблицы, основанными на сопоставлении LIKE с тем, что введено в текстовое поле.Это не большая таблица, и вместо того, чтобы хранить данные в локальной таблице, я просто делаю вызов SQL.Со временем я буду хранить его в локальной таблице.Когда элемент выбран из списка, текстовое поле заполняется выбранным значением.Моя проблема в том, что с каждым символом, введенным в текстовое поле, фокус теряется.И даже если я получу фокус обратно с помощью textbox.focus (), курсор находится в начале текста, а не в конце, и страница прокручивается до самого верха.

Есть ли способ сохранитьсфокусироваться на конце введенной строки, без прокрутки страницы вверх.

Вот код моей страницы:

<asp:Content ID="Content1" ContentPlaceHolderID="head1" Runat="Server">
    <link href="/css/usa.css" rel="stylesheet" />
    <link href="/css/formTables.css" rel="stylesheet" />
    <script type="text/javascript">
        function courseTextChanged() {
            var txt = document.getElementById("<%=courseTextBox.ClientID %>");
            txt.setAttribute("onkeyup", txt.getAttribute("onchange"));
            txt.setAttribute("onchange", "");
        }
        window.onload = function () {
            courseTextChanged();
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            if (prm != null) {
                prm.add_endRequest(function (sender, e) {
                    if (sender._postBackSettings.panelsToUpdate != null) {
                        courseTextChanged();
                    }
                });
            }
        };
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="contentBody" Runat="Server">
    <div id="content">
                <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>            
                <asp:UpdatePanel ID="CourseTextPanel" runat="server" style="width:460px; float:right;">

                    <ContentTemplate>
                        <p id="paraTwo" runat="server">
                            <asp:TextBox ID="courseTextBox" runat="server" CssClass="formTableTextBox" OnTextChanged="course_TextChanged" AutoPostBack="true" /><br /><span class="labelNote">Enter the name of the course you are searching for in this box.</span>
                        </p>
                    </ContentTemplate>

                    <Triggers>

                        <asp:AsyncPostBackTrigger ControlID ="courseTextBox" EventName ="TextChanged" />

                    </Triggers>

                </asp:UpdatePanel>
                <asp:UpdatePanel ID="ListBoxPanel" runat="server" style="width:460px; float:right;" >
                    <ContentTemplate>
                        <div id="crsListDIV" runat="server" style="width:460px; height:241px;" Visible="false">
                            <asp:ListBox ID="crsList" runat="server" Height="240px" Width="460px" style="overflow-x:auto; margin-left:20px;" AutoPostBack="True" OnSelectedIndexChanged="addCourseToTextbox" SelectionMode="Single" EnableViewState="True"></asp:ListBox>
                        </div>

                    </ContentTemplate>

                    <Triggers>

                        <asp:AsyncPostBackTrigger ControlID ="crsList" EventName ="SelectedIndexChanged" />

                    </Triggers>
                </asp:UpdatePanel>
    </div>

Вот код:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Configuration;

public partial class EMICourses_EMI_Out_of_Cycle_Training_Request_Form : System.Web.UI.Page
{

   string courseList;
   protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void course_TextChanged(object sender, EventArgs args)
    {
        if (courseTextBox.Text.Length > 0)
        {
            BindListBox();
        }
        else
        {
            crsList.Items.Clear();
            crsListDIV.Visible = false;

        }
    }
    protected string stripLeadingZero(string textboxKeywordText)
    {
        string pattern = @"(.)(0)(\d+)";
        string replacement = "$1$3";
        string textKeyWord = Regex.Replace(textboxKeywordText, pattern, replacement);

        return textKeyWord;
    }

    protected void BindListBox()
    {
        if (courseTextBox.Text.Length > 0)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings.Get("connString"));
            string textboxKeyword = stripLeadingZero(courseTextBox.Text);
            string sp = "";
            sp = "selAllCourses";
            SqlCommand command = new SqlCommand(sp, con);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@keywords", SqlDbType.VarChar).Value = textboxKeyword;
            SqlDataAdapter da = new SqlDataAdapter(command);

            DataSet ds = new DataSet();
            da.Fill(ds, "CourseList");
            ds.Tables[0].Columns.Add("CodeAndTitle", typeof(string), "CourseCode + ' ' + CourseTitle");
            crsList.DataSource = ds;
            crsList.DataTextField = "CodeAndTitle";
            crsList.DataValueField = "CodeAndTitle";
            crsList.DataBind();
            crsListDIV.Visible = true;
        }
        else
        {
            crsList.Items.Clear();
            crsListDIV.Visible = false;
        }

    }

    protected void addCourseToTextbox(object sender, EventArgs e)
    {
        Int32 item = crsList.SelectedIndex;
        courseTextBox.Text = crsList.Items[item].ToString();
        crsListDIV.Visible = false;
    }
}

Любая помощь будет оценена.

...