简体   繁体   English

如何在Checkstate中保存ASP复选框状态并在postba后检索值

[英]How to save ASP checkbox state in Checkstate and retrieve value after postba

Am developing an ASP Webform App and having some challenges with checkbox Viewstate and Postback.我正在开发一个 ASP Webform 应用程序,并且在复选框 Viewstate 和 Postback 方面遇到了一些挑战。 My App has 2 Gridviews.我的应用程序有 2 个 Gridviews。 Gridview has about 8 columns and 3 of those columns has 3 TemplateFields with each TemplateField having its own ASP checkbox with a different IDs. Gridview 大约有 8 列,其中 3 列有 3 个 TemplateField,每个 TemplateField 都有自己的 ASP 复选框和不同的 ID。 Gridview displays data from an Active Directory which has already been assigned to a user will be updated, deleted, or unchanged. Gridview 显示来自已分配给用户的 Active Directory 中的数据,这些数据将被更新、删除或不变。 i want to use the checkboxes checked states or values for the updates.我想使用复选框选中状态或值进行更新。

Please see Markup for Gridview A请参阅 Gridview A 的标记

<asp:GridView ID="gv_ZugeteilteEmailverteiler" runat="server" AllowPaging ="true" PageSize="15" CssClass="table table-striped table-bordered" AutoGenerateColumns="false" Width="100%" BorderColor="#DEBA84" BackColor="Silver" HeaderStyle-Height="40px" OnPreRender="gv_ZugeteilteEmailverteiler_PreRender"     
    HorizontalAlign="Center" CellPadding="0">
    <Columns>
    <asp:TemplateField HeaderText="Reihe" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
    <ItemTemplate>
    <%# Container.DataItemIndex + 1 %>   
    </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="gruppenname" HeaderText="Gruppenname" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
    <asp:BoundField DataField="standort" HeaderText="Standort" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
    <asp:BoundField DataField="beschreibung" HeaderText="Beschreibung" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>             
    <asp:BoundField DataField="genehmigt" HeaderText="Genehmigt" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="400px"/>
    <asp:BoundField DataField="zielobjekt" HeaderText="ZielObjekt" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
    <asp:BoundField DataField="ACTION_CHECKED" HeaderText="Action_Checked" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px" />
    <asp:TemplateField HeaderText="Neu-Hinzufügen" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">                                                          
    <ItemTemplate>
    <asp:CheckBox ID="cb_EmailverteilerHinzufuegen" runat="server" AutoPostBack="true" Checked="false" ItemStyle-HorizontalAlign="Center" CssClass="checkboxClass" onclick="CheckBoxCheck(this);" onchange="return javascript:CheckBoxCheck(this);" OnCheckedChanged="cb_EmailverteilerHinzufuegen_CheckedChanged"/>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Entfernen" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" >
    <ItemTemplate>
    <asp:CheckBox ID="cb_EmailverteilerEntfernen" runat="server" AutoPostBack="true" ItemStyle-HorizontalAlign="Center" CssClass="checkboxClass" onclick="CheckBoxCheck(this);" onchange="return javascript:CheckBoxCheck(this);" OnCheckedChanged="cb_EmailverteilerEntfernen_CheckedChanged"/>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Bestätigen" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
    <ItemTemplate>
    <asp:CheckBox ID="cb_EmailverteilerBestaetigen" runat="server" AutoPostBack="true" ItemStyle-HorizontalAlign="Center" class="checkboxClass" onclick="CheckBoxCheck(this);" onchange="return javascript:CheckBoxCheck(this);" OnCheckedChanged="cb_EmailverteilerBestaetigen_CheckedChanged"/>
    </ItemTemplate>
    </asp:TemplateField>                                       
    </Columns>
    <HeaderStyle ForeColor="Black" Font-Bold="True" BackColor="#CCCC00"></HeaderStyle>
    </asp:GridView>

The Gridview B also has about 6 columns and one checkbox in a Template field. Gridview B 在模板字段中也有大约 6 列和一个复选框。 The Data in Gridview B are Directories from the AD that can be added to the user's list of already given directories shown in Gridview A. Hence when the checkbox in Gridview B is clicked, the entire row selected or checked will be added to Gridview A. Gridview B 中的数据是来自 AD 的目录,可以添加到 Gridview A 中显示的用户列表中。因此,当单击 Gridview B 中的复选框时,选中或选中的整行都将添加到 Gridview A。

Please see the Markup for Gridview B请参阅 Gridview B 的标记

