将数据表中的信息放入gridview

时间:2012-11-19 02:50:42

标签: search gridview datatable

我正在编写一个简单的搜索算法来显示包含在文本框中输入的值的结果。

我正在尝试将数据表中的信息放入gridview的boundfield元素中。 代码我必须显示搜索结果:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SimpleSearch.ascx.cs"Inherits="SimpleSearch" %>

 <asp:TextBox ID="SimpleSearchBox" runat="server" />
        <asp:Button ID="submitSearch" runat="server" Text="Search" 
        onClick="SimpSearch" />


            <asp:Gridview ID="results" runat="server" Visible="false" >

            <Columns>
            <asp:BoundField  DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField  DataField="Description" HeaderText="Description" SortExpression="Description" />
            <asp:BoundField  DataField="Path" headerText="Path" SortExpression="Path" />

            </Columns>

        </asp:Gridview>
        <label ID="errMsg" runat="server" />

但我认为真正的麻烦来自我的代码隐藏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;    
using System.Web.Configuration;
using System.Data.Common;
using System.Data;

public partial class SimpleSearch : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void SimpSearch(object sender, EventArgs e)
{
    // retrieve the connection string from our config file
    string connString =
    WebConfigurationManager.ConnectionStrings["GeoNames"].ConnectionString;
    // retrieve the provider name from config file
    string providerName =
    WebConfigurationManager.ConnectionStrings["GeoNames"].ProviderName;
    // get the factory based on the provider name
    DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
    // create the connection
    DbConnection conn = factory.CreateConnection();
    conn.ConnectionString = connString;
    //get text from search box
    string query = SimpleSearchBox.Text;
    try
    {
        // define the SQL command1
        string sql = "SELECT Title, td.ImageID, ti.ImageID, Description FROM TravelImageDetails as td, TravelImage as ti";
        sql += " WHERE td.ImageID = ti.ImageID AND td.Title LIKE '%@query%' OR td.Description LIKE'%@query%' ";
        // create a command
        DbCommand cmd = factory.CreateCommand();
        cmd.CommandText = sql;
        cmd.Connection = conn;
        // create the data adapter
        DbDataAdapter adapter = factory.CreateDataAdapter();
        adapter.SelectCommand = cmd;
        // fill a data table from the adapter
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        results.DataSource = dt;
        results.DataBind();
        results.Visible = true;
    }

    catch (Exception ex)
    {
        errMsg.InnerText = "<h2>An Error Occurred</h2>";
        errMsg.InnerText += ex.Message;
    }

    finally
    {
        conn.Close();
    }
}
}

点击搜索按钮显示没有数据,我想知道它为什么不做任何事情。任何输入都会有所帮助,我在c#中的技能非常有限

0 个答案:

没有答案