如何在gridview中使用复选框
本文关键字:复选框 gridview | 更新日期: 2023-09-27 18:08:15
我有一个asp.net表单显示从Oracle数据库的用户详细信息,使用网格视图。我甚至设法在网格视图中使用以下模板获得一个复选框字段。
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chck"/>
</ItemTemplate>
</asp:TemplateField>
我希望管理员能够使用复选框选择多个条目,并对它们执行一定的操作。对于删除操作,我尝试使用以下
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (Convert.ToBoolean(GridView1.Rows[i].Cells[1].Value == true))
GridView1.Rows.RemoveAt[i];
}
然而,这显示了一个错误。显然,每行上的每个复选框都必须有自己唯一的索引。我怎么去那儿?任何形式的帮助都会很感激。谢谢:)
你需要使用findControl在gridview行中找到控件
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb1 = (CheckBox)GridView1.Rows[i].FindControls("chck");
if(cb1.Checked)
GridView1.Rows.RemoveAt[i];
}
使用查找控件获取复选框:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chck = (CheckBox)GridView1.Rows[i].FindControl("chck");
if (chck != null)
{
if (chck.Checked)
{
GridView1.Rows.RemoveAt[i];
}
}
}
这是Aspx文件:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
</asp:GridView>
这是CS文件:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
string constr = @"Server=.'SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
string query = @"SELECT CategoryID, CategoryName, Approved FROM Categories";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
string cid = row.Cells[1].Text;
bool status = chkStatus.Checked;
string constr = @"Server=.'SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
string query = "UPDATE Categories SET Approved = @Approved WHERE CategoryID = @CategoryID";
SqlConnection con = new SqlConnection(constr);
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("@Approved", SqlDbType.Bit).Value = status;
com.Parameters.Add("@CategoryID", SqlDbType.Int).Value = cid;
con.Open();
com.ExecuteNonQuery();
con.Close();
LoadData();
}