2

I want to retrieve the recipe names from the database and need to display the data in the list form. I have added the code behind. But what do I include in the template.

Source

<asp:ListView ID="ListView1" runat="server">
                    <ItemTemplate>

                    </ItemTemplate>
                </asp:ListView>

Code behind

protected void Page_Load(object sender, EventArgs e)
{

    MySqlConnection con = new MySqlConnection("Server=localhost;Database=FreedomKitchen;Uid=root;Password=;");
    con.Open();
    MySqlCommand cmd = new MySqlCommand("select Recipe_Name from Recipes", con);
    MySqlDataAdapter da = new MySqlDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds, "Recipe_Names");
    ListView1.DataSource = ds;
    ListView1.DataBind();
}

3 Answers 3

0

you can add a label if you want to display only data '>

or textbox if you want to edit the data

1
  • Hi, I need want the list item to be like a link to the next page, which will show a detailed view of the recipe. So which is a desirable implementation? Would button work? How can I implement on item listener on this...? Thanks May 7, 2016 at 10:10
0

You can add ASP.NET controls in the template and then use the Eval method to bind to the value of a field from your dataset:

<asp:ListView ID="ListView1" runat="server">
    <ItemTemplate>
        <asp:Label ID="recipe_name" 
                   runat="Server" 
                   <!-- in eval you use the name of a field/property 
                        found in your collection or datatable    
                   -->
                   Text='<%#Eval("Recipe_Name") %>' />
    </ItemTemplate>
</asp:ListView>

You can find the documentation for itemtemplates on MSDN

0

You can put in the <ItemTemplate> whatever you want to display in the specific list view item.

In addition, I think it will be easier for you to map DataSet into appropriate collection of Recipe type.

For example, in the designer:

<ItemTemplate>
   <asp:Label runat="server" ID="lbl"></asp:Label>
</ItemTemplate>

Code Behind:

void Page_Load(object sender, EventArgs e) 
{
    ...Code...
    ListView1.ItemDataBound += new EventHandler<System.Web.UI.WebControls.ListViewItemEventArgs>(ListView1_ItemDataBound);
}

private void ListView1_ItemDataBound(object sender, System.Web.UI.WebControls.ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        var recipeName = e.Item.DataItem as *Your_Recipe_Class_Type*;
        if (recipeName != null)
        {
            Label lbl = e.Item.FindControl("lbl");
            lbl.Text = recipeName.*DesiredProperty*;
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.