Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

c# - Gridview get Checkbox.Checked value

I have a GridView that has 10 columns populated by CheckBoxes. But instead of using FindControl() is there a way to get the CheckBox.Checked value by using a loop?

Current Code:

if (e.CommandName == "updaterow")
{
     int index = Convert.ToInt32(e.CommandArgument);
     GridViewRow selectedRow = GridView1.Rows[index];
     // TableCell BranchCode = selectedRow.Cells[0];
     CheckBox cb101 = (CheckBox)selectedRow.FindControl("cb101");
     CheckBox cb102 = (CheckBox)selectedRow.FindControl("cb102");
     //...and so on
}  

ASPX CODE:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
    <Columns>
        <asp:TemplateField HeaderText="101">
            <ItemTemplate>
                <asp:CheckBox runat="server" id="cb101" AutoPostBack="false" Checked='<%# Eval("101").ToString()=="1" ? true : false %>' Enabled='<%#(String.IsNullOrEmpty(Eval("101").ToString()) ? false: true) %>'/>
            </ItemTemplate>
        </asp:TemplateField>
        ....and so on
        <asp:ButtonField ButtonType="Button" CommandName="updaterow" Text="Update"/>
    </Columns>
</asp:GridView>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this,

Using foreach Loop:

foreach (GridViewRow row in GridView1.Rows)
{
     CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
     if (chk != null && chk.Checked)
     {
       // ...
     }
}

Use it in OnRowCommand event and get checked CheckBox value.

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...