C#Gridview CheckBox字段或(Templatefield + CheckBox)

时间:2013-12-17 06:44:49

标签: c# asp.net gridview checkbox

我有一个gridview从数据库中提取出一列“Product”。

有了这个,我需要一个checkbox让用户在gridview完成后对每个产品进行“检查”。

我对 CheckBox字段VS(模板字段+复选框)进行了研究,并决定使用(模板字段+复选框)来保存gridview checkbox

GridView Column [0] =产品名称 GridView列[1] =复选框

在“检查”某些checkboxes后,用户点击提交将触发下面的事件。

string checkedBy;        
foreach (GridViewRow row in grvCheckList.Rows)
{
   // Im not sure how to check if each checkbox has been "checked" 
   // or not as it is in the gridview  cell.

   // what I like to have is
      if((checkbox in column[1]).checked == true)
      { 
        checkedBy = // Staff name 
        // my codes to store the staff name into database with respective to the product listed in             the gridview row 
       }
      else
      { 
        checkedBy = "NULL"
        // my code to store "NULL" into database with respect to the product listed in the gridview        row
      }
}   

对于通常checkbox,我通常做的是

if(checkbox1.checked == true ) 
else if(checkbox2.checked == true )
else if(checkbox3.checked == true )
etc

所以我的问题是如何检查每行中的checkbox是否已经“检查”,尽管gridview中的每一行都使用相同的checkbox

1 个答案:

答案 0 :(得分:7)

CheckBox字段:
必须绑定到数据库字段并且是只读的。

模板字段中的复选框 可以用作rocord选择器。

带有模板字段的示例:

ASPX:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
            <asp:BoundField DataField="fname" HeaderText="fname" SortExpression="fname" />
            <asp:BoundField DataField="lname" HeaderText="lname" SortExpression="lname" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

代码背后:

 protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow item in GridView1.Rows)
        {
            CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
            if (chk != null)
            {
                if (chk.Checked)
                {
                    // process selected record
                    Response.Write(item.Cells[1].Text + "<br>");
                }
            }
        }
    }