我想保留一些在数组列表中检查的数据。我在gridview中添加了复选框,当我检查其中一个项目时。复选框的click事件为所有人运行,例如,当我点击任意一个复选框运行4次时,我有两个数据,所以它适用于每一个但是,我希望只添加一个复选框的项目被选中或取消选中列出。有解决方案还是其他解决方案
// checkbox click event
protected void SelectedFriends_Click(object sender, EventArgs e)
{
bool isflag=false;
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("FriendSelector");
if (cb != null && cb.Checked)
{
string friendname = GridView1.Rows[row.RowIndex].Cells[1].Text.ToString();
for (int i = 0; i < list.Count; i++)
{
if (friendname.Equals(list[i].ToString()))
{
isflag = true;
}
}
// if it is added previously don't add to list
if(!isflag)
{
list.Add(friendname);
}
}
else
{
string friendname = GridView1.Rows[row.RowIndex].Cells[1].Text.ToString();
for (int i = 0; i < list.Count; i++)
{
if (friendname.Equals(list[i].ToString()))
{
isflag = true;
}
}
// if it is not checked and it is in list delete it from list
if(isflag)
{
list.Remove(friendname);
}
}
}
}
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1" Font-Bold="True"
Width="157px">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox runat="server" id="FriendSelector"
oncheckedchanged="SelectedFriends_Click" AutoPostBack="True">
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="F_Name" HeaderText="Friend Name"
SortExpression="F_Name" />
</Columns>
</asp:GridView>
答案 0 :(得分:0)
你能试试吗?
protected void SelectedFriends_Click(object sender, EventArgs e)
{
list.Clear();
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("FriendSelector");
if (cb != null && cb.Checked)
{
string friendname = GridView1.Rows[row.RowIndex].Cells[1].Text.ToString();
list.Add(friendname);
}
}
}