我正在创建一个包含X行和2列的动态表。这存储在视图状态中。
如何获得每行每个单元格的值?
请参阅我的代码示例:
<p>How many rows?<asp:TextBox ID="txtNoSitesDeployed" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /></p>
<asp:Table ID="dt" runat="server">
</asp:Table>
<asp:Button ID="btnGenerateEmail" runat="server" Text="Generate Email Content Bulk" onclick="btnGenerateEmail_Click" />
<p>
<asp:Label ID="lblTemplate" runat="server" Text=""></asp:Label>
</p>
请参阅代码隐藏:
public partial class _Default : System.Web.UI.Page
{
protected int Rows
{
get
{
return ViewState["Rows"] != null ? (int)ViewState["Rows"] : 0;
}
set
{
ViewState["Rows"] = value;
}
}
protected int Columns
{
get
{
return ViewState["Columns"] != null ? (int)ViewState["Columns"] : 0;
}
set
{
ViewState["Columns"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
this.Rows = Int32.Parse(txtNoSitesDeployed.Text);
this.Columns = 2;
}
}
protected void Button1_Click (object sender, System.EventArgs e)
{
// Total number of rows.
int rowCnt;
// Current row count.
int rowCtr;
// Total number of cells per row (columns).
int cellCtr;
// Current cell counter.
int cellCnt;
rowCnt = Rows;
for(rowCtr=1; rowCtr <= rowCnt; rowCtr++)
{
// Create a new row and add it to the table.
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
var txtSiteName = new TextBox();
txtSiteName.ID = "txtSiteName-" + rowCtr;
txtSiteName.ToolTip = "Enter site name";
cell1.Controls.Add(txtSiteName);
//add cell to row
row.Cells.Add(cell1);
TableCell cell2 = new TableCell();
var ddltBU = new DropDownList();
ddltBU.ID = "ddltBU-" + rowCtr;
ddltBU.Items.Add(new ListItem("fruit", "fruit"));
cell2.Controls.Add(ddltBU);
//add cell to row
row.Cells.Add(cell2);
//add row to dt
dt.Rows.Add(row);
}
}
protected void btnGenerateEmail_Click(object sender, EventArgs e)
{
foreach(TableRow row in dt.Rows)
{
foreach(TableCell cell in dt.Rows)
{
Response.Write(cell.Text);
}
}
}
}
我似乎无法访问单元格值。
非常感谢任何帮助