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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14712980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:46:37  来源:igfitidea点击:

Read all rows and cell values dynamic table asp.net

c#asp.netdynamicrows

提问by dany88

I found the tutorial to create a dynamic table and add rows:

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

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

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

How can I read all rows in the table, and then the values ??of the textbox in the cells? The values ??are entered in a table in a database (SQL Server). Can I continue to use C# and asp.net or do I have to use Javascript?

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

I hope someone will give me help.

我希望有人能给我帮助。

This is the code:

这是代码:

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

CODE BEHIND:

背后的代码:

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

回答by pwnyexpress

Since you're creating the table dynamically, you can't reference it like controls that are statically embedded on the page. To get a reference to the Table object you'll need to find it in the Page's ControlCollection and cast it out, just like in the example:

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

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

The Table class contains a table row collectionwhich you will then need to loop over. Each row in the row collection has a collection of cells, each of which will contain child controls(see: Controls property) which will be your textboxes.

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

回答by saeed

Hi if you take look at SetPreviousDatathis function is trying to read previous textbox value but there is some thing wrong with it i have done following changes and it works fine first of all the following code in SetPreviousData

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

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

is always returning NULL because this function is not a recursive function and your table may be inside a container in your page so add following function to your code

总是返回 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;
}

and change the code

并更改代码

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

to

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

in next step change the following code in SetPreviousData

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

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

to

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

set break points and see the results if it's tough to you let me know to provide you a function which returns table data in a datatable

设置断点并查看结果,如果您觉得困难,请告诉我为您提供一个返回表数据的函数 datatable

回答by Ruchi

<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="" />

Server Side :

服务器端 :

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

Let me know if you have any questions.

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

One more thing, if you wish to store the values and retrieve them later, the code would be modified accordingly.

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

回答by Zakos

reference for a dynamic table doesn't work well , blame microsoft ,

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

I use this :

我用这个:

Save inside a session List[YourObjectData] and every time you get into Page_Load , fill it the table

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

here is solution for number 2 :

这是数字 2 的解决方案:

somewhere inside Default.aspx

Default.aspx 中的某处

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

Code behind:

后面的代码:

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

回答by sumit

I think you must bind your table again at the Page_loadevent.For example if you are binding the table at View_Clickbutton event,you have to call this method in Page_loadevent as View_Click(null,null).

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