3

我找到了创建动态表并添加行的教程:

http://geekswithblogs.net/dotNETvinz/archive/2009/06/29/faq-dynamically-adding-rows-in-asp-table-on-button-click.aspx

如何读取表格中的所有行,然后读取单元格中文本框的值?这些值被输入到数据库(SQL Server)的表中。我可以继续使用 C# 和 asp.net 还是必须使用 Javascript?

我希望有人能给我帮助。

这是代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dynamic Adding of Rows in ASP Table Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" />
    </form>
    </body>
</html>

代码背后:

public partial class _Default1 : System.Web.UI.Page
{
    //A global variable that will hold the current number of Rows
    //We set the values to 1 so that it will generate a default Row when the page loads
    private int numOfRows = 1;

    protected void Page_Load(object sender, EventArgs e)
    {
        //Generate the Rows on Initial Load
        if (!Page.IsPostBack)
        {
            GenerateTable(numOfRows);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (ViewState["RowsCount"] != null)
        {
            numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
            GenerateTable(numOfRows);
        }
    }

    private void SetPreviousData(int rowsCount, int colsCount)
    {
        Table table = (Table)Page.FindControl("Table1");
        if (table != null)
        {
            for (int i = 0; i < rowsCount; i++)
            {
                for (int j = 0; j < colsCount; j++)
                {
                    //Extracting the Dynamic Controls from the Table
                    TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
                    //Use Request objects for getting the previous data of the dynamic textbox
                    tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
                }
            }
        }
    }

    private void GenerateTable(int rowsCount)
    {

        //Creat the Table and Add it to the Page
        Table table = new Table();
        table.ID = "Table1";
        Page.Form.Controls.Add(table);

        //The number of Columns to be generated
        const int colsCount = 3;//You can changed the value of 3 based on you requirements

        // Now iterate through the table and add your controls

        for (int i = 0; i < rowsCount; i++)
        {
            TableRow row = new TableRow();
            for (int j = 0; j < colsCount; j++)
            {
                TableCell cell = new TableCell();
                TextBox tb = new TextBox();

                // Set a unique ID for each TextBox added
                tb.ID = "TextBoxRow_" + i + "Col_" + j;
                // Add the control to the TableCell
                cell.Controls.Add(tb);
                // Add the TableCell to the TableRow
                row.Cells.Add(cell);
            }

            // And finally, add the TableRow to the Table
            table.Rows.Add(row);
        }

        //Set Previous Data on PostBacks
        SetPreviousData(rowsCount, colsCount);

        //Sore the current Rows Count in ViewState
        rowsCount++;
        ViewState["RowsCount"] = rowsCount;
    }
}
4

5 回答 5

3

由于您是动态创建表格,因此您不能像静态嵌入在页面上的控件那样引用它。要获得对 Table 对象的引用,您需要在 Page 的 ControlCollection 中找到它并将其丢弃,就像在示例中一样:

Table table = (Table)Page.FindControl("Table1");

Table 类包含一个表格行集合,然后您需要对其进行循环。行集合中的每一行都有一个单元格集合,每个单元格都包含子控件(请参阅:控件属性),它们将是您的文本框。

于 2013-02-05T17:32:19.183 回答
2

嗨,如果你看一下SetPreviousData这个函数正在尝试读取以前的文本框值,但是它有一些问题我已经完成了以下更改,它首先工作正常,下面的代码SetPreviousData

 Table table = (Table)Page.FindControl("Table1");

始终返回 NULL,因为此函数不是递归函数,并且您的表可能位于页面中的容器内,因此请在代码中添加以下函数

private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }

    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }

    return null;
}

并更改代码

Table table = (Table)Page.FindControl("Table1");

Table table = FindControlRecursive(Page , "Table1") as Table;

在下一步中更改以下代码SetPreviousData

tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];

tb.Text = Request.Form[tb.UniqueID];

