I want to keep some data which is checkhed in array list. I added checkbox to gridview and when i checked one of items. click event of checkbox runs for all so for example, I have two data when i click the any checkbox it runs 4 times, so it works for each one however, I want that only the item of one checkbox which is checked or unchecked is added to list. Is there solution or another solution
// 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>
Can you try this?