How to retrieve the input values from Dynamically

2019-09-17 13:47发布

问题:

I have a DropDownList bounded with list of items from SqlDataSource. With the help of DropDownList_SelectedIndexchanged() function i am able to generate two dynamic text boxes.

Required Output: I need to search for the data based on the textbox inputs given by the user and Searched data shall be displayed in JQGrid with the help of Button_Click() event.

Current Issue: The textbox inputs are not retrieved and it always retrieved as null string "". Exception obtained is : Incorrect Syntax near "AND" (SQL Query)

How to solve this issue?

My aspx code:

<asp:Panel ID="Panel5" runat="server" Height="221px">
            <span style="font-size: 135%; font-family: Verdana; font-weight: bold"> Search Functionalities </span>
            <asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="column_list_for_filter" DataTextField="All_Columns" DataValueField="All_Columns" OnSelectedIndexChanged ="DropDownList5_SelectedIndexChanged"  AutoPostBack="true">
            </asp:DropDownList>
            <asp:SqlDataSource ID="column_list_for_filter" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" SelectCommand="SELECT COLUMN_NAME 'All_Columns' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='RESULT'  "></asp:SqlDataSource>
            <asp:Button ID="Button1" runat="server" Font-Bold="True" Font-Names="Arial" Font-Size="Small" OnClick="Button1_Click" Text="Search Flow Periods" Width="144px" />
            <asp:Table ID="dynamic_filter_table" runat="server" ToolTip="Results">
            </asp:Table>
</asp:Panel>

My C# code:

//Creation of Two Dynamic Text Box Web Controls on DDL selection
     protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
     {
         createdynamiccontrols();

     }

    /*Two Text Boxes and Two Labels for input and search the FlowPeriod and display in JqGrid      
    thru button click event*/
     protected void createdynamiccontrols()//(string ID1, string ID2)
     {
         int i = DropDownList5.SelectedIndex;
         ++i;
         TableRow row;
         row = new TableRow();
         TableCell cell1 ;
         cell1 = new TableCell();
         TableCell cell2;
         cell2= new TableCell();
         // Set a unique ID for each TextBox added
         TextBox tb1;
         tb1 = new TextBox();
         TextBox tb2;
         tb2 = new TextBox();
         Label lbl1;
         lbl1 = new Label();
         Label lbl2;
         lbl2 = new Label();
         // Set a unique ID for each TextBox added      
         tb1.ID = "lowerbound_" + i.ToString();
         tb2.ID = "upperbound_"+ i.ToString() ;
         lbl1.Text = "LowerBound:";
         lbl1.Font.Size = FontUnit.Point(10);
         lbl1.Font.Bold = true;
         lbl1.Font.Name = "Arial";
         lbl2.Text = "UpperBound:";
         lbl2.Font.Size = FontUnit.Point(10);
         lbl2.Font.Bold = true;
         lbl2.Font.Name = "Arial";
         // Add the control to the TableCell       
         cell1.Controls.Add(lbl1);
         cell1.Controls.Add(tb1);
         cell2.Controls.Add(lbl2);
         cell2.Controls.Add(tb2);
         // Add the TableCell to the TableRow  
         row.Cells.Add(cell1);
         row.Cells.Add(cell2);
         dynamic_filter_table.Rows.Add(row);
         dynamic_filter_table.EnableViewState = true;
         ViewState["dynamic_filter_table"] = true;
         Button1.EnableViewState = true;
         ViewState["Button_1"] = true;
     }

     protected override object SaveViewState()
     {
         object[] viewstate = new object[2];
         List<string> dynamic_text_values  = new List<string>();
         foreach (TableRow row in dynamic_filter_table.Controls)
         {
             foreach (TableCell cell in row.Controls)
             {
                 if (cell.Controls[1] is TextBox)
                 {
                     dynamic_text_values.Add(((TextBox)cell.Controls[1]).Text);
                 }
             }
         }
         viewstate[0] = dynamic_text_values.ToArray();
         viewstate[1] = base.SaveViewState();
         return viewstate;
     }

    protected override void LoadViewState(object savedState)
     {
         if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[])
         {
             object[] newViewState = (object[])savedState;
             string[] txtValues = (string[])(newViewState[0]);
             if (txtValues.Length > 0)
             {
                createdynamiccontrols();

             }
             base.LoadViewState(newViewState[1]);
         }
         else
         {
             base.LoadViewState(savedState);
         }
     }


     protected void Button1_Click(object sender, EventArgs e)
    {
        createdynamiccontrols();                 
        int j = DropDownList5.SelectedIndex;
        ++j;
        Panel6.Visible = true;
        JQGrid9.Visible = true;
        TextBox lowerboundd = dynamic_filter_table.FindControl("lowerbound_" + j.ToString()) as TextBox;
        TextBox upperbound = dynamic_filter_table.FindControl("upperbound_" + j.ToString()) as TextBox;
        string testt = lowerboundd.Text;
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("SELECT ColumnName1,Columnname2 FROM RESULT WHERE " + DropDownList5.SelectedValue + " >= " + lowerboundd.Text + " AND " + DropDownList5.SelectedValue + " <= " + upperbound.Text, con);
        DataSet ds = new DataSet();
        da.Fill(ds);

        /*Error occurs here as Incorrect Syntax near AND as the string obtained is "" and not          
        textbox inputs*/

        con.Close();
        Session["DataforSearch"] = ds.Tables[0];

     }

protected void Page_Load(object sender, EventArgs e)
    {           
        //Dynamic controls creation on Page Load
        if (!IsPostBack)
        {
            BindDropDownLists();

        } 
        dynamic_filter_table.EnableViewState = true;
    }

回答1:

You need to move BindDropDownLists(); to the Page_Init method from Page_Load or else the page lifecycle will not find the viewstate and attach to your controls. By the time you are in Page_Load you are too late. Make sure your logic to create the controls in init and your logic to retrieve the data in load/events and you should see some results.

You don't need the viewstate stuff as that will automagically wire itself up, you can't create the dynamic controls in a control event like click or selectedindexchanged as thats too late in the lifecycle. The dynamic controls need to be created before load for the viewstate to be wired by the time load comes around.

More Reading