编译时没有错误代码,但屏幕上没有数据表,我无法弄清楚原因

时间:2014-02-27 11:58:53

标签: c# html sql .net sql-server

搜索文本框没有在屏幕上返回有效的数据表人,任何人都知道为什么?

数据库类:

static public DataTable SearchButton(string search)
{
    using (var conn = new SqlConnection(DatabaseConnectionString))
    {
        var dt = new DataTable();
        const string searchQuery = "exec SearchTerm";

        using (var cmd = new SqlCommand(searchQuery, conn))
        {
            conn.Open();
            cmd.Parameters.Add("@Search_Term", SqlDbType.VarChar, search.Length).Value = "%" + search + "%";
            dt.Load(cmd.ExecuteReader());
            return dt;
        }
    }
}

PeopleList.aspx.cs:

protected void SearchButton_Click(object sender, EventArgs e)
{
    if (SearchTextbox.Text == null || SearchTextbox.Text == "")
    {
        PeopleListLabel.Text = "Please enter a search term!";
    }
    else
    {
        Phonelist.DataSource = Database.SearchButton(SearchTextbox.Text);
        Phonelist.DataBind();
    }  
}

SQL存储过程:

print 'SearchTerm'
if exists (select * from sys.objects where object_id = object_id(N'[SeachTerm]') AND type in (N'P', N'PC'))
    drop procedure SearchTerm

go
    create procedure SearchTerm 
        @Search_Term varchar(64) = null
    as
    begin
    set nocount on;

    SELECT first_name, last_name, email_address, gender, home_address, home_city, home_state, home_zip_code, telephone_number
    FROM person
    WHERE first_name LIKE @Search_Term OR last_name LIKE @Search_Term
end

2 个答案:

答案 0 :(得分:0)

你缺少commandType。

static public DataTable SearchButton(string search)
    {
        using (var conn = new SqlConnection(DatabaseConnectionString))
        {
            var dt = new DataTable();
            const string searchQuery = "exec SearchTerm";
            using (var cmd = new SqlCommand(searchQuery, conn))
            {
                conn.Open();
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.Add("@Search_Term", SqlDbType.VarChar, search.Length).Value = "'%" + search + "%'";
                dt.Load(cmd.ExecuteReader());
                return dt;
            }
        }
    }

答案 1 :(得分:0)

您需要将搜索参数括在单引号中。

替换它:

cmd.Parameters.Add("@Search_Term", SqlDbType.VarChar, search.Length).Value 
    = "%" + search + "%";

有了这个:

cmd.Parameters.Add("@Search_Term", SqlDbType.VarChar, search.Length).Value 
    = "'%" + search + "%'";