根据下拉列表选择的值在文本框中搜索数据

时间:2015-02-08 21:10:30

标签: c# asp.net search

我已经在asp.net gridview中创建了公司联系人列表。我需要像图片中的内容。如果有人之前已经这样做了,请给我一个链接或一些示例代码。 search data based on dropdownlist selected value

1 个答案:

答案 0 :(得分:1)

aspx代码

<asp:Label ID="Label1" runat="server" Text="Search By"></asp:Label>

    <asp:TextBox ID="txtSearchName" runat="server"></asp:TextBox>

   <asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem>Name</asp:ListItem>
        <asp:ListItem>Search By Employee Name</asp:ListItem>
        <asp:ListItem>Search By Company Name</asp:ListItem>            
        <asp:ListItem>Search By Mobile</asp:ListItem>
    </asp:DropDownList>

    <asp:Button ID="btnSearch_Click" runat="server" onclick="btnSearch_Click_Click" 
        Text="Search By" />

C#

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlCon = new   SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        SqlCommand cmd = new SqlCommand("Select * from tablename", sqlCon);
        sqlCon.Open();
        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataBind();
    }
}


protected void btnSearch_Click_Click(object sender, EventArgs e)
{

    string Query = string.Empty;
    try
    {
        if (sqlCon.State == ConnectionState.Closed)
        {
            sqlCon.Open();
        }
        if (DropDownList1.SelectedValue.ToString() == "Search By Employee Name")
        {
            Query = "select * from tablename where EmployeeName Like '%" + txtSearchName.Text + "%'";
        }
        else if (DropDownList1.SelectedValue.ToString() == "Search By Company Name")
        {
            Query = "select * from tablename where CompanyName Like '" + txtSearchName.Text + "%'";
        }
        else if (DropDownList1.SelectedValue.ToString() == "Search By Mobile")
        {
            Query = "select * from tablename where Mobile Like '%" + txtSearchName.Text + "'";
        }

        SqlDataAdapter sqlDa = new SqlDataAdapter(Query, sqlCon);
        DataSet Ds = new DataSet();
        sqlDa.Fill(Ds);
        GridView1.DataSource = Ds;
        GridView1.DataBind();
    }
    catch (Exception ex)
    {
        HttpContext.Current.Response.Write("<script>alert('wfrmGrid: 11')</script>" + ex.Message);
    }
    finally
    {
        sqlCon.Close();
    }
}

}