I got a gridview
that pulls out a column of "Product" from the database.
With that, I would need a checkbox
for the user to "checked" against each product in the gridview
when it's finished.
I have research about CheckBox Field VS (Template Field + CheckBox) and decided to use (Template Field + CheckBox) for the gridview
to hold the checkbox
.
GridView Column[0] = Product Name GridView Column [1] = Checkbox
After "checking" some checkboxes
, then the user click submit which would trigger the event below.
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
}
}
For usual checkbox
, what I normally do is below
if(checkbox1.checked == true )
else if(checkbox2.checked == true )
else if(checkbox3.checked == true )
etc
So the my question is how do I check if the checkbox
in each row has been "checked" or not despite every row in the gridview
uses the same checkbox
.
CheckBox Field:
must bound to a field of database and is read only.
CheckBox in Template Field: Can use as a rocord selector.
Sample with template field:
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" />
Code behind:
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>");
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With