Получить значение динамически сгенерированных текстовых полей в коде после нажатия кнопки?

0

В приведенном ниже коде я динамически генерирую некоторые текстовые поля. И я пытаюсь получить там значения в событии click кнопки asp. Я пробовал много способов, но никто, кажется, не работает. Также я стараюсь избегать использования ajax для отправки значений. Любая помощь в этом вопросе будет по-настоящему оценена.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="product_entry.aspx.cs"Inherits="product_entry" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="pos.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

<script>
    $(document).ready(function() {
        var maxrow = 1;
        $('#TextBox1').val(maxrow);
        //var scrolled = 0;
        $("td.sno").each(function(index, element) {
            $(element).text(index + 1);
        });
        $(document).on("click", "button.remove", function() {
            $(this).parent().parent().remove();
            adding();
        });
        $(document).on("click", ".add, .remove,.tabrow:last", function() {
            numbering();
        });
        $(document).on("focus", ".tabrow:last", function() {
            // scrolled = scrolled + 200;

            //$("#table").animate({
            //   scrollTop: scrolled,20:"linear"
            //});

            adding();

        });

        function numbering() {

            $("td.sno").each(function(index, element) {
                $(element).text(index + 1);
                maxrow = index + 1;
            });



        }
        function iding() {

            $("tr").each(function(trIdx, element) {
                var trIndex = 'textbox' + (trIdx);
                // alert('hello');
                $(this).find("td > input").attr('id', function(idx) {
                    return trIndex + (idx + 1)
                });
            });
        }

        function adding() {
            $("tr.tabrow:first").clone(true).appendTo("#Table1");
            numbering();
            iding();
      $(".tabrow:last").children("td").children("input").each(function(index, element) {
                $(element).val("");
            });


            $('#TextBox1').val(maxrow);


        }
        $(document).on("click", ".check", function() {
            setdata();
        });
        function setdata() {
            var rowValues

            $("tr").each(function(index, value) {
                rowValues = new Array(); $(this).find('input').each(function() {
                    if ($(this).val() != '') {
                        alert('hello');
                        rowValues.push($(this).val());
                    }


                })
                alert("row" + index + " : " + rowValues);
                //do something with rowValues
            }
                     )

            $.ajax({
                type: "POST",
                url: "pdtentry.aspx/Done",
                contentType: "application/json; charset=utf-8",
                data: "{ info: rowValues}",
                dataType: "json",
                success: function(result) {
                    alert('Yay! It worked!');
                },
                error: function(result) {
                    alert('Oh no :(');
                }
            });


            return false;

        }
    });
</script>

</head>
<body>
<form id="form1" runat="server">
<div id="mhead">
  <asp:Label ID="Label1" runat="server" Text="Enter product into database"></asp:Label>
</div>
<div>
    <asp:TextBox ID="TextBox1" runat="server" Style="display: none;"></asp:TextBox>          
</div>
<asp:Panel ID="Pnl" runat="server">
    <div id="table">
        <asp:Table ID="Table1" runat="server">
            <asp:TableHeaderRow ID="head">
                <asp:TableHeaderCell ID="remove">-</asp:TableHeaderCell>
                <asp:TableHeaderCell ID="sno">S.No</asp:TableHeaderCell>
                <asp:TableHeaderCell ID="pdt_id">Product ID</asp:TableHeaderCell>
                <asp:TableHeaderCell ID="pdt_descp">Product Description</asp:TableHeaderCell>
                <asp:TableHeaderCell ID="plu">PLU</asp:TableHeaderCell>
                <asp:TableHeaderCell ID="pdt_type">Product Type</asp:TableHeaderCell>
                <asp:TableHeaderCell ID="cost">Cost</asp:TableHeaderCell>
                <asp:TableHeaderCell ID="discount">Discount</asp:TableHeaderCell>
                <asp:TableHeaderCell ID="qty">Quantity</asp:TableHeaderCell>
            </asp:TableHeaderRow>

        </asp:Table>
    </div>
