如何在c#中使用数据集加载数据表

时间:2014-12-05 15:01:07

标签: c# sql asp.net gridview datatable

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

以下是完整的代码:

    <%@ 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>

有人可以就如何做到这一点提供一些指导或指导吗? 感谢

2 个答案:

答案 0 :(得分: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指出的那样,您不希望连接打开太长时间,但显示的当前代码不允许我重构。我只关注当前的问题:)

答案 1 :(得分:1)

您可以使用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的原因。启用连接池(默认)关闭后,它会将其标记为&#34;未使用&#34;。