基本ASP搜索带有数据网格的SQL Server

时间:2018-03-20 21:29:36

标签: c# asp.net

我试图关注基本的asp.net视频:https://www.youtube.com/watch?v=9e0kwADEoEg来创建一个包含文本框,按钮和gridview的网页。

出于某种原因,gridview永远不会显示填充数据:/我认为它是因为.fill但实际上并不确定。我在sql server上运行跟踪时可以看到查询。网页上没有输出!?有人可以帮忙吗?

ausing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

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

    SqlConnection vid = new SqlConnection("Server=localhost;Database=exam;Integrated Security=True");

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string str = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = '@search'";
        SqlCommand xp = new SqlCommand(str,vid);
        xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = TextBox1.Text;

        vid.Open();
        xp.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = xp;

        DataSet ds = new DataSet();
        da.Fill(ds, "Name");
        GridView1.DataSource = ds;
        GridView1.DataBind();
        vid.Close();
    }
}

2 个答案:

答案 0 :(得分:0)

       // Open connection
        using (SqlConnection c = new SqlConnection(vid))
        {
            c.Open();
            // 2
            // Create new DataAdapter
            using (SqlDataAdapter a = new SqlDataAdapter(
                "SELECT * FROM EmployeeIDs", c))
            {
                // 3
                // Use DataAdapter to fill DataTable
                DataTable t = new DataTable();
                a.Fill(t);

                // 4
                // Render data onto the screen
                dataGridView1.DataSource = t; // <-- From your designer
            }
        }

答案 1 :(得分:0)

删除查询中的单引号:

string str = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = @search";

引号告诉Sql Server将@search视为字符串文字而不是sql变量名。

此外,摆脱ExecuteNonQuery()代码。该函数用于INSERT / UPDATE / DELETE语句。

另一个问题是SqlConnection对象。不要尝试在页面中重用SqlConnection对象。 .Net使用一种称为连接池的功能来缓存底层连接对象,并尝试重用相同的.Net SqlConnection对象实例。只需保持连接字符串的方便并创建一个新的SqlConnection实例。真。

还有更多。下面的代码进行了许多其他改进:using以便在发生异常时清理事务,Fill()将为您打开和关闭连接,绑定到特定的表等等...

private const string cnString = "Server=localhost;Database=exam;Integrated Security=True";

protected void Button1_Click(object sender, EventArgs e)
{
    string sql = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = @search";
    DataSet ds = new DataSet();

    using (SqlConnection con = new SqlConnection(cnString))
    using (SqlCommand xp = new SqlCommand(sql, con))
    using (SqlDataAdapter da = new SqlDataAdapter(xp))
    {
        xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = TextBox1.Text;
        da.Fill(ds, "Name");
    }

    GridView1.DataSource = ds.Tables["Name"];
    GridView1.DataBind();
}