选中后CheckBox在GridView上丢失状态

时间:2013-12-11 14:24:08

标签: c# asp.net gridview checkbox

我遇到GridView CheckBoxes的问题。     我添加了选择我的GridView和每次我选择一行,在PostBack后我的Checked CheckBoxes丢失了他们的价值。任何建议?

添加了页面加载。

My GirdView:
----------------
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="RulesGridView" runat="server" CellPadding="8" DataSourceID="RulesDataSource" ForeColor="#333333" GridLines="None" OnRowCreated="RulesGridView_RowCreated" OnSelectedIndexChanged="RulesGridView_SelectedIndexChanged" ViewStateMode="Enabled">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="false" OnCheckedChanged="chkSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>

C# Code behind:
-------------------
  protected void RulesGridView_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] =           "this.style.cursor='pointer';this.style.textDecoration='underline';";
                e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
                e.Row.ToolTip = "Click to select row";
                e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.RulesGridView, "Select$" + e.Row.RowIndex);
            }
        }
protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            Session["RuleList"] = new List<Rule>();
            Session.Timeout = 180;
            //LstRules.Items.Clear();
            string folder = ConfigurationManager.AppSettings["MovieCreatorGUIRulesFolder"];
            XmlSerializer mySerializer = new XmlSerializer(typeof(List<Rule>));
            StreamReader reader = new StreamReader(folder + "\\DB" + txtdbnum.Text + "Rules.xml");
            List<Rule> RuleList = (List<Rule>)mySerializer.Deserialize(reader);
            reader.Close();
            Session["RuleList"] = RuleList;
        }
        ZoomInCommon.Users.UserInfo userInfo = PublishManager.GetCurrentYoutubeUser(-1);
        if (userInfo == null)
            txtYoutubeLoginUser.Text = "Not Logged In";
        else
            txtYoutubeLoginUser.Text = userInfo.DisplayName;
    }

3 个答案:

答案 0 :(得分:0)

尝试包装初始化文本框的代码。听起来我觉得它只是在你回发时重新初始化控件。

if (!Page.IsPostBack)
{
    //code that loads or builds your checkboxes
}

答案 1 :(得分:0)

尝试启用PostBack:

   <asp:CheckBox ID="chkSelect" 
                  runat="server"  AutoPostBack="true" 
                  OnCheckedChanged="chkSelect_CheckedChanged" />

答案 2 :(得分:0)

如果你是在每个请求上绑定gridview的数据,那么你需要在某处保存复选框的状态并在数据绑定后立即重新恢复它们之前的状态

更新

请参阅下面的简约示例

HTML

<asp:Label ID="lblOutput" runat="server"></asp:Label>

<br /><br />

<asp:Button ID="btn" runat="server" Text="PostBack" OnClick="btn_Click" />

<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" DataKeyNames="FirstName">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField HeaderText="">
            <ItemTemplate>
                <asp:HiddenField ID="dataKey" runat="server" Value='<%# Eval("FirstName") %>' />
            <asp:CheckBox ID="chkSelect" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="FirstName" HeaderText="First name" />
        <asp:BoundField DataField="LastName" HeaderText="Last name" />
        <asp:BoundField DataField="Age" HeaderText="Age" />
        </Columns>
</asp:GridView>

页面代码隐藏

    IList<Person> _allPersons;

    protected void Page_Init(object sender, EventArgs e)
    {
        _allPersons = Helper.GetPersons();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gv.DataSource = _allPersons;
            gv.DataBind();
        }
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        var selectedPersons = GetSelectedPersons();
        lblOutput.Text = string.Join(",", selectedPersons.Select(x => string.Format("{0} {1}", x.FirstName, x.LastName)));
    }

    private IList<Person> GetSelectedPersons()
    {
        var persons = new List<Person>();

        foreach (GridViewRow row in gv.Rows)
        {
            var chkSelect = row.FindControl("chkSelect") as CheckBox;
            var dataKey = row.FindControl("dataKey") as HiddenField;

            if (chkSelect != null && dataKey != null && chkSelect.Checked)
            {
                var person = _allPersons.FirstOrDefault(x => x.FirstName == dataKey.Value);

                if (person != null)
                    persons.Add(person);
            }
        }

        return persons;
    }

最后,如果你好奇,那么Person和数据Helper的实现细节

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

public class Helper
{
    public static IList<Person> GetPersons()
    {
        return new List<Person>()
        {
            new Person(){FirstName = "Kanye", LastName ="West", Age = 33},
            new Person(){FirstName = "Justin", LastName ="Timberlake", Age = 18},
            new Person(){FirstName = "Celine", LastName ="Dion", Age = 38},
            new Person(){FirstName = "Samantha", LastName ="Jade", Age = 33},
            new Person(){FirstName = "Marshal", LastName ="Matters", Age = 35},
            new Person(){FirstName = "Armando", LastName ="Perez", Age = 14}
        };
    }
}

希望它有意义

利奥