无法在搜索中显示gridview数据

时间:2018-11-13 09:29:03

标签: c# asp.net gridview

加载页面时,我能够从数据库检索数据,显示到目前为止数据库中的所有数据。但是当我要使用文本框和搜索按钮时,出现错误消息“错误:必须声明标量变量@MRF_NO”。我的代码有问题吗?我将发布代码。

C#

private void searchsumm()
    {
        database db = new database();
        string database = db.MRF();
        using (SqlConnection con = new SqlConnection(database))
        {
            con.Open();

            string query = "Select MRF_No, BU, Dept,ReqByDept_Mngr FROM MRF_Details";
            using (SqlCommand com = new SqlCommand(query, con))

            if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
            {
                query += " WHERE ContactName LIKE @MRF_No + '%'";
                com.Parameters.AddWithValue("@MRF_No", txtSearch.Text.Trim());
            }

            using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt); //Error: Must declare the scalar variable "@MRF_No".
                smry.DataSource = dt;
                smry.DataBind();
            }
            con.Close();
        }

    }

ASP.NET

<div class="col-sm-4">
                <asp:TextBox ID="txtSearch" runat="server" ReadOnly="false" CssClass="form-control"></asp:TextBox>  
            </div>

            <div class="col-sm-5">
                <asp:Button ID="searchdb" runat="server" CssClass="btn" Text="Search" onclick="btnsummary"/>
            </div>

            <div class="row-space"></div>

        <asp:GridView runat="server" ID="smry" CssClass="list-group" AutoGenerateColumns="False" AllowPaging="true"  >

            <Columns>
                <asp:BoundField DataField="MRF_No" HeaderText="MRF No" SortExpression="MRF_No" />
                <asp:BoundField DataField="BU" HeaderText="Business Unit" SortExpression="BU" />
                <asp:BoundField DataField="Dept" HeaderText="Department" SortExpression="Dept" />
                <asp:BoundField DataField="ReqByDept_Mngr" HeaderText="Request By" SortExpression="ReqByDept_Mngr" />
            </Columns>

        </asp:GridView>

2 个答案:

答案 0 :(得分:0)

where 子句中,您的查询似乎有误:

query += " WHERE ContactName LIKE @MRF_No + '%'";

应该是:

query += " WHERE ContactName LIKE '%' + @MRF_No + '%'";

此外,我认为您需要通过传递刚刚构建的命令来创建 SqlDataAdapter ,以便查询包含您定义的参数。

using (SqlDataAdapter sda = new SqlDataAdapter(com))
{
     DataTable dt = new DataTable();
     sda.Fill(dt);
     smry.DataSource = dt;
     smry.DataBind();
}

答案 1 :(得分:0)

可能是语法问题。你能看下面是否可行:

query += " WHERE ContactName LIKE @MRF_No";
com.Parameters.AddWithValue("@MRF_No", "%" + txtSearch.Text.Trim() + "%");