【问题标题】:dynamic search using stored procedure asp.net使用存储过程 asp.net 进行动态搜索
【发布时间】:2015-12-29 19:14:05
【问题描述】:

在 asp.net 中使用存储过程实现动态搜索时遇到问题 我有一个用于考勤系统的数据表和数据库 这是我的 Default.aspx.cs 代码

public partial class _Default : Page
{
    static string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            this.gridData();
            this.search();
        }
    }
    //--------------------------------------------------
    private void gridData()
    {
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT EventUserId, EventDate, EventTime, Eventtype, Readerid FROM V_EventLogs"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    DataTable dt = new DataTable();
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();

                }
            }
        }
    }

    private DataTable search()
    {
        DataTable sdt = new DataTable();
        SqlConnection con = new SqlConnection(constr);
        try
        {

            SqlCommand cmd = new SqlCommand("userSearch", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandTimeout = 300;
            cmd.Parameters.AddWithValue("@EventUserId", TextBox1.Text);
            cmd.Parameters.AddWithValue("@EventDateFrm", ASPxDateEdit1.Text);
            cmd.Parameters.AddWithValue("@EventDateTo", ASPxDateEdit2.Text);
            cmd.Parameters.AddWithValue("@Readerid", txtReader.Text);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            // passs parameter to data adapter
            SqlDataAdapter sda = new SqlDataAdapter(cmd);

            sda.Fill(sdt);

        }
        catch (Exception ex)            {
            Response.Write(ex);
        }

        return sdt;
    }



   //---------------------------------------------------


    protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        this.gridData();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {    
        GridView1.DataSource = search();
        GridView1.DataBind();
    }

}

}

这是我的 Default.aspx 页面:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<div class="jumbotron">
    <h1>BioWeb TimeTel</h1>
    <p class="lead">Time Attendance</p>
    <%--<p><a href="http://www.asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>--%>
</div>
<div>

        User ID:
        &nbsp;<asp:TextBox ID="TextBox1" runat="server" CssClass="form-control"></asp:TextBox>
        &nbsp;
        <br />
        <br />
        Event Date:
        &nbsp;&nbsp;
        <br />
        <dx:ASPxDateEdit ID="ASPxDateEdit1" runat="server" DisplayFormatString="MM/dd/yyyy" EditFormatString="MM/dd/yyyy">
        </dx:ASPxDateEdit>
        <br />
        Event Time:
        <br />
        &nbsp;<dx:ASPxDateEdit ID="ASPxDateEdit2" runat="server" DisplayFormatString="MM/dd/yyyy" EditFormatString="MM/dd/yyyy">
        </dx:ASPxDateEdit>
        &nbsp;
        <br />
        <br />
        Reader:
        &nbsp;<asp:TextBox ID="txtReader" runat="server" CssClass="form-control" AutoCompleteType="Disabled"></asp:TextBox>
        &nbsp;
        <br />
        <br />
        &nbsp
        <br />
        <br />
        <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" CssClass="btn btn-primary btn-lg" OnLoad="Page_Load" />
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
        OnPageIndexChanging="OnPageIndexChanging" PageSize="10" UseAccessibleHeader="True" CssClass="table table-hover">
        <Columns>
            <asp:BoundField DataField="EventUserId" HeaderText="User ID" />
            <asp:BoundField DataField="EventDate" HeaderText="Date IN" />
            <asp:BoundField DataField="EventTime" HeaderText="Time IN" />
            <asp:BoundField DataField="Eventtype" HeaderText="Type" />
            <asp:BoundField DataField="Readerid" HeaderText="Reader" />

        </Columns>
    </asp:GridView>     
    </div>

我的存储过程是:

CREATE procedure userSearch
(
@EventUserId int = NULL,
@EventDateFrm nvarchar(10) = NULL,
@EventDateTo nvarchar(10) = NULL,
@Readerid int = NULL
)
as
select V_EventLogs.EventUserId,V_EventLogs.EventDate,V_EventLogs.EventTime,V_EventLogs.Eventtype,V_EventLogs.Readerid 
from V_EventLogs 
where
(@EventUserId is NULL OR EventUserId = @EventUserId )
AND
(@EventDateFrm is NULL OR Convert(varchar(10),EventDate,110) >= Convert(varchar(10),@EventDateFrm,110))
AND 
(@EventDateTo is NULL OR Convert(varchar(10),EventDate,110)  <= Convert(varchar(10),@EventDateTo,110))
AND
(@Readerid is NULL OR Readerid = @Readerid)

现在,当我想搜索员工时,网格数据表仍然是空的并且没有得到任何值,但是当我在 SQL Server 上测试我的存储过程运行良好时 - 第二个问题是当我选择任何其他页面时,分页数据表动态搜索仅适用于第一页,搜索实现不起作用并且数据表显示所有数据库值!为什么??

【问题讨论】:

  • 为什么不在方法外声明 Datatable 并在从 gridData() 方法返回数据后进行绑定更改签名以返回数据表也在 Page_Load 中有一个 else并将那里的数据也绑定到数据网格..应该是一个简单的修复..您还可以在调试时确认调用Fill方法时数据是否实际加载到数据表中
  • 你的分页也应该是下面的GridView1.CurrentPageIndex = e.NewPageIndex; 然后像这样分配数据源和数据绑定GridView1.DataSource = sdt; //将数据表实例移到方法之外使其成为公共或静态GridView1.DataBind();
  • 您熟悉 PostBacks..吗?但是在您的 Page_Load 事件中有一个断点,您会看到哪里出错了..您需要一个 if (IsPostBack) else { } 您不需要检查 == false 要么做 if(!IsPostBack){} else{} 要么做 if(IsPostBack){} else{}

