C# - 在没有数据源控件的情况下绑定GridView Eval数据

时间:2014-02-14 15:04:07

标签: c# sql gridview datatable system.data.datatable

我希望在不使用数据源控件的情况下填充(排序的)GridView(称为SearchResultsGid)。我做了一些研究,我猜我可能需要使用数据集和数据来成功绑定网格,但我不完全确定如何做到这一点。我更习惯使用数据源控件....

网格视图使用Eval语句,如果可能的话我想保留它,因为它允许字段是到其他页面的超链接。虽然,如果有另一种方式,我愿意尝试...

SearchResultsGrid的要点是,当用户在文本字段中键入内容然后点击“搜索”按钮时,会弹出一个网格,其中包含数据库中的所有相关结果。有一个转发器显示用户已添加用于查看的所有数据库项目,但此刻与我无关(无论如何它都可以正常工作)。

任何帮助将不胜感激! :)

以下是代码:

<table cellpadding="4" cellspacing="0" class="inputForm" width="100%">
    <tr><td width="100%"><p align="justify">Select the products that should have this option.</p></td></tr>
    <tr>
        <td valign="top">
           <asp:Label ID="errorLbl" ForeColor="Red" Font-Bold="true" runat="server" Text=""></asp:Label>
            <asp:UpdatePanel ID="MainContentAjax" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <div class="section">
                        <div class="header"><h2><asp:Localize ID="FindProductsCaption" runat="server" Text="Find Products" /></h2></div>
                        <asp:Panel ID="SearchFormPanel" runat="server" CssClass="content" DefaultButton="SearchButton">
                            <table class="inputForm">
                                <tr>
                                    <th class="rowHeader"><cb:ToolTipLabel ID="SearchNameLabel" runat="server" Text="Product Name:" ToolTip="Enter all or part of a product name.  Wildcard characters * and ? are accepted." /></th>
                                    <td><asp:TextBox ID="SearchName" runat="server" Text="" /></td>
                                    <th class="rowHeader"><cb:ToolTipLabel ID="ShowImagesLabel" runat="server" Text="Show Thumbnails:" ToolTip="When checked, product images will be displayed in the search results." /></th>
                                    <td><asp:CheckBox ID="ShowImages" runat="server" /></td>
                                    <td><asp:LinkButton ID="SearchButton" runat="server" Text="Search" SkinID="Button" OnClick="SearchButton_Click" /></td>
                                </tr>
                            </table>

                            <cb:SortedGridView ID="SearchResultsGrid" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductId" GridLines="None" SkinID="PagedList" Width="100%" AllowPaging="true" Visible="false" DefaultSortExpression="Name" EnableSortingAndPagingCallbacks="True" PageIndex="0" AllowSorting="True">

                                <Columns>
                                    <asp:TemplateField HeaderText="Thumbnail">
                                        <ItemStyle HorizontalAlign="Center" />
                                        <ItemTemplate>
                                            <asp:HyperLink ID="NodeImageLink" runat="server" NavigateUrl='<%# UrlGenerator.GetBrowseUrl((int)Eval("ProductId"), CatalogNodeType.Product, (string)Eval("Name")) %>'> <asp:Image ID="NodeImage" runat="server" ImageUrl='<%# Eval("ThumbnailUrl") %>' Visible='<%# !string.IsNullOrEmpty((string)Eval("ThumbnailUrl")) %>' AlternateText='<%# Eval("Name") %>' /> </asp:HyperLink>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="SKU" SortExpression="Sku">
                                        <HeaderStyle HorizontalAlign="Left" />
                                        <ItemTemplate>
                                            <asp:HyperLink ID="ProductSku" runat="server" Text='<%#Eval("Sku")%>' SkinID="FieldHeader" /><br />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Item" SortExpression="Name" > 
                                        <HeaderStyle HorizontalAlign="Left" />
                                        <ItemTemplate>
                                            <asp:HyperLink ID="ProductName" runat="server" Text='<%#Eval("Name")%>' SkinID="FieldHeader" /><br />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Assigned">
                                        <ItemStyle Width="50px" HorizontalAlign="Center" />
                                        <ItemTemplate>
                                            <asp:ImageButton ID="AttachButton" runat="server" CommandArgument='<%#Container.DataItemIndex%>' AlternateText="Add" ToolTip="Add" SkinID="AddIcon" OnClientClick="this.visible=false" OnClick="AttachButton_Click" Visible='<%#!IsProductLinked(((Product)Container.DataItem).ProductId)%>' />
                                            <asp:ImageButton ID="RemoveButton" runat="server" CommandArgument='<%#Container.DataItemIndex%>' AlternateText="Remove" ToolTip="Remove" SkinID="DeleteIcon" OnClientClick="return confirm('Are you sure you want to remove this item from this option?')" OnClick="RemoveButton_Click" Visible='<%#IsProductLinked(((Product)Container.DataItem).ProductId)%>' />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                                <EmptyDataTemplate>
                                    There are no products that match the search text.
                                </EmptyDataTemplate>
                            </cb:SortedGridView>
                        </asp:Panel>
                    </div>
                    <div class="section">
                        <div class="header"><h2>Assigned Products</h2></div>
                        <div class="content">
                            <asp:Repeater ID="RelatedProductGrid" runat="server" SkinID="PagedList" OnItemCommand="RelatedProductGrid_RowDeleting">
                                <HeaderTemplate>
                                    <table width="100%" class="pagedList" cellpadding="0" cellspacing="0">
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <tr class="oddRow">
                                        <td>
                                            <asp:Label ID="ProdID" runat="server" Text='<%#Eval("ProductId") %>' Visible="false" />
                                            <asp:HyperLink ID="ProductName2" runat="server" Text='<%#Eval("Name")%>' NavigateUrl='<%#Eval("ProductId", "/Admin/products/EditProduct.aspx?ProductId={0}")%>' />
                                        </td>
                                        <td><asp:ImageButton ID="RemoveButton2" runat="server" SkinID="DeleteIcon" CommandName="Delete" CommandArgument='<%#Eval("ProductId") %>' AlternateText="Remove" ToolTip="Remove" OnClientClick="return confirm('Are you sure you want to remove this item from this option?')" /></td>
                                    </tr>
                                </ItemTemplate>
                                <AlternatingItemTemplate>
                                    <tr class="evenRow">
                                       <%--  <td>
                                            <asp:Label ID="ProdID2" runat="server" Text='<%#Eval("ProductId") %>' Visible="false" />
                                            <asp:HyperLink ID="ProductSku" runat="server" Text='<%#Eval("Sku")%>' NavigateUrl='<%#Eval("ProductId", "/Admin/products/EditProduct.aspx?ProductId={0}")%>' />
                                        </td>--%>
                                        <td>
                                            <asp:Label ID="ProdID" runat="server" Text='<%#Eval("ProductId") %>' Visible="false" />
                                            <asp:HyperLink ID="ProductName2" runat="server" Text='<%#Eval("Name")%>' NavigateUrl='<%#Eval("ProductId", "/Admin/products/EditProduct.aspx?ProductId={0}")%>' />
                                        </td>
                                        <td><asp:ImageButton ID="RemoveButton2" runat="server" SkinID="DeleteIcon" CommandName="Delete" CommandArgument='<%#Eval("ProductId") %>' AlternateText="Remove" ToolTip="Remove" /></td>
                                    </tr>
                                </AlternatingItemTemplate>
                                <FooterTemplate>
                                    </table>
                                </FooterTemplate>
                            </asp:Repeater>
                        </div>
                    </div>
                    <asp:Button ID="FinishButton" runat="server" Text="Finish" OnClick="FinishButton_Click" /><br />
                    <br />

                </ContentTemplate>
            </asp:UpdatePanel>
        </td>
    </tr>
