从asp.net webform中检索数据

时间:2014-09-15 04:45:36

标签: asp.net gridview dataadapter

这个程序有什么问题?     它显示da.Fill(dt);中的错误。此程序用于按名称从DataBase搜索记录。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Threading.Tasks;

public partial class NameSearch : System.Web.UI.Page
{
    public SqlConnection con = new 

       SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].   
       ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {        
        SqlCommand cmd = new SqlCommand("select * from case1 where     
        Name="+txtSearchName.Text,con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet dt = new DataSet();
        da.SelectCommand = cmd;
        da.Fill(dt);
        GridView1.DataSource = dt;
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

2 个答案:

答案 0 :(得分:0)

您必须在commandtype而不是Text中使用StoredProcedure。使用参数化查询来避免sql注入

string name=txtSearchName.Text;
SqlCommand cmd = new SqlCommand("select * from case1 where Name=@name",con);
cmd .Parameters.AddWithValue("@name", name);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();

答案 1 :(得分:0)

   SqlCommand cmd = new SqlCommand("select * from case1 where     
    Name='"+txtSearchName.Text + "'",con);
    cmd.CommandType = CommandType.Text;
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds= new DataSet();
    da.SelectCommand = cmd;
    da.Fill(ds, "FooTable");
    GridView1.DataSource = ds.Tables["FooTable"];;
    cmd.ExecuteNonQuery();
    con.Close();
相关问题