2014-12-05 68 views
0

我有一个使用名为dsCustomers的数据集的工作gridview。我正在进行更改以便能够搜索gridview(在按键搜索时)。通过使用通过使用sqlDataReader填充的DataTable(建立连接然后运行SQL SELECT),我可以使搜索过程工作。但是sqlDataReader并没有为我提供所有需要的数据字段,因为有一些数据是从外部来源(数据库外部)填充的。所以我需要用dsCustomers数据集填充DataTable。如何使用c中的数据集加载数据表#

下面是完整的代码:

<%@ Page Language="C#" MasterPageFile="~/Master.master" AutoEventWireup="true" Inherits="Customers" Title="Customers" Codebehind="Customers.aspx.cs" EnableEventValidation="false"%> 

    <%@ Register assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" namespace="System.Web.UI.WebControls" tagprefix="asp" %> 
    <%@ Import Namespace="System.Data" %> 
    <%@ Import Namespace="System.Data.SqlClient"%> 
    <asp:Content ID="cntMain" ContentPlaceHolderID="plcMainBody" runat="Server"> 
    <script runat="server"> 
     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString()); 
      SqlCommand cmd = new SqlCommand(); 
      DataView dv = new DataView(); 


      DataTable dt = new DataTable(); 
      DataTable dtsort = new DataTable(); 


      private DataTable DataTable 
      { 
       get { return (DataTable)Session["DataTable"]; } 
       set { Session["DataTable"] = value; } 
      } 
      private DataView DataView 
      { 
       get { return (DataView)Session["DataView"]; } 
       set { Session["DataView"] = value; } 
      } 
      protected override void OnLoad(EventArgs e) 
      { 
       base.OnLoad(e); 
       if (!this.IsPostBack) 
       { 
        DataTable dt; 

        if (this.DataTable == null) 
         LoadDataToTable(); 
        else dt = this.DataTable; 
        this.txtNumber.Attributes.Add("onkeyup", string.Format("javascript:__doPostBack('{0}','')", this.upnlGridView.ClientID)); 
       } 
       else 
       { 
        string target = this.Request.Form["__EVENTTARGET"]; 
        if (!string.IsNullOrEmpty(target) && target.Equals(this.upnlGridView.ClientID)) 
        { 
         if (!string.IsNullOrEmpty(this.txtNumber.Text)) 
         { 
          Filter(); 
         } 
         else 
         { 
          this.grvItems.DataSource = this.DataTable; 
          this.grvItems.DataBind(); 
         } 
        } 
       } 
      } 
      private void Filter() 
      { 
       if (!string.IsNullOrEmpty(this.txtNumber.Text)) 
       { 
        DataRow[] rows = this.DataTable.Select(string.Format("ID LIKE '%{0}%'", this.txtNumber.Text)); 
        this.grvItems.DataSource = this.LoadData(rows); 
        this.grvItems.DataBind(); 
       } 
      } 


      private void LoadDataToTable() 
      { 
     //   con.Open(); 
     //   cmd.Connection = con; 
     //   cmd.CommandText = "select * from Users";    --I NEED TO USE THE DATASET   //  RETURN HERE (dsCustomers) 
    //  cmd.CommandType = System.Data.CommandType.Text; 
    // 
    //    SqlDataAdapter adapter = new SqlDataAdapter(cmd); 
    //    DataSet dsCustomers = new DataSet(); 
    //   adapter.Fill(dsCustomers); 

       this.grvItems.DataSource = dsCustomers; 
    //    this.grvItems.DataBind(); 
       Session["DataTable"] = dt; 
      } 
      protected void PageIndexChanging(object sender, GridViewPageEventArgs e) 
      { 


      } 
      protected void Sorting(object sender, GridViewSortEventArgs e) 
      { 
       BindData(e.SortExpression); 
      } 


      private void BindData(string sortExpression) 
      { 
       // reset the dataview, else it will be undefined value! 
       dv = (DataView)Session["DataView"]; 
       if (sortExpression.Length > 0) 
       { 
        dv.Sort = sortExpression; 
        // save the dataview in stateless environment 
        Session["DataView"] = dv; 
       } 
       this.grvItems.DataSource = dv; 
       this.grvItems.DataBind(); 
      } 
      private DataTable LoadData() 
      { 
       return this.LoadData(null); 
      } 
      private DataTable LoadData(DataRow[] rows) 
      { 
       DataTable dt = this.GetTable(); 


       if (rows != null) 
       { 
        foreach (DataRow r in rows) 
        { 
         dt.Rows.Add(r[0], r[1]); 
        } 


       } 
       dv = dt.DefaultView; 
       Session["DataView"] = dv; 
       return dt; 
      } 
      private DataTable GetTable() 
      { 
       DataTable dt = new DataTable(); 
       dt.Columns.Add("ID", String.Empty.GetType()); 
       dt.Columns.Add("Role", String.Empty.GetType()); 
       return dt; 
      } 
     </script> 


    </head> 
    <body> 

     <asp:ScriptManager runat="server" ID="PageScriptManager" /> 
     Search EID: 
     <asp:TextBox runat="server" ID="txtNumber" AutoPostBack="true" /> 

     <asp:UpdatePanel runat="server" ID="upnlGridView"> 
      <ContentTemplate> 
       <hr /> 
       <asp:GridView runat="server" ID="grvItems" AllowPaging="True" AllowSorting="True" 
        AutoGenerateColumns="False" PageSize="20" OnRowEditing="grvItems_RowEditing" 
         ShowFooter="True" OnRowCommand="grvItems_RowCommand" 
        OnRowCreated="grvItems_RowCreated" OnRowDeleted="grvItems_RowDeleted" 
        CellPadding="5" DataSourceID="dsCustomers"> 
         <AlternatingRowStyle CssClass="DataGridAlternate" /> 
         <RowStyle CssClass="DataGridItemStyle" /> 
         <HeaderStyle CssClass="Header"></HeaderStyle> 
         <FooterStyle CssClass="DataGridAlternate"></FooterStyle> 
         <Columns> 
          <asp:TemplateField> 
           <HeaderStyle HorizontalAlign="Center" Width="40px" VerticalAlign="Middle" /> 
           <ItemStyle HorizontalAlign="Center" /> 
           <ItemTemplate> 
            <asp:ImageButton runat="server" ImageUrl="images/icon-pencil.gif" AlternateText="Edit" 
             CommandName="Edit" CausesValidation="False" ID="btnEdit"></asp:ImageButton> 
            <asp:ImageButton runat="server" ImageUrl="images/icon-delete.gif" AlternateText="Delete" 
             CommandName="Delete" CausesValidation="False" ID="btnDelete" OnClientClick="return confirm('Are you sure you want to delete?');"> 
            </asp:ImageButton> 
           </ItemTemplate> 
          </asp:TemplateField> 
          <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" /> 
          <asp:BoundField DataField="Role" HeaderText="Role" SortExpression="Role" /> 
          <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" /> 
          <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" /> 
          <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" /> 
          <asp:BoundField DataField="PhoneNumber" HeaderText="Phone Number" SortExpression="PhoneNumber" /> 
          <asp:BoundField DataField="LOCATION" HeaderText="Location" SortExpression="dsCustomers" /> 
         </Columns> 
       </asp:GridView> 
      </ContentTemplate> 
     </asp:UpdatePanel> 


     <table width="100%"> 
      <tr> 
       <td width="10%">&nbsp;</td> 
       <td align="left"> 
        <asp:Label ID="lblMessage" runat="server" Text="" CssClass="error"></asp:Label> 
       </td> 
      </tr> 


       </td> 
      </tr> 
     </table> 
     <asp:ObjectDataSource ID="dsCustomers" runat="server" SelectMethod="GetDataDictionary" 
      TypeName="DataObjects.dsCustomers " InsertMethod="AddUpdate" 
      UpdateMethod="AddUpdate" DeleteMethod="Delete"> 
      <SelectParameters> 
       <asp:Parameter Name="ID" Type="String" ConvertEmptyStringToNull="False" DefaultValue="ALL" /> 
      </SelectParameters> 
      <UpdateParameters> 
       <asp:Parameter Name="ID" Type="String" /> 
       <asp:Parameter Name="Role" Type="String" /> 
      </UpdateParameters> 
      <InsertParameters> 
       <asp:Parameter Name="ID" Type="String" /> 
       <asp:Parameter Name="Role" Type="String" /> 
      </InsertParameters> 
      <DeleteParameters> 
       <asp:Parameter Name="EID" Type="String" /> 
      </DeleteParameters> 
     </asp:ObjectDataSource> 


    </asp:Content> 