标签: c# asp.net sql-server stored-procedures datatable


【解决方案1】:

答案就在您的问题中。您没有在 PageIndexChanging 中进行任何搜索...

protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    this.gridData();
}

上面的代码只是简单地重新绑定整个数据,因为您的 gridData() 方法检索所有记录,设置 NewPageIndex 只会将您移动到该页面。

尝试编写如下内容:

protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = search();
    }

这不是一个完美的解决方案。应该使用存储过程本身实现的分页;此 SP 应将页面索引和每页记录数作为输入以及其他搜索条件;您需要构建动态 SQL 以在 SP 中获取相应的页面结果并将其绑定回 Grid。一个简单的 Google 搜索可能会为您提供替代解决方案。但是,上述更改应该可以按您的意愿进行。

【讨论】:

  • 这也不起作用,数据网格不会出现或显示任何搜索结果,但存储过程在 Sql Server 中工作正常
  • 只要不理解和实现正确的分页概念,这里很难解释;网上有很多文章;我建议您在实施之前了解后端分页的概念
【解决方案2】:

我建议你只在Fill命令后关闭连接,不要调用ExecuteNonQuery,像这样:

    SqlCommand cmd = new SqlCommand("userSearch", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandTimeout = 300;
    cmd.Parameters.AddWithValue("@EventUserId", TextBox1.Text);
    cmd.Parameters.AddWithValue("@EventDateFrm", ASPxDateEdit1.Text);
    cmd.Parameters.AddWithValue("@EventDateTo", ASPxDateEdit2.Text);
    cmd.Parameters.AddWithValue("@Readerid", txtReader.Text);

    // passs parameter to data adapter
    SqlDataAdapter sda = new SqlDataAdapter(cmd);

    con.Open();
    sda.Fill(sdt);
    con.Close();

如果您想使用 DataAdapter。否则,您可以直接检索数据:

    SqlCommand cmd = new SqlCommand("userSearch", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandTimeout = 300;
    cmd.Parameters.AddWithValue("@EventUserId", TextBox1.Text);
    cmd.Parameters.AddWithValue("@EventDateFrm", ASPxDateEdit1.Text);
    cmd.Parameters.AddWithValue("@EventDateTo", ASPxDateEdit2.Text);
    cmd.Parameters.AddWithValue("@Readerid", txtReader.Text);

    con.Open();
    var reader = cmd.ExecuteReader();
    var dtbl = new DataTable();
    dtbl.Load(reader);
    con.Close();

当然最好将所有内容放入 try-catch 并使用“使用”..... :-)

【讨论】:

  • 我试过你的代码,但没有工作同样的错误数据表没有任何数据,我已经在使用 try catch 但没有异常
  • 您的搜索函数仅在 btnSearch_Click 事件处理程序上调用。您是否尝试过使用相同的参数直接调试和运行 SP?
  • 是的,我已经在 Sql Server 上尝试过 SP,它正在工作,但是当我调用它时,它没有从 SP 获得任何搜索值,并且数据网格没有出现
【解决方案3】:

可以创建动态搜索SQL server存储过程

创建 PROCEDURE CUSTOMER.GET_DynamicSearch ( -- 动态搜索的可选过滤器 @CustomerID INT = NULL, @CustomerName NVARCHAR(50) = NULL, @CustomerTitle NVARCHAR(50) = NULL, @locationId int = NULL, @ControlCardNumber bigint = NULL, @Formnumber int = NULL ) 作为 开始 设置无计数 宣布 @lCustomerID INT = NULL, @lCustomerName NVARCHAR(50) = NULL, @lCustomerTitle NVARCHAR(50) = NULL, @llocationId int = NULL, @lControlCardNumber bigint = NULL, @lFormnumber int = NULL 设置@lCustomerID = @CustomerID SET @lCustomerName = LTRIM(RTRIM(@CustomerName)) SET @lCustomerTitle = LTRIM(RTRIM(@CustomerTitle)) SET @llocationId = LTRIM(RTRIM(@locationId)) SET @lControlCardNumber = @ControlCardNumber SET @lFormnumber = LTRIM(RTRIM(@Formnumber)) 选择 c.客户ID, c.客户名称, c.CustomerTitle, c.LocationId, c.ControlCardNumber, c.FormNumber FROM CUSTOMER.客户 c 在哪里 (@lCustomerID 为 NULL 或 CustomerId = @lCustomerID) AND(@lCustomerName 为 NULL 或 CustomerName LIKE '%' +@lCustomerName + '%') AND(@lCustomerTitle 为 NULL 或 CustomerTitle LIKE '%' + @lCustomerTitle + '%') AND(@llocationId 为 NULL 或 locationId = @llocationId ) AND(@lControlCardNumber 为 NULL 或 ControlCardNumber = @lControlCardNumber) AND(@lFormnumber 为 NULL 或 Formnumber = @lFormnumber) ORDER BY c.CustomerID asc 结尾 去

执行细节

EXEC CUSTOMER.GET_DynamicSearch -- 2000 条记录

-- 仅提供 CustomerName 参数:

EXEC CUSTOMER.GET_DynamicSearch @CustomerName= 'Uttam' -- 1040 条记录

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多