在文本框中搜索asp.net [英] asp.net search in textbox

查看:57
本文介绍了在文本框中搜索asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是在Asp.net页面中包含一个文本框.当我在该数据库表上输入charector并在弹出窗口中显示相应的记录时,我们选择其中之一将被显示.
我的数据库查询是
从job_desc之类的作业中选择*,例如''+ document.getElementById(<%= TextBox2.ClientID%>").value +''"

my requirement is in Asp.net page consists of one textbox. when i enter charector on that i search database table and display corresponding records in popup and we select one of then that will be displayed.
My Database Query is
select * from jobs where job_desc like ''"+document.getElementById("<%=TextBox2.ClientID%>").value+"''"

推荐答案

你好,

您可以将javascript与ajax配合使用.

我将在此处编写代码,您只需更改查询即可.


这是js文件,您可以按原样使用.只需在searchSuggest函数中更改重定向路径.将其重定向到您的文本框即可.此外,您还需要下载ajaxtoolkit并将其添加到ur bin文件夹中.




hello,

you use javascript with ajax for this.

i will write the code here,you just change ur query.


this is the js file,You can use it as it is.Just change the redirect path in the searchSuggest function.redirect it where you have ur text box.and one thing more you have to download ajaxtoolkit and add it in ur bin folder.




// JScript File
var maxDivId, currentDivId, strOriginal;
//Our XmlHttpRequest object to get the auto suggestvar
searchReq = getXmlHttpRequestObject();
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
        //alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
    }
}
//Called from keyup on the search textbox.//Starts the AJAX request.
function searchSuggest(e) {

    var key = window.event ? e.keyCode : e.which;
    if (key == 40 || key == 38) {
        scrolldiv(key);
    }
    else {
        if (searchReq.readyState == 4 || searchReq.readyState == 0) {
            var str = escape(document.getElementById('txtSearch').value);
            strOriginal = str;
            searchReq.open("GET", 'CreateModifyNewItem.aspx?search=' + str + '&url=' + window.location, true);
            searchReq.onreadystatechange = handleSearchSuggest;
            searchReq.send(null);
        }
    }

}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
    if (searchReq.readyState == 4) {
        var ss = document.getElementById('search_suggest');
        ss.innerHTML = '';
        var str = searchReq.responseText.split("~");
        if (str.length > 1) {
            for (i = 0; i < str.length - 1; i++) {
                //Build our element string.  This is cleaner using the DOM, but
                //IE doesn't support dynamically added attributes.
                maxDivId = i;
                currentDivId = -1;
                var suggest = '<div ';
                suggest += 'id=div' + i;
                suggest += '  '
                suggest += 'onmouseover="javascript:suggestOver(this);" ';
                suggest += 'onmouseout="javascript:suggestOut(this);" ';
                suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
                suggest += document.onclick = function() { HideSuggDiv('this.innerHTML'); };
                suggest += 'class="suggest_link">' + str[i] + '</div>';
                ss.innerHTML += suggest;
                ss.style.visibility = 'visible';
            }
        }
        else {
            ss.style.visibility = 'hidden';
        }
    }

}
//Mouse over function
function suggestOver(div_value) {
    div_value.className = 'suggest_link_over';
}
function scrollOver(div_value) {
    div_value.className = 'suggest_link_over';
    document.getElementById('txtSearch').value = div_value.innerHTML;
}
function HideSuggDiv(value) {
    var txt = document.getElementById('txtSearch');
    var obj = document.getElementById('search_suggest');
    var evt = window.event || arguments.callee.caller.arguments[0];
    var eobj = window.event ? evt.srcElement : evt.target;
    if (eobj.nodeType == 3) eobj = eobj.parentNode;
    while (eobj.parentNode) {
        if (eobj == obj) return;
        eobj = eobj.parentNode;
    }
    obj.style.visibility = 'hidden';
}
//Mouse out function
function suggestOut(div_value) {
    div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
    var ss = document.getElementById('search_suggest');
    document.getElementById('txtSearch').value = value;
    ss.innerHTML = '';
    ss.style.visibility = 'hidden';
}
function scrolldiv(key) {
    var tempID;

    if (key == 40) {
        if (currentDivId == -1) {
            scrollOver(div0);
            currentDivId = 0;
        }
        else {
            if (currentDivId == maxDivId) {
                tempID = 'div' + maxDivId;
                var a = document.getElementById(tempID);
                currentDivId = -1;
                suggestOut(a)
                document.getElementById('txtSearch').value = strOriginal;
            }
            else {
                tempID = currentDivId + 1;
                setScroll(currentDivId, tempID)
            }
        }
    }
    else if (key == 38) {
        if (currentDivId == -1) {
            tempID = maxDivId;
            setScroll(maxDivId, maxDivId)
        }
        else {
            if (currentDivId == 0) {
                tempID = 'div' + currentDivId;
                var a = document.getElementById(tempID);
                currentDivId = -1;
                suggestOut(a)
                document.getElementById('txtSearch').value = strOriginal;
            }
            else {
                tempID = currentDivId - 1;
                setScroll(currentDivId, tempID)
            }
        }

    }
}
function setScroll(Old, New) {
    var tempDivId;
    currentDivId = New;
    tempDivId = 'div' + Old;
    var a = document.getElementById(tempDivId);
    suggestOut(a)
    tempDivId = 'div' + currentDivId;
    var b = document.getElementById(tempDivId);
    scrollOver(b);
}