可有人请提供关于如何做到这一点一些指导或方向? 感谢

+0

错误表明您正在从GridView的数据源获取'DataSet',而没有将其转换为'DataSet'。使用:'dsCustomers = grvItems.DataSource作为数据集;' – Habib 2014-12-05 15:04:02

+0

@Habib:除了他们目前正在使用'DataTable' ...所以演员阵容将失败。他们需要使用'SqlDataAdapter'来加载'DataSet'。 – 2014-12-05 15:04:50

+0

@TrueBlueAussie,可能我错了,但我认为当前的代码必须使用现有gridview中的'DataSet'或* something *来更改。这取决于OP。 – Habib 2014-12-05 15:07:35

回答

1

使用SqlDataAdapter

private void LoadDataToTable() 
{ 
    con.Open(); 
    cmd.Connection = con; 
    cmd.CommandText = "select * from Users"; 
    cmd.CommandType = System.Data.CommandType.Text; 

    SqlDataAdapter adapter = new SqlDataAdapter(cmd); 
    DataSet dataset = new DataSet(); 
    adapter.Fill(dataset); 

    this.grvItems.DataSource = dataset; 
    this.grvItems.DataBind(); 
    Session["DataTable"] = dt; 
} 

作为Tim Schmelter指出,你不希望连接打开的时间过长,但显示你当前的代码不会让我重构。我只是专注于眼前的问题:)

+0

我第一次得到'DataSource和DataSourceID都是在'grvItems'上定义的。删除一个定义。'在搜索列上的值时未找到列。 DataTable似乎没有被填充。我还使用dsCustomers更新数据集,其中Dataset dataset = new DataSet();线。 – user1774445 2014-12-08 14:16:36

+0

其实我认为这是'fill'之间的冲突,然后用它作为DataSource。尝试将DataSource设置为'adapter'而不是'dataset'(我自己没有尝试过)。 – 2014-12-08 14:18:57

+0

我上传了上面的完整代码。 – user1774445 2014-12-08 14:53:32

0

您可以使用既SqlDataAdapter,尽显DataTableDataSet

DataSet ds = new DataSet(); 
using(var con = new SqlConnection("Connection-String")) 
using (var da = new SqlDataAdapter("select * from Users", con)) 
{ 
    // you don't need to use con.Open which is done by Fill automatically 
    da.Fill(ds); 
} 

请注意,您应该关闭连接尽快(全在ASP.NET中越多),这就是为什么我使用using。启用连接池(默认)关闭后,它会将其标记为“未使用”。

相关问题