<asp:GridView ID="gv_MoeglicheEmailverteiler" runat="server" ClientIDMode="Static"  
AutoGenerateColumns="false" BorderColor="#DEBA84" BackColor="Silver" HeaderStyle-Height="40px" OnPreRender="gv_MoeglicheEmailverteiler_PreRender"   
HorizontalAlign="Center" CellPadding="3" CssClass="tablesorter">
<Columns>                
<asp:TemplateField HeaderText="Reihe" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center">   
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>   
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="gruppenname" HeaderText="Gruppenname" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>                           
<asp:BoundField DataField="standort" HeaderText="Standort" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="beschreibung" HeaderText="Beschreibung" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>             
<asp:BoundField DataField="genehmigt" HeaderText="Genehmigt" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="zielobjekt" HeaderText="ZielObjekt" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="ACTION_CHECKED" HeaderText="Action_Checked" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px" />
<asp:TemplateField ItemStyle-Width="300px"  HeaderText="Action" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="cb_CheckOneMoglicheverteilerRow" runat="server" ItemStyle-HorizontalAlign="Center" class="checkboxClass" AutoPostBack="true" onclick = "Check_Click(this);" OnCheckedChanged="CheckBox_CheckChanged"/>
</ItemTemplate>        
</asp:TemplateField>
</Columns>
<HeaderStyle ForeColor="Black" Font-Bold="True" BackColor="#CCCC00"></HeaderStyle>                       
</asp:GridView>

PROBLEM: Each of the checkboxes in both Gridviews fires events.问题:两个 Gridviews 中的每个复选框都会触发事件。 Example the Checkbox in Gridview B's Event is to add the checked Row to Gridview A. I managed to save the Gridviews ViewState and retrieve them after every Postback or event and Bind them succesfully. Gridview B 事件中的复选框示例是将选中的行添加到 Gridview A。我设法保存了 Gridviews ViewState 并在每个回发或事件后检索它们并成功绑定它们。

My problem is, the checkboxes in Gridview A, i cannot or dont know how i could save their checkedstates in a ViewState and restore them after Postback or after an Event or after page refreshes.我的问题是,Gridview A 中的复选框,我无法或不知道如何将其选中状态保存在 ViewState 中并在回发后或事件后或页面刷新后恢复它们。 They all go unchecked after page refreshes or after a Postback.在页面刷新或回发后,它们都将取消选中。

Here are the methods to add a row from Gridview B to Gridview A and Remove Row from Gridview A以下是从 Gridview B 添加一行到 Gridview A 和从 Gridview A 中删除行的方法

// Create Datatable and save in Viewstate, I was thinking i could add the checkboxes columns to the datatable here as well, but i dont know how to get their values, because the Gridview columns values i get from a database boundfield. // 创建数据表并保存在 Viewstate 中,我想我也可以将复选框列添加到这里的数据表中,但我不知道如何获取它们的值,因为我从数据库绑定字段获取的 Gridview 列值。

    private DataTable CreateDataTable()
    {
      DataTable dt = new DataTable();
      if (ViewState["SelectedRecords"] != null)
      {
         dt = (DataTable)ViewState["SelectedRecords"];
      }
      else
      {
       dt.Columns.Add("gruppenname");
       dt.Columns.Add("standort");
       dt.Columns.Add("beschreibung");
       dt.Columns.Add("genehmigt");
       dt.Columns.Add("zielobjekt");
       dt.Columns.Add("Action_Checked");
       dt.AcceptChanges();
      }
        return dt;
   }

// Method to add Row to from Gridview A to Gridview B //从Gridview A到Gridview B添加Row的方法

private DataTable AddRow(GridViewRow gvRow, DataTable dt)
  {
            DataRow[] dr = dt.Select("gruppenname = '" + gvRow.Cells[1].Text + "'");

            if (dr.Length <= 0)
            {

                dt.Rows.Add();
                dt.Rows[dt.Rows.Count - 1]["gruppenname"] = gvRow.Cells[1].Text;
                dt.Rows[dt.Rows.Count - 1]["standort"] = gvRow.Cells[2].Text;
                dt.Rows[dt.Rows.Count - 1]["beschreibung"] = gvRow.Cells[3].Text;
                dt.Rows[dt.Rows.Count - 1]["genehmigt"] = gvRow.Cells[4].Text;
                dt.Rows[dt.Rows.Count - 1]["zielobjekt"] = gvRow.Cells[5].Text;
                dt.Rows[dt.Rows.Count - 1]["Action_Checked"] = gvRow.Cells[6].Text;
                dt.AcceptChanges();
            }

            return dt;
  }

// Method to remove Row from Gridview A // 从 Gridview A 中删除 Row 的方法

private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
 {
            DataRow[] dr = dt.Select("gruppenname = '" + gvRow.Cells[1].Text + "'");
            if (dr.Length > 0)
            {

                dt.Rows.Remove(dr[0]);
                dt.AcceptChanges();
            }
            return dt;

  }

