peter411
peter411

Reputation: 19

Asp.Net Website Data Binding DataList

I need help with the Data Binding in a Asp.Net Website Project. I build a Data List at the Frontend and now a want to bind a easy String called "Test" to this Data List. How can I achive this?

 <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" %>

<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)
    {
        DataList1.DataSource = "Test";
        DataList1.DataBind();
    }


</script>




<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent1" Runat="Server">
    <form id="form1" runat="server">
    <div class="contentText">

       <div class="row">
       <label for="name">Name:</label>
           <input type="text" id="name" name=""><br><br>
       </div>

       <div class="row">
           <label for="address">Address:</label>
           <input type="text" id="address" name=""><br><br>
       </div>

       <div class="row">
           <label for="phone">Phone:</label>
           <input type="tel" id="phone" name=""><br><br>
       </div>

       <div class="row">
           <label for="email">Email:</label>
           <input type="email" id="email" name="">

           <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

           <asp:DataList ID="DataList1" runat="server">

           </asp:DataList>

       </div>
        </div>
    </form>
</asp:Content>

Hope anyone can help me. Thanks...

Upvotes: 1

Views: 1214

Answers (1)

Denys Wessels
Denys Wessels

Reputation: 17049

DataList is a control which should be used to display a repeatable list of data which implements either IListSource or IEnumerable interfaces.If you want t bind a single value just use a label instead.But anyway, if you really want to force binding a single value to the DataList here's an example:

.ASPX:

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:DataList ID="DataList1" runat="server">
    <ItemTemplate>
        <asp:Label Text='<%# Eval("Value") %>' runat="server" />
    </ItemTemplate>
</asp:DataList>

Code behind:

protected void Button1_Click(object sender, EventArgs e)
{
   DataList1.DataSource = new List<object> { new { Value = "Test" } };
   DataList1.DataBind();
}

Upvotes: 1

Related Questions