用ASP.NET Web语言在gridview1中勾选取多个checkbox的值,点击button按钮,被选中的checkbox的值,被传到Gridview2中跳转到gridview2中。
时间: 2024-02-26 15:59:14 浏览: 93
gridview 分页保存每页的Checkbox选中的值
4星 · 用户满意度95%
可以使用以下代码实现:
在ASP.NET Web页面中,添加两个GridView控件(GridView1和GridView2),并在GridView1中添加CheckBox列和Button控件:
```
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" onclick="CheckAllCheckBoxes(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>
```
在code-behind中,添加以下代码:
```
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (CheckBox)e.Row.FindControl("chkRow");
if (chkRow != null)
{
chkRow.Attributes["onclick"] = string.Format("javascript:CheckCheckBox(this,'{0}');", chkSelectAll.ClientID);
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkRow = (CheckBox)row.FindControl("chkRow");
if (chkRow.Checked)
{
string id = row.Cells[1].Text;
string name = row.Cells[2].Text;
DataTable dt = (DataTable)GridView2.DataSource;
if (dt == null)
{
dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Name", typeof(string));
}
dt.Rows.Add(id, name);
GridView2.DataSource = dt;
GridView2.DataBind();
}
}
}
```
在JavaScript中,添加以下代码:
```
function CheckAllCheckBoxes(chk) {
var gridView = document.getElementById('<%= GridView1.ClientID %>');
var inputs = gridView.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
inputs[i].checked = chk.checked;
}
}
}
function CheckCheckBox(chk, chkAll) {
var gridView = document.getElementById('<%= GridView1.ClientID %>');
var inputs = gridView.getElementsByTagName("input");
var chkAllCtrl = document.getElementById(chkAll);
var isAllChecked = true;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i] != chkAllCtrl) {
if (!inputs[i].checked) {
isAllChecked = false;
}
}
}
chkAllCtrl.checked = isAllChecked;
}
```
这个例子中,我们在GridView1中添加了一个CheckBox列,用于选择需要传递的行。在Button控件的Click事件中,我们遍历GridView1的所有行,如果该行的CheckBox被选中,则将该行的ID和Name添加到DataTable中,并将DataTable绑定到GridView2中。
为了实现全选/取消全选的功能,我们添加了两个JavaScript函数:CheckAllCheckBoxes和CheckCheckBox。其中CheckAllCheckBoxes用于全选/取消全选所有的CheckBox,CheckCheckBox用于检查是否需要选中“全选”CheckBox。
阅读全文