【问题标题】:how to load datatable using dataset in c#如何在c#中使用数据集加载数据表
【发布时间】:2015-02-03 18:59:47
【问题描述】:

我有一个使用名为 dsCustomers 的数据集的工作网格视图。我正在进行更改以便能够搜索 gridview(在按键搜索时)。我使用通过使用 sqlDataReader 填充的 DataTable(建立连接然后运行 ​​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>

有人可以就如何实现这一点提供一些指导或指导吗? 谢谢

【问题讨论】:

  • 该错误表明您正在从 GridView 的数据源获取DataSet,而没有将其转换为DataSet。使用:dsCustomers = grvItems.DataSource as DataSet;
  • @Habib:除了他们现在使用DataTable...所以演员表会失败。他们需要使用SqlDataAdapter 来加载DataSet
  • @TrueBlueAussie,可能是我读错了问题,但我认为当前代码必须使用现有 gridview 或 something 中的 DataSet 进行更改。这取决于 OP。

标签: c# sql asp.net gridview datatable


【解决方案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 指出的那样,您不希望连接打开太久,但是您当前显示的代码不允许我重构。我只关注眼前的问题:)

【讨论】:

  • 我第一次得到'数据源和数据源ID都是在'grvItems'上定义的。删除一个定义。后跟在列上搜索值时未找到列。 DataTable 似乎没有被填充。我还使用 dsCustomers 更新了数据集,其中 Dataset dataset = new DataSet();行。
  • 其实我认为这是fill 之间的冲突,然后将其用作数据源。尝试将 DataSource 设置为 adapter 而不是 dataset(我自己没有尝试过)。
  • 哎哟。这是一个全新的球赛,因为大部分配置都在页面中。我已经很多年没有使用过 ASP.net(现在 100% MVC/Razor),所以必须把它留给专家 :)
【解决方案2】:

您可以同时使用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 的原因。启用连接池(默认)关闭它只会将其标记为“未使用”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 2011-10-21
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多