HTML code
Create a aspx page with a list box, text box and 2 buttons as shown below.
<div style="margin: 0 auto; text-align: center;">
<table border="0">
<tr>
<td>
<asp:Label ID="lblfoodnames" runat="server" Text="List of Foods" Font-Bold="true"></asp:Label>
</td>
<td>
<asp:ListBox ID="lbnames" runat="server" Width="180px" BackColor="AliceBlue" Height="120px">
</asp:ListBox>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:TextBox ID="txtadditems" Width="180px" BackColor="AliceBlue" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnaddItems" runat="server" Text="Add Food"
onclick="btnaddItems_Click" />
<asp:Button ID="btnremoveItems" runat="server" Text="Remove Food"
onclick="btnremoveItems_Click" />
</td>
</tr>
</table>
</div>

C# code In cs page add the following code for the Add Food button click event to add new items in list box.
protected void btnaddItems_Click(object sender, EventArgs e)
{
// add the value from textbox to list
lbnames.Items.Add(txtadditems.Text);
// clear the textbox after adding
txtadditems.Text = "";
}
Next for the Remove Food button add the following code
protected void btnremoveItems_Click(object sender, EventArgs e)
{
// get the selected item
ListItem selected = lbnames.SelectedItem;
// remove the items
lbnames.Items.Remove(selected);
}
Now to text the code enter some values in text box and click Add Food button and see the result as shown below.

To remove the item from list. Select the item and click remove food button as shown below.

No comments:
Post a Comment