简体   繁体   English

表中的动态复选框不会保留选中的值

[英]dynamic check boxes in a table won't hold checked value

I am dynamically creating a table with data and check boxes in it, my problem is when i check to see one specific check-box is checked, out of many, it resets to the default state of false (note: its not just one it doesn't work with, it works with non of the generated check boxes)我正在动态创建一个包含数据和复选框的表,我的问题是当我检查是否选中了一个特定的复选框时,它会重置为默认的 state 的 false (注意:它不仅仅是一个它不适用于,它适用于非生成的复选框)

Before i create the page_load function i create the check box, further down i create the table, and populate it with data, then i set up a function to check on a click to see if the box was indeed checked, iv'e tried many iterations of this with no luck在我创建 page_load function 之前,我创建了复选框,再往下创建表,并用数据填充它,然后我设置了一个 function 以单击以检查该框是否确实被选中,我尝试了很多没有运气的迭代

protected void  table_builder(SqlDataReader readerinfo)
{
    //Create a new step for the user
    step3label.Text = "3.";
    //Table header
    TableHeaderRow hr = new TableHeaderRow();
    TableHeaderCell hc = new TableHeaderCell();
    TableHeaderCell hc2 = new TableHeaderCell();
    TableHeaderCell hc3 = new TableHeaderCell();
    hr.Cells.Add(hc);
    hc.Text = "ID"; //Assign header 1 with a name
    hr.Cells.Add(hc2);
    hc2.Text = "Name";//Assign header 2 with a name
    hr.Cells.Add(hc3);
    hc3.Text = "Selection";
    Table1.Rows.Add(hr);


    //Dynamic Table Generation
    int numcells = 3;
    int triswitch = 0;//this is use to chose which cell is made, id, name or selection
    string checkboxID = null;


    while (readerinfo.Read())   //execute the following aslong as there is data to fill the table with
    {
        for (int j = 0; j < 1; j++)
        {
            TableRow r = new TableRow();
            for (int i = 0; i < numcells; i++)
            {
                TableCell c = new TableCell();

                switch (triswitch)
                {
                    case 0: // this case sets the info for the feild id
                        c.Text = readerinfo.GetSqlGuid(0).ToString();
                        checkboxID = readerinfo.GetSqlGuid(0).ToString();
                        r.Cells.Add(c);
                        triswitch = 1;
                        break;

                    case 1:
                        c.Text = readerinfo.GetString(1);
                        r.Cells.Add(c);
                        triswitch = 2;
                        break;

                    case 2:
                        Checkbox_creator(checkboxID,ref c);
                        r.Cells.Add(c);
                        triswitch = 0;
                        break;

                }
            }
            Table1.Rows.Add(r);
        }
    }       
}

protected void Checkbox_creator(string id,ref TableCell send)
{
    //create the checbox
    ckbx = new CheckBox();
    ckbx.ID = "CBX" + checkboxid.ToString();
    checkboxid++;
    ckbx.InputAttributes.Add("value", id);
    send.Controls.Add(ckbx); //add the chekbox to the cell
    checkboxidlist.Add(id);//add the id of the checkbox to the list 
}



//
//AFTER DATATABLE IS LOADED
//

public void test()
{
    // Find control on page.
    CheckBox myControl1 = (CheckBox)Table1.FindControl("CBX0");
    if (myControl1 != null)
    {
        // Get control's parent.
        Control myControl2 = myControl1.Parent.Parent.Parent;
        Response.Write("Parent of the text box is : " + myControl2.ID);
        if (myControl1.Checked == true)
        {
            Response.Write("check box checked");
        }
    }
    else
    {
        Response.Write("Control not found");
    }
}
 //on Submit button click, execute the following function
protected void Submit_Click(object sender, EventArgs e)
{
    //Code to be executed
    string Userinput; //declare Userinput variable
    Userinput = Searchbox.Value; // Set variable to asp controll        
    Response.Write("<br /> <br />"+ Userinput +" <- user imput works");
    ConnectToSql(Userinput);//insert what the user submitted into a query
    test();
    //
    //
    //NoTe code validation is needed to prevent injections
    //  
}

So basically what is happening here is that you are dynamically dropping this onto the page every time the page loads.所以基本上这里发生的事情是每次页面加载时你都会动态地将它放到页面上。 Because you are doing this dynamically, the checkbox that fires off a "checked" event or is checked against during a postback no longer exists as it is not part of the viewstate.因为您正在动态执行此操作,所以触发“已检查”事件或在回发期间检查的复选框不再存在,因为它不是视图状态的一部分。 The way that the ASP.NET page lifecycle works is to fire off the sequence of lifecycle events regardless of whether or not the page is posted back or not, meaning that a new page is built upon you firing a postback event and the page goes through preinit, init, preload, load, and all that jazz before it actually hits any of the event handling code. ASP.NET 页面生命周期的工作方式是触发生命周期事件序列,无论页面是否回发,这意味着新页面是在您触发回发事件并且页面经过 preinit 时构建的, init、preload、load 和所有的爵士乐在它实际命中任何事件处理代码之前。 The page that exists for the postback has a freshly created set of checkboxes that have no binding to the ones that were on the previous page.为回发而存在的页面有一组新创建的复选框,这些复选框与前一页上的复选框没有绑定。

You have a few options here, and here are two of them:这里有几个选项,这里有两个:

Have the 'checked' event fire a postback and have the unique ID of the web control checked against a collection you maintain on the server.让“checked”事件触发回发,并根据您在服务器上维护的集合检查 web 控件的唯一 ID。 You can drop the controls onto the page via a repeater or gridview and hook into its populate event.您可以通过中继器或 gridview 将控件拖放到页面上,并挂钩到其填充事件。 In doing so you can add the unique ID of the control that was just added into a Dictionary that you store in session that maintains any relationship that you want from a checkbox to a piece of data.在这样做时,您可以添加刚刚添加到字典中的控件的唯一 ID,该字典存储在 session 中,该字典维护您想要的从复选框到数据的任何关系。

Use Javascript to update a hidden field that is always on the page and has view state enabled.使用 Javascript 更新始终在页面上并启用视图 state 的隐藏字段。 In doing so you can have some sort of delimited string containing the information you deem relevant to the 'checked' checkboxes.在这样做时,您可以使用某种分隔字符串,其中包含您认为与“已选中”复选框相关的信息。 Every time a checkbox is checked, add its identifying information to the hidden input field's value and then when the postback fires you should be able to check that hidden input for its value and do whatever you need to do from there.每次选中复选框时,将其标识信息添加到隐藏输入字段的值,然后当回发触发时,您应该能够检查隐藏输入的值并从那里执行您需要执行的任何操作。

These both seem like pretty hairy ways of handling this though.不过,这两种方法似乎都非常麻烦。 If you elaborate on what exactly you need then perhaps I can give you a better suggestion.如果你详细说明你到底需要什么,那么也许我可以给你一个更好的建议。

add the check boxes to the page before the view state is loaded and the event fires.在加载视图 state 并触发事件之前,将复选框添加到页面。 Do it in the OnInit method not the onload.在 OnInit 方法而不是 onload 中执行此操作。 Use Onload to see if they're checked or not.使用 Onload 查看它们是否被选中。 Be sure you're giving them ID's.一定要给他们身份证。 Unless this is a partial postback (ajax) then only render the check boxes if !IsPostback除非这是部分回发 (ajax),否则仅在 !IsPostback 时呈现复选框

It appears after two days of searching, i have found a pretty good solution that is much quicker and easier to understand than some others;经过两天的搜索,我发现了一个很好的解决方案,它比其他一些更快、更容易理解; It appears that as the other answers state, it is because of the page_load, however in this situation init is not needed, you simply need to recreate all of the controls before you can do anything else.似乎与其他答案 state 一样,这是因为 page_load,但是在这种情况下不需要 init,您只需要重新创建所有控件即可执行其他任何操作。

The key to this solution is:这个解决方案的关键是:

protected void RecreatePreviousState()
{
    if (this.IsPostBack)
    {
        //code to recreate
    }       
}

Where the comment in the above code is, is where you call the main function that creates all of your controls, like in my example it was:上面代码中的注释所在的位置是您调用创建所有控件的主要 function 的位置,就像在我的示例中一样:
ConnectToSql(Searchbox.Value) below will be all of the code associated with this page, for future reference for anyone with this problem.下面的ConnectToSql(Searchbox.Value)将是与此页面相关的所有代码,以供以后遇到此问题的任何人参考。

Code Behind:代码背后:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;


public partial class codebehind : System.Web.UI.Page 
{
//DECLARATIONS    
string selectedvalue;
List<string> createdckbxs = new List<string>();
List<string> CheckedCheckboxes = new List<string>();
CheckBox ckbx;
int ckbxID = 0;
//END DECLARATIONS


protected void Page_Load(object sender, EventArgs e)
{

    Response.Write(DateTime.Now); //local time -- testing
    Response.Write("<br /><br />NOTE: the id feild in the below table will be useless soon, it is only for testing purposes, look at CRM<br /><br />");
    selectedvalue = Request.QueryString["filter"];
    //88888888888888888
    RecreatePreviousState();
    //88888888888888888
    Response.Write(selectedvalue);
    instructionsfunc();
}


protected void instructionsfunc()
{
    switch (selectedvalue)
    {
        case "Name":
            instructions.Text = "Please enter the first few letters of the company you are looking for, ex. for "some company", you might search som";
            break;
        case "State":
            instructions.Text = "Please enter the abreviation of the state you are looking for, ex. for New York, enter NY";
            break;
    }

}


protected string sqlSelector(string uinput)
{
    switch (selectedvalue) //create the sql statments
    {
        case "Name":          
            return "SELECT [id],[name] FROM [asd].[jkl] WHERE [name] LIKE '" + uinput + "%' and [deleted] = 0 ORDER BY [name] ASC";  
        case "State":
            return "SELECT [id],[name] FROM [asd].[jkl] WHERE [shipping_address_state] LIKE '" + uinput + "%' and [deleted] = 0 ORDER BY [name] ASC";
        default:
            Response.Redirect("errorpage.aspx?id=002");
            return null; 
    }

}



//on Submit button click, execute the following function NOTE THIS BUTTON's ONLY USE IS POSTBACK
protected void Submit_Click(object sender, EventArgs e)
{
    string Userinput; //declare Userinput variable
    Userinput = Searchbox.Value; // Set variable to asp controll        
    Response.Write("<br /> <br />"+ Userinput +" <- user imput works");
}

//on Clear button click execute the following function
protected void Clear_Click(object sender, EventArgs e)
{
    Response.Redirect(Request.RawUrl);
}



protected void ConnectToSql(string input)
{
    System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
    //Todo add any aditional data needed to connection
    conn.ConnectionString = ConfigurationManager.ConnectionStrings["SplendidTestConnectionString"].ConnectionString;
    try
    {
        conn.Open();

        //this is the actual sql, this gets the data
        SqlCommand sqlString2 = new SqlCommand();
        sqlString2.CommandText = sqlSelector(input);
        sqlString2.CommandTimeout = 15;
        sqlString2.CommandType = System.Data.CommandType.Text;
        sqlString2.Connection = conn;
        SqlDataReader reader;
        reader = sqlString2.ExecuteReader();

        table_builder(reader);


        reader.Close(); //close the sql data reader



    }
    catch (Exception e)
    {
        //Some sort of redirect should go here to prevent the user from vewing a broken page
        conn.Close();
        //Response.Redirect("errorpage.aspx?id=001");
        Response.Write(e);
    }
    finally
    {
        if (conn.State != System.Data.ConnectionState.Closed)
        {
            conn.Close();//close up the connection after all data is done being populated
        }
    }

}

protected void  table_builder(SqlDataReader readerinfo)
{
    //Create a new step for the user
    step3label.Text = "3.";
    //Table header
    TableHeaderRow hr = new TableHeaderRow();
    TableHeaderCell hc = new TableHeaderCell();
    TableHeaderCell hc2 = new TableHeaderCell();
    TableHeaderCell hc3 = new TableHeaderCell();
    hr.Cells.Add(hc);
    hc.Text = "ID"; //Assign header 1 with a name
    hr.Cells.Add(hc2);
    hc2.Text = "Name";//Assign header 2 with a name
    hr.Cells.Add(hc3);
    hc3.Text = "Selection";
    Table1.Rows.Add(hr);


    //Dynamic Table Generation
    int numcells = 3;
    int triswitch = 0;//this is use to chose which cell is made, id, name or selection


    while (readerinfo.Read())   //execute the following aslong as there is data to fill the table with
    {
        for (int j = 0; j < 1; j++)
        {
            TableRow r = new TableRow();
            for (int i = 0; i < numcells; i++)
            {
                TableCell c = new TableCell();

                switch (triswitch)
                {
                    case 0: // this case sets the info for the feild id
                        c.Text = readerinfo.GetSqlGuid(0).ToString();
                        //RENAME THIS To ADDING BUTTON = readerinfo.GetSqlGuid(0).ToString();
                        r.Cells.Add(c);
                        triswitch = 1;
                        break;

                    case 1:
                        c.Text = readerinfo.GetString(1);
                        r.Cells.Add(c);
                        triswitch = 2;
                        break;

                    case 2:
                        ckbx = new CheckBox();
                        ckbx.ID = "CBX" + ckbxID;
                        createdckbxs.Add(ckbx.ID);
                        c.Controls.Add(ckbx);                           
                        r.Cells.Add(c);
                        triswitch = 0;
                        ckbxID++;
                        break;

                }
            }
            Table1.Rows.Add(r);
        }
    }
}



//
//AFTER DATATABLE IS LOADED
//   

protected void RecreatePreviousState()
{
    if (this.IsPostBack)
    {
        ConnectToSql(Searchbox.Value);
        MergeBtnCreate();
    }       
}

protected void MergeBtnCreate()
{
    Button MergeBTN = new Button();
    MergeBTN.Text = "Merge";
    MergeBTN.Click += new EventHandler(MergeBTN_Click);
    MergeBTNHolder.Controls.Add(MergeBTN);
}

void MergeBTN_Click(object sender, EventArgs e)
{
    foreach(string id in createdckbxs)
    {
        CheckBox myControl1 = (CheckBox)Table1.FindControl(id);
        if (myControl1 != null)
        {
            if (myControl1.Checked == true)
            {
                CheckedCheckboxes.Add(id);
            }
        }
        else
        {
            Response.Redirect("errorpage.aspx?id=003");
        }
    }

}

}


Asp.net Asp.net

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

<!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>Hello</title>
</head>
<body>
<form id="form1" runat="server">
        <div style="background-color:#55aaff;margin-bottom:10px;padding:5px;">
        <h3 style="padding:2px;margin:0px;">
            2.
        </h3>
        <asp:Label ID="instructions" runat="server" />
        <asp:Label ID="buttonclicked" runat="server" />
        <br />       
        <input id="Searchbox" type="text" runat="server" />
        <br />
        <asp:Button ID="SubmitBTN" runat="server" OnClick="Submit_Click" Text="Submit" />
        <asp:Button ID="ClearBTN" runat="server" OnClick="Clear_Click" Text="Clear" />
    </div>
    <div>
        <h3 style="padding:2px;margin:0px;">
            <asp:Label ID="step3label" runat="server" Text=""></asp:Label>
        </h3>
        <asp:Table ID="Table1" runat="server" GridLines="Both" />
    </div>
    <div>
        <asp:PlaceHolder ID="MergeBTNHolder" runat="server"></asp:PlaceHolder>
    </div>


</form>

</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM