简体   繁体   中英

how to load datatable using dataset in c#

I have a working gridview that uses a dataset called dsCustomers. I am making changes to be able to search the gridview (upon key press search). I got the search process to work by using DataTable that gets populated by using sqlDataReader (make a connection and then run SQL SELECT). But sqlDataReader does not provide me all the desired data's field because there are some data's that are populated from outside source (outside the database). So I need to populate the DataTable with the dsCustomers dataset.

Here is the complete code:

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

Can someone please provide some guidance or direction on how to accomplish this? thanks

Use a 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;
}

As Tim Schmelter points out, you don't want connections open for too long, but your current code shown does not allow me to refactor. I am just focusing on the immediate issue :)

You can use a SqlDataAdapter for both, filling a DataTable and a DataSet :

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);
} 

Note that you should close the connection as soon as possible (all the more in ASP.NET), that's why i have used using . With connection-pooling enabled(default) closing it will just mark it as "unused".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM