【问题标题】:Read all rows and cell values dynamic table asp.net读取所有行和单元格值动态表asp.net
【发布时间】:2017-04-21 04:13:01
【问题描述】:

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

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

【问题讨论】:

  • 你能把你的代码贴在这里吗,我以前用过类似的方法。我可以帮你。您需要为每个文本框指定 textchanged 事件,并且在客户端使用 javascript 您可以更改文本框的 ID 和值,然后使用隐藏字段将其保存在服务器端以临时存储它们。
  • 代码中是否总是返回null Table table = (Table)Page.FindControl("Table1");设置断点并检查

标签: c# asp.net dynamic rows


【解决方案1】:

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

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

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

【讨论】:

  • 在这个例子中的表总是返回 null
  • 表格的 ID 是“Table1”还是您给了它不同的 ID?
【解决方案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 中返回表数据的函数

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:
      <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);
          }
      }
      

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

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

      【讨论】:

      • 能否请您提供一些关于现在将 StringToSend 的值存储到隐藏字段中的代码 ---- HFTEXTVALUES 以便从服务器端访问它
      【解决方案5】:

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

      我用这个:

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

      【讨论】:

        猜你喜欢
        • 2013-05-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 2016-03-10
        • 2017-11-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多