在页面加载列表视图搜索我不知道如何绑定数据

时间:2013-12-24 20:42:47

标签: asp.net

当我搜索用户名时,帮助我在页面加载时绑定搜索端的数据,我不知道如何将数据绑定到数据视图:

  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        DeleteCommand="DELETE FROM Users WHERE [UserID] = @UserID" 
        SelectCommand="SELECT * FROM Users WHERE UserRoles = 'Admin'" 

        UpdateCommand="UPDATE Users SET [Gender] = @Gender,[Username] = @Username,[Name] = @Name,[Address]=@Address,[State]=@State,[ZipCode]=@ZipCode,[Phone]=@Phone,[EmailAdd]=@EmailAdd,[City]=@City WHERE [UserID] = @UserID">
    </asp:SqlDataSource>

if (txtsearchstaff.Text != " " && txtsearchstaff.Text != "")
        {
            string strConString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlConnection myConnect = new SqlConnection(strConString);
            string cmd = "SELECT * FROM users WHERE Username=@Search";
            SqlDataAdapter da = new SqlDataAdapter(cmd, myConnect);
            da.SelectCommand.Parameters.AddWithValue("@Search", txtsearchstaff.Text);

           DataSet ds = new DataSet();
          /*  da.Fill(ds, );

            ListView1.DataSource = da;
            ListView1.DataBind();*/

            ListView1.DataSource = ds.Tables["table"];
           ListView1.DataBind();
        }

1 个答案:

答案 0 :(得分:0)

只需使用SqlCommand对象执行查询,然后将SqlDataReader绑定到列表视图,如下所示:

string strConString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

// Create a connection object, which gets disposed of by using block
using(var myConnect = new SqlConnection(strConString))
{
    // Make parameterized query to be executed by the command object
    string query = "SELECT * FROM users WHERE Username=@Search";

    // Create a command object to execute query, which gets disposed of by using block
    using(var theCommand = new SqlCommand(query, myConnect))
    {
        // Add the value for the @Search parameter
        theCommand.Parameters.AddWithValue("@Search", txtsearchstaff.Text.Trim());

        // Open the connection as late as possible
        myConnect.Open();

        // Store results of query in reader
        var theReader = theCommand.ExecuteRead();

        // Bind reader to list view
        ListView1.DataSource = theReader;
        ListView1.DataBind();
    }
}