类似的论坛上发表投票主题:
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:DataList ID="DataList1" runat="server" Width="100%" BorderWidth="1" ondeletecommand="MinusItemList_DeleteCommand">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#("OptionName")%>'></asp:TextBox>
<asp:Button ID="Button1" runat="server" CommandName="delete" Text="删除" />
</ItemTemplate>
</asp:DataList>
<asp:Button ID="Button2" runat="server" οnclick="Button2_Click" Text="添加项" />
<asp:Button ID="Button3" runat="server" Text="保存" οnclick="Button3_Click" />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</form>
</body>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebCommonLib.DataList
{
public partial class Demo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable table = new DataTable();
table.Columns.Add("OptionName", typeof(string));
for (int i = 0; i < 5; i++)
{
DataRow row = table.NewRow();
row["OptionName"] = string.Empty;
table.Rows.Add(row);
}
ViewState["table"] = table;
DataList1.DataSource = table;
DataList1.DataBind();
}
}
protected void MinusItemList_DeleteCommand(object source, DataListCommandEventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
Table.Rows[item.ItemIndex]["OptionName"] = (item.Controls[1] as TextBox).Text;
}
Table.Rows.RemoveAt(e.Item.ItemIndex);
DataList1.DataSource = Table;
DataList1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
DataRow row = Table.NewRow();
Table.Rows.Add(row);
DataList1.DataSource = Table;
DataList1.DataBind();
}
private DataTable Table {
get {
if (ViewState["table"] != null)
return (DataTable)ViewState["table"];
return null;
}
}
protected void Button3_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
Literal1.Text += (item.Controls[1] as TextBox).Text;
}
}
}
}