将SqlDataSource链接到ASP.NET中单个项的标签

2skhul33  于 5个月前  发布在  .NET
关注(0)|答案(2)|浏览(67)

我有一个asp:SqlDataSource,它返回一个单行。我如何将该值返回到标签中。我让它在asp:DataList中工作,但由于它是一个单一的记录,它的杀伤力过大。

<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
            ConnectionString="<%$ ConnectionString %>" 
            SelectCommand="SELECT  STATEMENT">
        </asp:SqlDataSource>

        <asp:DataList ID="DataList5" runat="server" DataSourceID="SqlDataSource2">
            <ItemTemplate>
                <asp:Label ID="label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label><br />
            </ItemTemplate>
        </asp:DataList>

字符串

h9vpoimq

h9vpoimq1#

下面是一个在C#中实现的方法:

DataView oDV = (System.Data.DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);

Label1.Text = string.Join("|", oDV.Table.Rows[0].ItemArray.Select(p => p.ToString()).ToArray());

字符串

sbdsn5lh

sbdsn5lh2#

我猜我的项目使用了一个实际的方法,而不是像我最初建议的那样使用一个属性。
您可以使用text SqlCommand(String, SqlConnection),将select语句和SqlConnection(String)传递到数据库。

public string GetSelectStatement()
{
  SqlConnection conn = new SqlConnection(ConnectionString);
  string selectStatement = "SELECT TOP 1 ID FROM Customer";
  SqlCommand comm = new SqlCommand(selectStatement, conn);
  comm.CommandType = System.Data.CommandType.Text;
  SqlDataReader reader = comm.ExecuteReader();
  
  // My code has a While loop, but you shouldn't need it with only one record
  reader.Read();
  string ID = (string)reader["ID"];
  return ID;
}

字符串
然后,在页(aspx)或控件(ascx)中,可以使用该方法绑定标签文本.

<asp:Label ID="label1" runat="server" Text='<%# GetSelectStatement() %>'></asp:Label>

相关问题