Asp.net

如何在 Eval 格式字元串中使用單引號

  • June 29, 2009

我有一個Repeater,它的SqlDatasource 嵌套在一個Gridview TemplatedField 中。

中繼器的數據源 SelectCommand 使用來自 Gridview 的 Eval 的 FormatString 設置。

SelectCommand 有一個用於比較字元串的 WHERE 子句。

因為我已經使用了單引號和雙引號,所以我無法在 SQL WHERE 子句中分隔字元串。

如何在 Eval FormatString 中添加單引號?

我試過使用“替換”。

我嘗試過使用“特殊字元”(… WHERE StringField = ‘{0}’ …)

到目前為止沒有運氣。感謝您提供的任何幫助。

<asp:GridView ID="GridView1" runat="server" DataSourceID="DataSource1" DataKeyNames="Foo" AutoGenerateColumns="False" AllowSorting="true" >
   <Columns>
       <asp:BoundField DataField="Foo" HeaderText="Foo" SortExpression="Foo" />
       <asp:BoundField DataField="Bar" HeaderText="Bar" SortExpression="Bar" />
       <asp:TemplateField>
           <ItemTemplate>
               <asp:Repeater ID="Repeater1" runat="server" DataSourceID="DataSourceNested">
                   <ItemTemplate>
                       <asp:Label ID="Label1" runat="server" Text='<%# Eval("Blah") %>'></asp:Label>
                   </ItemTemplate>
               </asp:Repeater>
               <asp:SqlDataSource ID="DataSourceNested" runat="server" DataFile="~/App_Data/DatabaseName"
                   SelectCommand='<%# Eval("Bar", "SELECT Blah FROM TableName WHERE (StringField = {0})") %>' >
               </asp:SqlDataSource>
           </ItemTemplate>
       </asp:TemplateField>
   </Columns>
</asp:GridView>

不要忘記 .aspx 頁面只是 XML。您只需像往常一樣轉義引號。

例如:

<asp:Repeater ID="repeatTheLabel" runat="server">
   <ItemTemplate>
       <asp:Label ID="Label1" Text="<%# Eval("Id", "This is item '{0}'.") %>" runat="server" />
   </ItemTemplate>
   <SeparatorTemplate>
       <br />
   </SeparatorTemplate>
</asp:Repeater>

當上述表達式被數據綁定時,介於<%#和之間的值%>變為:

Eval("Id", "This is item '{0}'.")

…當與具有“Id”屬性值從 1 到 5 的對像數組進行數據綁定時,它在 HTML 頁面上作為輸出生成:

這是項目'1’。

這是項目'2’。

這是項目'3’。

這是項目'4’。

這是項目'5’。

引用自:https://stackoverflow.com/questions/264414