我可以通过单击gridview标题中的复选框来选择一个或所有复选框。如果我取消选中一个复选框,则标题复选框将变为未选中状态。选中用户后,我可以单击“提交”。我遇到的问题是,单击“提交”后,如何将每个所选用户的ID添加到数组中?还有如何在c#中从此数组读取每个数据?
前端代码
<div>
<asp:Button ID="submit" runat="server" Text="Submit" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="checkboxSelectAll" onclick="HeaderCheckBoxClick(this);" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" onclick="ChildCheckBoxClick(this);" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="ID" HeaderText="ID" />
</Columns>
</asp:GridView>
<script type="text/javascript">
function HeaderCheckBoxClick(checkbox) {
var gridView = document.getElementById("GridView1");
for (i = 1; i < gridView.rows.length; i++) {
gridView.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = checkbox.checked;
}
}
function ChildCheckBoxClick(checkbox) {
var gridView = document.getElementById("GridView1");
var atleastOneCheckboxUnchecked = false;
for (i = 1; i < gridView.rows.length; i++) {
if (gridView.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == false) {
atleastOneCheckboxUnchecked = true;
break;
}
}
gridView.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = !atleastOneCheckboxUnchecked;
}
</script>
</div>
C# Code behind
protected void Page_Load(object sender, EventArgs e)
{
List<MyData> list = new List<MyData>();
if (!IsPostBack)
{
list.Add(new MyData() { Name = "Tom", ID = 123 });
list.Add(new MyData() { Name = "Ben", ID = 611 });
list.Add(new MyData() { Name = "Sally", ID = 78 });
GridView1.DataSource = list;
GridView1.DataBind();
}
}
public class MyData
{
public string Name { get; set; }
public int ID { get; set; }
}
protected void submit_Click(object sender, EventArgs e)
{
//Not sure what to add here
}`
}
答案 0 :(得分:0)
您可以在gridview中添加复选框列表- aspx:-
<div>
<asp:CheckBoxList runat="server" ID="chk1">
</asp:CheckBoxList>
<asp:Button runat="server" ID="btn" OnClick="btn_Click"/>
</div>
aspx.cs-
protected void btn_Click(object sender, EventArgs e)
{
List<string> items = new List<string>();
for(int i=0; i < chk1.Items.Count; i++)
{
if (chk1.Items[i].Selected == true)
{
//can do anything here
items.Add(chk1.Items[i].Text);
}
}
}