.NET checkbox.Checked总是返回false

时间:2012-11-28 14:29:33

标签: c# .net checkbox checked

我是.NET的新手,我的复选框有问题。即使选中它们,它们都会返回错误。这是我的asp代码

   <asp:GridView ID="gvGeneros1" runat="server" class="divTable" 
        AutoGenerateColumns="False" DataKeyNames="idgenero" CssClass="table">
        <Columns>
            <asp:BoundField DataField="nome" HeaderText="Gênero" SortExpression="nome" >
            <ControlStyle Width="200px" />
            <ItemStyle Width="200px" />
            </asp:BoundField>
            <asp:TemplateField AccessibleHeaderText="Check">
                <ItemTemplate>
                    <asp:CheckBox ID="checkGenero" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

这是我的c#代码

DataSet dsDivided;

protected void Page_Load(object sender, EventArgs e)
{
    Music musicbll = new Music();
    DataSet dsGeneros = musicbll.getGenders();

    int size = dsGeneros.Tables[0].Rows.Count;
     dsDivided = null;

        // Divide in two DataTable
        dsDivided = Tools.SplitDataTableInTwo((DataTable)dsGeneros.Tables[0], size / 2);

    gvGeneros1.DataSource = dsDivided.Tables["FirstSet"];
    gvGeneros1.DataBind();

    for (int i = 0; i < gvGeneros1.Rows.Count; i++)
    {
        ((CheckBox)gvGeneros1.Rows[i].Cells[1].Controls[1]).Checked=false;
    }

}


protected void btGravarPrefs_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable("generos");
    dt.Columns.Add("idgenero", typeof(int));
    dt.Columns.Add("active", typeof(bool));

    for (int i = 0; i < gvGeneros1.Rows.Count; i++)
    {
        int idCliente = (int)dsDivided.Tables[0].Rows[i][0];
         bool check = ((CheckBox)gvGeneros1.Rows[i].Cells[1].Controls[1]).Checked; //always false
        dt.Rows.Add(new object[] { idCliente, check});
    }
}

}

我不知道该怎么做,我全身都搜索,看起来是正确的。感谢

1 个答案:

答案 0 :(得分:12)

我认为你应该用Data binding

包裹你的if (!Page.IsPostBack)
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    { 
       //Bind your datasource here
    }
}