设置断点并查看结果,如果您觉得很难,请告诉我为您提供一个函数,该函数在datatable

于 2013-02-05T18:13:19.143 回答
0

动态表的参考效果不好,怪微软,

我用这个:

保存在会话 List[YourObjectData] 中,每次进入 Page_Load 时,将其填入表格

这是 2 号的解决方案:

Default.aspx 中的某处

<div class="specialTable">
    <asp:Table ID="Table1" runat="server"  />
</div>

后面的代码:

protected void Page_Load(object sender, EventArgs e)
{
    FillDynamicTable();

    if (!IsPostBack)
    {

    }
}

private void FillDynamicTable()
{
    Table1.Rows.Clear(); //  Count=0 but anyways

    if (Session["Table1"] == null) return;

    foreach (var data in Session["Table1"] as List<MyObject>)
    {
        AddRow(data);
    }
}

private void AddRow(MyObject data)
{
    var row = new TableRow { Height = 50 };
    var cell = new TableCell();
    var label = new Label { Text = data.something, Width = 150 };
    cell.Controls.Add(label);
    row.Cells.Add(cell);
    Table1.Rows.Add(row);
}
于 2014-02-23T09:42:02.820 回答
0

我认为您必须在事件中再次绑定您的表格。Page_load例如,如果您在View_Click按钮事件中绑定表格,则必须在事件中调用此方法Page_loadView_Click(null,null)

于 2014-11-20T04:42:41.347 回答
0
<script type="text/javascript">
       var StringToSend='';
       function fncTextChanged(newvalueadded) {
           if (StringToSend != '')
               StringToSend = StringToSend + ';' + newvalueadded;
           else
               StringToSend = newvalueadded;
           //alert(StringToSend); -- For Testing all values
           // now store the value of StringToSend into hidden field ---- HFTEXTVALUES to access it from server side.
         }

    </script>
     <asp:Button ID="Save" runat="server" onclick="SaveTextBoxValues_Click" Text="save" /> 
     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" /> 
    <asp:HiddenField ID="hfTextValues" runat="server" Visible="false" Value="" />

服务器端 :

protected void Page_Load(object sender, EventArgs e)
{
    //Generate the Rows on Initial Load
    if (!Page.IsPostBack)
    {
        GenerateTable(numOfRows);
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    if (ViewState["RowsCount"] != null)
    {
        numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
        GenerateTable(numOfRows);
    }
}
protected void SaveTextBoxValues_Click(object sender, EventArgs e)
{
    string AllTextBoxValues = hfTextValues.Value;
    string[] EachTextBoxValue = AllTextBoxValues.Split('~');
    //here you would get all values, EachTextBoxValue[0] gives value of first textbox and so on.
}

private void GenerateTable(int rowsCount)
{

    //Creat the Table and Add it to the Page
    Table table = new Table();
    table.ID = "Table1";
    Page.Form.Controls.Add(table);

    //The number of Columns to be generated
    const int colsCount = 3;//You can changed the value of 3 based on you requirements

    // Now iterate through the table and add your controls

    for (int i = 0; i < rowsCount; i++)
    {
        TableRow row = new TableRow();
        for (int j = 0; j < colsCount; j++)
        {
            TableCell cell = new TableCell();
            TextBox tb = new TextBox();
            HiddenField hf = new HiddenField();
            // Set a unique ID for each TextBox added
            tb.ID = "tb" + i + j;
            hf.ID = "hf" + i + j;
            tb.Attributes.Add("onblur", "fncTextChanged(this.value);");
            // Add the control to the TableCell
            cell.Controls.Add(tb);
            // Add the TableCell to the TableRow
            row.Cells.Add(cell);
        }

        // And finally, add the TableRow to the Table
        table.Rows.Add(row);
    }
}

如果您有任何问题,请告诉我。

还有一件事,如果您希望存储这些值并稍后检索它们,代码将相应地进行修改。

于 2013-02-05T21:44:34.773 回答