读取所有行和单元格值动态表asp.net

本文关键字:动态 asp net 单元格 读取 | 更新日期: 2023-09-27 17:58:02

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

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;
    }
}

读取所有行和单元格值动态表asp.net

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

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

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

嗨,如果你看看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 中的表数据

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

<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);
    }
}

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

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

对动态表的引用不能很好地工作,这要归咎于微软、

我使用这个:

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

这是第二个问题的解决方案:

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);
}