// Now this is how i call them // Method to Get Data from checked Row in Gridview Moglicheverteiler to add to Gridview Zugeteilte Emailverteiler // 现在这就是我如何称呼它们 // 从 Gridview Moglicheverteiler 中的选中行获取数据以添加到 Gridview Zugeteilte Emailverteiler 的方法

    private void GetData()
        {
            DataTable dt;
            if (ViewState["SelectedRecords"] != null) 
                dt = (DataTable)ViewState["SelectedRecords"];
            else
                dt = CreateDataTable();         

            for (int i = 0; i < gv_MoeglicheEmailverteiler.Rows.Count; i++)
            {
              CheckBox chk = (CheckBox)gv_MoeglicheEmailverteiler.Rows[i].Cells[6].FindControl("cb_CheckOneMoglicheverteilerRow");  string test = gv_MoeglicheEmailverteiler.Rows[i].Cells[1].Text;

if (gv_ZugeteilteEmailverteiler != null && chk.Checked) 
{
for (int j = 0; j < gv_ZugeteilteEmailverteiler.Rows.Count; j++) 
                    {
                        string actionChecked = gv_ZugeteilteEmailverteiler.Rows[j].Cells[6].Text;                     
                        if ((chk.Checked && actionChecked == "Bestaetigen")|| (chk.Checked && actionChecked == "Bestaetigt") || (chk.Checked && actionChecked == "TRUE") || (chk.Checked && actionChecked == "FALSE") || (chk.Checked && actionChecked == "Entfernen"))
                        {
                            dt = AddRow(gv_MoeglicheEmailverteiler.Rows[i], dt);

                            dt = AddRow(gv_ZugeteilteEmailverteiler.Rows[j], dt);
                            
                        }
                        else if (chk.Checked)
                        {
                            dt = AddRow(gv_MoeglicheEmailverteiler.Rows[i], dt);                          
                        }                      
                    }
                }
            }

            ViewState["SelectedRecords"] = dt;               
        }

        
        private void SetData()
        {
         
            if (ViewState["SelectedRecords"] != null)
            {
                DataTable dt = (DataTable)ViewState["SelectedRecords"];
                for (int i = 0; i < gv_MoeglicheEmailverteiler.Rows.Count; i++)
                {
                    CheckBox chk = (CheckBox)gv_MoeglicheEmailverteiler.Rows[i].Cells[6].FindControl("cb_CheckOneMoglicheverteilerRow");
                    if (chk != null)
                    {

                        DataRow[] dr = dt.Select("gruppenname = '" + gv_MoeglicheEmailverteiler.Rows[i].Cells[1].Text + "'");
                        chk.Checked = dr.Length > 0;

                    }
                }
            }         
        }

So in short am trying to figure out how i can save the checkboxes values into the viewstate just as i did with the Gridview Columns.所以简而言之,我试图弄清楚如何将复选框值保存到视图状态中,就像我对 Gridview 列所做的一样。 Any ideas out there will be really appreciated.任何想法都将不胜感激。 Ibeen stocked on the problem for months.几个月来,我一直在解决这个问题。

    // Bind ZugeteiltGridview For GetData Method
    private void BindZugeteilteGridviewForGetDataMethod()
    {
        DataTable dt = (DataTable)ViewState["SelectedRecords"];
        gv_ZugeteilteEmailverteiler.DataSource = dt;
        gv_ZugeteilteEmailverteiler.DataBind();
        //CheckAddedRowFromMoglicheEmailverteiler();
    }

You have AutoPostback=true - this is the problem.您有AutoPostback=true - 这就是问题所在。 Don't do it this way.不要这样做。

Instead, add a button to execute the changes from Grid A to Grid B. You should be able to access the checkbox values then by looping over the GridView rows before they are databound - You might need a hidden field to store the ID of the item on each row.相反,添加一个按钮来执行从网格 A 到网格 B 的更改。您应该能够访问复选框值,然后在数据绑定之前循环遍历 GridView 行 - 您可能需要一个隐藏字段来存储项目的ID在每一行。 You than should - if you need to - fetch the data for that ID from the datastore rather than try and get it from the GridView.您应该 - 如果需要 - 从数据存储中获取该 ID 的数据,而不是尝试从 GridView 获取它。 You can try of course but as they are DataBound controls I believe you need to fetch the text of the cell.您当然可以尝试,但由于它们是 DataBound 控件,我相信您需要获取单元格的文本。

Once that is done than you can rebind the grid(s).完成后,您可以重新绑定网格。

Make sure you don't databind the grid A before you loop over it or all you checkboxes will be gone.确保在循环之前不要对网格 A 进行数据绑定,否则所有复选框都将消失。

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

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