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

时间:2013-02-05 17:08:24

标签: c# asp.net dynamic rows

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

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

5 个答案:

答案 0 :(得分:3)

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

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

Table类包含一个table row collection,然后您需要循环。行集合中的每一行都有一个collection of cells,每个行都包含child controls(请参阅:控件属性),它们将是您的文本框。

答案 1 :(得分: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

中的表格数据

答案 2 :(得分: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);
    }
}

如果您有任何问题,请与我们联系。

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

答案 3 :(得分:0)

动态表的引用效果不好,怪微软,

我用这个:

保存在会话列表[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);
}

答案 4 :(得分:0)

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