and in the aspx page you have to use the input textbox type
add ajax toolkit in the register tag and js file reference

<pre lang="xml"><input type="text" id="Text1" name="txtSearch" onkeyup="searchSuggest(event);"

                                            style="width: 170px" />
                                        <asp:HiddenField ID="HiddenField1" runat="server" />
                                        <div id="Div4" style="z-index: 2; visibility: hidden; position: absolute;
                                            left: 11px; width: 170px; top: 40px">
                                        </div>
                                            <asp:Button ID="Button1" runat="server" Text="Search" CausesValidation="False"

                                            OnClick="btnSearch_Click" CssClass="asset-viewer-btn" OnClientClick="getSearchValue();" />
    <script type="text/javascript" language="javascript">
        function getSearchValue() {
            var getValue = document.getElementById('txtSearch').value;
            var hiddenfield = document.getElementById("<%=txtHiddenFieldSearch.ClientID%>").value = getValue;
        }
    </script>







在页面上加载以下代码:







on the page load in code behind:

if (Request.QueryString["search"] != null)
            {
              string  clientName = Request["search"].ToString();
                Getresult();
            }








私有无效Getresult()
{
DataTable dt = new DataTable();

//string search =从资产类型如Concat("%,""+ clientName +"'',''%)|| AssetSubType像Concat("%,' '"+ clientName +"'',''%'')||资产类型如Concat(%",''"+ clientName +"'',''%'')限制7;
字符串搜索=从AssetType相似的资产中选择资产类型""+ clientName +"%按AssetType UNION分组从AssetAsset相似的资产中选择AssetSubType""+ clientName +"%组按AssetSubType UNION选择资产其中AssetName类似于"+ clientName +"%,按AssetName LIMIT 10"分组;
如果(myConnection.State == ConnectionState.Closed)
{
myConnection.Open();
}
命令=新的MySqlCommand(search,myConnection);
MySqlDataAdapter da =新的MySqlDataAdapter(命令);
da.Fill(dt);
StringBuilder sb = new StringBuilder();
如果(clientName!=")
{
如果(dt.Rows.Count> 0)
{
for(int i = 0; i< dt.Rows.Count; i ++)
{
sb.Append(dt.Rows [i] .ItemArray [0] .ToString()+〜"); //创建Con
//sb.Append(dt.Rows [i] .ItemArray [2] .ToString()+〜");
//sb.Append(dt.Rows [i] .ItemArray [3] .ToString()+〜");
}
}
}
Response.Write(sb.ToString());

}



受保护的无效btnSearch_Click(对象发送者,EventArgs e)
{
字符串searchValue = txtHiddenFieldSearch.Value;
//txtSearch.Value = txtSearch.Value.Replace(",").Replace(",").Trim();
字符串搜索=从资产中选择*,其中AssetType类似于''" + searchValue +%" || AssetSubType类似于" + searchValue +%" || AssetName类似于" + searchValue +%"";

如果(myConnection.State == ConnectionState.Closed)
{
myConnection.Open();
}
//OdbcCommand命令=新的OdbcCommand(search,myConnection);
命令=新的MySqlCommand(search,myConnection);
MySqlDataAdapter适配器=新的MySqlDataAdapter(search,myConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
myConnection.Close();

}








private void Getresult()
{
DataTable dt = new DataTable();

//string search = "Select * from assets where AssetType Like Concat (''%'',''" + clientName + "'',''%'') || AssetSubType Like Concat (''%'',''" + clientName + "'',''%'') || AssetType Like Concat(''%'',''" + clientName + "'',''%'') Limit 7";
string search = "Select AssetType from assets where AssetType Like ''" + clientName + "%'' group by AssetType UNION Select AssetSubType from assets where AssetSubType Like ''" + clientName + "%'' group by AssetSubType UNION Select AssetName from assets where AssetName Like ''" + clientName + "%'' group by AssetName LIMIT 10";
if (myConnection.State == ConnectionState.Closed)
{
myConnection.Open();
}
command = new MySqlCommand(search, myConnection);
MySqlDataAdapter da = new MySqlDataAdapter(command);
da.Fill(dt);
StringBuilder sb = new StringBuilder();
if (clientName != "")
{
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append(dt.Rows[i].ItemArray[0].ToString() + "~"); //Create Con
//sb.Append(dt.Rows[i].ItemArray[2].ToString() + "~");
//sb.Append(dt.Rows[i].ItemArray[3].ToString() + "~");
}
}
}
Response.Write(sb.ToString());

}



protected void btnSearch_Click(object sender, EventArgs e)
{
string searchValue = txtHiddenFieldSearch.Value;
//txtSearch.Value = txtSearch.Value.Replace(" ", "").Replace(" ", "").Trim();
string search = "Select * from assets where AssetType Like ''" + searchValue + "%'' || AssetSubType Like ''" + searchValue + "%'' || AssetName Like ''" + searchValue + "%''";

if (myConnection.State == ConnectionState.Closed)
{
myConnection.Open();
}
//OdbcCommand command = new OdbcCommand(search, myConnection);
command = new MySqlCommand(search, myConnection);
MySqlDataAdapter adapter = new MySqlDataAdapter(search, myConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
myConnection.Close();

}


Ramesh Reddy11111写道:
Ramesh Reddy11111 wrote:

从*的作业中选择*,例如"+" document.getElementById (<%= TextBox2.ClientID%>").value +''"

select * from jobs where job_desc like ''"+document.getElementById("<%=TextBox2.ClientID%>").value+"''"



您是从哪里学到的呢?通过语法,您已经在JavaScript中进行了查询.怎么办?这不是您应该编码的方式.我建议您在开始编码之前先买一本书或阅读初学者的教程.您目前的方向不正确.

根据您的要求,步骤应为:
1.在父页面中放置搜索文本框和一个按钮
2.绑住按钮以获取文本框数据并将其传递到新窗口(您称其为弹出窗口)(Querystring对您来说可能很简单)
3.在新窗口中,使用文本框值并在代码中从数据库中获取数据
4.显示在网格中检索到的数据.
5.显示选定的记录

试试吧.这是一个简单的工作流程,只要您了解ASP.NET的简单入门教程,就应该能够做到.



Where did you learnt doing like this? From the syntax, you have made a query in JavaScript. Now what? This is not the way you should code. I would suggest you to buy a book or read beginners tutorials before starting to code. You are not in right direction for now.

Based on your requirement, steps should be:
1. Place search textbox and a button in Parent Page
2. Tie up the button to get the textbox data and pass it on to a new window (which you call a popup) (Querystring can be simple for you)
3. In new window, use the textbox value and get data from database in your code behind
4. Show the data retrieved in a grid.
5. Show the selected record

Try it. It''s a simple work flow, and one should be able to do it as long as you know simple and beginner tutorials of ASP.NET.


Ramesh Reddy11111写道:
Ramesh Reddy11111 wrote:

我想以Google搜索.我在Google搜索文本框中输入了一些字符.每当我在其中输入相关信息时,就会像dorpdown一样显示出来,我选择了其中之一并回车.我想要在Serch上使用该类型.请参阅:http://www.google.co.in/

i want search as Google. i entered some charactor on the google search textbox. when ever i entered chr in to that related information is displayed like dorpdown i selected one of them and the enter. i want that type on serch. refer: http://www.google.co.in/


感谢您让我推荐Google搜索!!!

我建议您再次阅读您的问题.你到底在哪提到过.如果您不能正确地提出问题,您怎么能期望有人帮助您呢?

现在,我将要求您对Google"AutoSuggest"进行搜索-您将获得有关其的文章数量.如果您愿意,甚至CopeProjct也很少...

如果是正常情况,我会提供文章链接,但现在我建议您使用www.gooogle.com并选择适合您的文章.

顺便说一句:


Thanks for making me refer Google search!!!

I would suggest you to read your question again. Where exactly have you mentioned that. If you cannot frame your question properly, how come you can expect someone to help you?

Now i would ask you to google "AutoSuggest" - you will get number of articles on it. If you want, even CopeProjct has few...

Had it been a normal case, i would had provided the article links, but now i would suggest you to use www.gooogle.com and select the article that suits you.

BTW:

Ramesh Reddy11111写道:
Ramesh Reddy11111 wrote:

从* job_desc之类的作业中选择*,例如"+ document.getElementById("<%= TextBox2.ClientID%> ).value +"''"

select * from jobs where job_desc like ''"+document.getElementById("<%=TextBox2.ClientID%>").value+"''"


这仍然是实现它的一种非常错误的方法,并且仍然建议在编码之前先阅读它.您需要将键入的文本传递给代码隐藏,然后执行操作!


This still is a very WRONG way to achieve it and still suggest to read it before coding it. You need to pass the text typed to code-behind and do the stuff!


这篇关于在文本框中搜索asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