Alp*_*o69 4 c# asp.net checkbox gridview
我gridview从数据库中删除了一列"Product".
有了这个,我需要一个checkbox让用户gridview在它完成时对每个产品进行"检查" .
我对研究复选框字段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
}
}
Run Code Online (Sandbox Code Playgroud)
通常checkbox,我通常做的是下面
if(checkbox1.checked == true )
else if(checkbox2.checked == true )
else if(checkbox3.checked == true )
etc
Run Code Online (Sandbox Code Playgroud)
所以我的问题是如何检查checkbox每行中是否已"检查",尽管gridview使用中的每一行都相同checkbox.
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" />
Run Code Online (Sandbox Code Playgroud)
代码背后:
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>");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)