Return Gridview Checkbox boolean

无人久伴 提交于 2020-01-05 07:37:04

问题


I've racked my brains on trying to access the ID column of a gridview where a user selects a checkbox:

<asp:GridView ID="gvUserFiles" runat="server">
            <Columns>
            <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" >
                <ItemTemplate>
                    <asp:CheckBox  ID="chkSelect" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            </Columns>
        </asp:GridView>

The gridview columns are chkSelect (checkbox), Id, fileName, CreateDate

When a user checks a checkbox, and presses a button, i want to receive the "id" column value.

Here is my code for the button:

foreach (GridViewRow row in gvUserFiles.Rows)
            {
                var test1 = row.Cells[0].FindControl("chkSelect");
                CheckBox cb = (CheckBox)(row.Cells[0].FindControl("chkSelect"));
                //chk = (CheckBox)(rowItem.Cells[0].FindControl("chk1"));  
                if (cb != null && cb.Checked)
                {
                    bool test = true;

                }
            }

The cb.checked always is returned false.


回答1:


The Checkboxes being always unchecked can be a problem of DataBinding. Be sure you are not DataBinding the GridView before the button click event is called. Sometimes people stick the DataBinding on the Page_load event and then it keeps DataBinding on every PostBack. As it is called before the button click, it can make direct influence. When the GridView is DataBound you lose all the state that came from the page.

If you Databind the GridView on the Page_load, wrap it verifying !IsPostBack:

if (!IsPostBack)
{
    gvUserFiles.DataSource = data;
    gvUserFiles.DataBind();
}

If that is not your case, you can try verifying the checked property based on the Request.Form values:

protected void button_OnClick(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvUserFiles.Rows)
    {
        CheckBox cb = (CheckBox)row.FindControl("chkSelect");

        if (cb != null)
        {
            bool ckbChecked = Request.Form[cb.UniqueID] == "on";

            if (ckbChecked)
            {
                //do stuff
            }
        }
    }
}

The Checked value of a CheckBox is sent by the browser as the value "on". And if it is not checked in the browser, nothing goes on the request.




回答2:


You can achieve it using datakey like this

Add Datakey to your gridview

<asp:GridView ID="gvUserFiles" runat="server" DataKeyNames="Id">

and get it server side like this

string value = Convert.ToString(this.gvUserFiles.DataKeys[rowIndex]["Id"]);


来源:https://stackoverflow.com/questions/15186546/return-gridview-checkbox-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!