</table>

我开始使用函数来填充SearchResultsGrid,而SQL命令就是在获取按钮点击的正确信息方面的意思。我打算在按钮点击内调用此功能。

protected void PopulateSearchGrid()
{
    try 
    {
        System.Data.SqlClient.SqlDataReader dr = null;

        DataSet ds = new DataSet();
        DataTable resultsTbl = ds.Tables.Add("resultsTbl");
        using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter("SELECT OptionID, ac_Products.Name, Sku FROM ac_Options, ac_Products WHERE OptionID = @OptionID AND ac_Products.Name = @Name", cn))
            {
               ///and this is where I'm getting confused on what to do :(
            }
        }

    }
    catch { }
}

1 个答案:

答案 0 :(得分:1)

您可以使用DataTable对象,使用SQL查询填充它,并将其分配给网格的数据源。 使用您的DataAdapter用您的SQL查询填充DataTable(介意将列名与GridView上的列名匹配)

DataTable dt = new DataTable();
//use your DataAdapter to fill the data table
sda.Fill(dt);
SearchResultsGrid.DataSource = dt;
SearchResultsGrid.DataBind();

您的查询正在使用参数,因此您可能希望使用SqlCommand而不是直接在SqlDataAdapter上指定SQL。
SqlCommand cmd = new SqlCommand("Your Query",cn);
cmd.Parameters.Add("Your first parameter", your param value);
cmd.Parameters.Add("Your second parameter", your param value);
... new SqlDataAdapter(cmd)...