【发布时间】:2021-07-01 22:08:24
【问题描述】:
我正在尝试动态返回一个搜索框,该搜索框将使用参数化的 addwithvalue 函数根据 SQL 之类的函数在表中给出产品名称。
我的 aspx 设计文件如下所示:
我在 aspx.cs 代码后面的代码是这样的。
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;
namespace KUD4
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("Select * from dbo.tblProductInventory where ProductName like @ProductName", connection);
cmd.Parameters.AddWithValue("@ProductName", TextBox1.Text + "%");
connection.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
}
当我尝试在搜索字段中输入任何文本并单击“获取产品”按钮时。网格视图没有到达。
我做错了什么?
我的桌子是这样的:
id ProductName QuantityAvailable
101 iPhone 101
102 Apple Laptops 100
103 Books 120
104 Acer Laptops 119
105 iPads 134
【问题讨论】:
-
ExecuteReader返回SqlDataReader,它不支持IList、IListSource、IBindingList或IBindingListView作为DataSource属性要求者。 -
代码中的解决方案是什么
-
它在没有参数化之前一直在工作我认为问题在于参数化代码而不是gridview
-
当
AddWithValue通过提供的值自动检测类型时,另一个问题可能是类型不匹配。假设列类型为Nvarchar,而自动检测类型为Varchar。为匹配 db 列类型的参数提供显式类型。 -
它的varchar在表中你会怎么改请举个例子让我试试