2009/3/20 記
GridView のコピー
GridView1 の各行に CheckBox を追加。それにチェックを入れた結果をボタンクリックで GridView2 に表示します。
コードは以下のとおりです。
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected DataTable CreateDataTable1()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("Item", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(String)));
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr["Item"] = i;
dr["Name"] = "名前-" + i.ToString();
dt.Rows.Add(dr);
}
return dt;
}
void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = CreateDataTable1();
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView2.DataSource = CreateDataTable();
GridView2.DataBind();
}
protected DataTable CreateDataTable()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("Item", typeof(String)));
dt.Columns.Add(new DataColumn("Name", typeof(String)));
dt.Columns.Add(new DataColumn("Check", typeof(String)));
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Item"] = row.Cells[0].Text;
dr["Name"] = row.Cells[1].Text;
foreach (Control control in row.Cells[2].Controls)
{
if (control is CheckBox)
{
if (((CheckBox)control).Checked)
{
dr["Check"] = "チェック";
}
else
{
dr["Check"] = String.Empty;
}
}
}
dt.Rows.Add(dr);
}
}
return dt;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Check">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Copy" onclick="Button1_Click" />
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>