我有一个 gridview
从数据库中提取一列“Product”。
因此,我需要一个复选框
,以便用户在完成时“检查”gridview
中的每个产品。
我研究过 CheckBox Field VS (Template Field + CheckBox) 并决定将 (Template Field + CheckBox) 用于 gridview
按住复选框
。
GridView 列[0] = 产品名称 GridView 列 [1] = 复选框
“选中”一些复选框
后,用户点击提交将触发下面的事件。
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
所以我的问题是,尽管 gridview
中的每一行都使用相同的 复选框
。
最佳答案
复选框字段:
必须绑定(bind)到数据库的字段并且是只读的。
模板字段中的复选框: 可以用作 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>");
}
}
}
}
关于C# Gridview 复选框字段 VS(模板字段+复选框),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20627653/