lundi 29 février 2016

asp.net check if checkbox in gridview is checked

Gridview with a select-button, a boundfield and a checkbox. Binding the data to the gridview works fine. (the data in the DB has an NVARCHAR column for the bounfield and a BIT column for the checkbox.

When selecting a row via the 'Select' button, an event in code-behind is fired, and data from the 2 cells from the gridview are copied to 2 controls on the page: a textbox and checkbox.

The first works ok and I have no clue as to how to check if the checkbox in the gridview is checked or not. I need to know that so that I can populate other checkbox control accordingly.

(before I paste my code: I just spent some 12 hours searching for a solution here in SO and elsewhere. None of the numerous entries helped. So please bear with me...)

<asp:GridView ID="grv_Test1" runat="server" CssClass="myGrid"
    AutoGenerateColumns="False" DataKeyNames="Test1_First_Name"
    OnRowCommand="grv_Test1_RowCommand">
    <Columns>
        <asp:CommandField SelectText="sel'" ShowSelectButton="True" ControlStyle-CssClass="btn btn-primary myBtn-xs">
        </asp:CommandField>
        <asp:BoundField DataField="Test1_First_Name" HeaderText="Name"><HeaderStyle Width="85px" />
        </asp:BoundField>
        <asp:CheckBoxField DataField="Test1_Active" HeaderText="Active">
        </asp:CheckBoxField>
    </Columns>
    <HeaderStyle CssClass="myGridHeader" />
</asp:GridView>  

Code behind:

int my_Data_From_Grid = Convert.ToInt32(e.CommandArgument);
txb_Test1_Name.Text = grv_Test1.Rows[my_Data_From_Grid].Cells[1].Text;            // this works

cbx_Test1_Active.Text = grv_Test1.Rows[my_Data_From_Grid].Cells[2].Text;          // NOT working

if (Convert.ToString(grv_Test1.Rows[my_Data_From_Grid].Cells[2].Text) == "1")     // NOT working either
   { cbx_Test1_Active.Checked = true; }
else
   { cbx_Test1_Active.Checked = false; }

if (Convert.ToString(grv_Test1.Rows[my_Data_From_Grid].Cells[2].Text) == "True")  // NOT working either
   { cbx_Test1_Active.Checked = true; }
else
   { cbx_Test1_Active.Checked = false; }

Here is what I got when selecting Michael's row:
enter image description here
In the gridview Michael is "Active", and I need the checkbox at the top to be 'checked'.
How can it be done...? Thnaks a lot.




Aucun commentaire:

Enregistrer un commentaire