【发布时间】:2017-01-13 08:58:34
【问题描述】:
我有一个GridView 绑定到一个DataSource。它的最后一列有一个带有逗号分隔的数字字符串的文字控件。那个字符串一定要拆分,那些数字一定要在自己的TextBox里(我不知道有多少提前):
这是最后一列的定义:
<asp:TemplateField HeaderText="Cantidades">
<ItemTemplate>
<asp:Literal ID="litCantidades" runat="server" Text='<%# Eval("CANTIDADES") %>'></asp:Literal>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
之后,在RowDataBound 事件中,我做了这样的事情:
private void CreaControlesCeldaCantidades(GridViewRow gridRow)
{
//Array of numbers got from the bound literal control in the cell.
int[] cantidades = GetCantidadesFromRow(gridRow);
TableCell cantidadesCell = gridRow.Cells[9];
//I don't want the literal control anymore.
cantidadesCell.Controls.Clear();
int i = 0;
//I create one TextBox per each number to put it
//inside, so the user can edit it.
foreach (var cantidad in cantidades)
{
var cantidadTextBox = new TextBox();
cantidadTextBox.ID = "txtCantidad" + i++;
cantidadTextBox.Text = cantidad.ToString();
cantidadTextBox.Width = Unit.Pixel(10);
cantidadTextBox.CssClass = "txtCantidad";
cantidadesCell.Controls.Add(cantidadTextBox);
}
}
到目前为止,一切都很好。问题出现在PostBack 上。我尝试恢复用户编辑的号码,但是当我尝试恢复时,所有TextBox创建的号码都消失了:
private void ValidarEntradasNumericas()
{
foreach (GridViewRow row in grvMaterialesTareas.Rows)
{
var chkSistematico = (CheckBox)row.FindControl("chkSistematico");
var txtSustitucion = (TextBox)row.FindControl("txtSustitucion");
var sustitucion = 0;
if (chkSistematico.Checked)
{
txtSustitucion.Text = "100";
}
else if (!int.TryParse(txtSustitucion.Text, out sustitucion))
{
throw new Exception("Uno de los códigos de sustitución indicados no es numérico. Por favor, corrija su valor.");
}
var cantidad = 0;
var cantidadesCell = row.Cells[9];
//Fails miserably and I don't know why :'(
foreach (TextBox txtCantidad in cantidadesCell.Controls)
{
if (!int.TryParse(txtCantidad.Text, out cantidad))
{
throw new Exception("Una de las cantidades indicadas no es numérica. Por favor, corrija su valor.");
}
}
}
}
我想知道为什么该解决方案不起作用以及如何使其起作用。
提前致谢:)
【问题讨论】:
标签: c# asp.net gridview webforms