</asp:Panel>
<div>
    <asp:Button ID="Button1" runat="server" Text="Button" CausesValidation="False" OnClick="Button1_Click"
        UseSubmitBehavior="False" /></div>
<input id="Button2" type="button" value="button" class="check" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</form>

И код позади

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Collections;
 using System.Web.Services;



public partial class product_entry : System.Web.UI.Page
{
int count;
static String[] a;

protected void Page_Load(object sender, EventArgs e)
{
int i,j;

    for (i = 0; i < 1; i++)
    {
        TableRow tr = new TableRow();
        tr.Attributes.Add("class", "tabrow");

        for (j = 0; j <= 8; j++)
        {
            TableCell tc = new TableCell();

            if (j == 0)
            {

                tc.Controls.Add(new LiteralControl("<Button class=remove type=button>-</button>"));

            }
            if (j == 1)
            {
                tc.Attributes.Add("class", "sno");
            }
            if (j == 2 || j == 3 || j == 4 || j == 5 || j == 6 || j == 7 || j == 8)
            {
                TextBox tb = new TextBox();


                tb.Style["width"] = "98%";

                tc.Controls.Add(tb);
            }
            tr.Controls.Add(tc);
        }
        Table1.Controls.Add(tr);
    }


}
[WebMethod]
public static string Done(string[] info)
{

    a = info;
    Label lb2=new Label();
    lb2.Text=""+a.Length;
    string str = string.Empty;
    return str;


}
protected void Button1_Click(object sender, EventArgs e)
{
    Label2.Text = TextBox1.Text;
       count = Convert.ToInt32(TextBox1.Text);
    for (int i = 1; i <= count; i++)
   {
       for (int j = 1; j <= 7; j++)
       {
           Response.Write("textbox" + i + j);
          string aa = ((TextBox)Pnl.FindControl("textbox" + i + j)).Text;
            Response.Write(((TextBox)Pnl.FindControl("textbox11")).Text);
    }
   }
    /* try
    {
        int count = Convert.ToInt32(TextBox1.Text);
        for (int i = 1; i <= count; i++)
        {
            for (int j = 1; j <= 7; j++)
            {
                Label l = new Label();

               string str = "textbox" + i + j;
               TextBox tb=((TextBox)this.FindControl(str)).Text;
                l.Text = tb.Text;
            }
        }
    }
    catch { }
    Panel[] pnls = new Panel[1] { Pnl };
    //ArrayList answers = new ArrayList();
    //Alternatively....
    ArrayList arrayList = new ArrayList();
    //string[] arr=new string[7];
    //arrayList.Add(arr);
    //for (int i = 0; i < 7  ; i++)
    //{
      // ArrayList list2 = new ArrayList();
       //arrayList.Add(list2);
     //}

    //System.Collections.Hashtable ht = new System.Collections.Hashtable();

    foreach (Panel Pnl in pnls)
    {
        foreach (Control childControl in Pnl.Controls)
        {
            if (childControl is TextBox)
            {
                TextBox box = (TextBox)childControl;
                //if(box.Text!=null)
                //Retrieve and store value from childControl.Text
                arrayList.Add(box.Text);
                foreach (int i in arrayList)
                {
                    Label l3 = new Label();
                    l3.Text = (String)arrayList[i];

                    //Alternatively...
                    //   ht.Add( box.ID, box.Text );
                }
            }
        }
    } */


}
}
  • 0
    После добавления некоторого значения в текстовые поля они не сохраняются. Почему? Существует ли конкретное значение req или проблема с кодом?
  • 0
    никакие значения не сохраняются, никаких конкретных значений не требуется.
Теги:

1 ответ

1
Лучший ответ

одним из способов является поиск элемента в коллекции Request.Forms

Request.From["controlName"] 

Это будет содержать требуемое значение. Обратите внимание, что он работает с Name а не с Id поэтому вы также должны указать Name.

  • 0
    пожалуйста, не могли бы вы предоставить код для применения того же самого в моем случае

Ещё вопросы

Сообщество Overcoder
Наверх
Меню