将一个表复制到另一个表

时间:2015-01-15 21:26:59

标签: c# asp.net gridview

我有两个网格视图,一个连接到一个表,另一个连接到同一个数据库中的其他表

表1 表2

gridview1 gridview2

当使用gridview选择工具选择gridview1中的记录时,然后通过单击按钮,它将记录移动到table2,现在显示在gridview 2上 我试过了

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow r = GridView1.SelectedRow;
    string strQuery = "insert into table values('" + r.Cells[0] + "','" + r.Cells[1] + "')";
}

但我需要它连接到button1,我尝试了其他人

protected void btnSend_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("MenuName");
    dt.Columns.Add("MenuID");

    foreach (GridViewRow grdRow in gridview1.Rows) ////////////// Add new Data from GridMenuList TO Datatable DT
        {
            if (((CheckBox)grdRow.FindControl("chkSelect")).Checked)
            {
                DataRow drow = dt.NewRow();

                Label lblMenuName = (Label)grdRow.FindControl("lblMenuName");

                HiddenField hdnID = (HiddenField)grdRow.FindControl("hdnID");

                drow["MenuName"] = lblMenuName.Text;               
                drow["MenuID"] = hdnID.Value;

                dt.Rows.Add(drow);
            }
        }
    if (dt.Rows.Count > 0)
    {
        gridview2.DataSource = dt;
        gridview2.DataBind();
    }
}

protected void gridview2_RowDataBound(object sender, GridViewRowEventArgs e)
{

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView dr = (DataRowView)e.Row.DataItem;

        //e.Row.Cells[0].Text = dr["MenuName"].ToString();
        Label lblMenuName = e.Row.FindControl("lblMenuName") as Label;
        lblMenuName.Text = dr["MenuName"].ToString();

        HiddenField hdnID = e.Row.FindControl("hdnID") as HiddenField;
        hdnID.Value = dr["MenuID"].ToString();
     }
}

似乎无法让它发挥作用

在我试用了user3607430的建议之后

protected void buttonMove_Click(object sender, EventArgs e)
{
    GridViewRow row = GridView1.SelectedRow;
    SqlCommand move = new SqlCommand("Command String", cn);
    cn.Open();
    move.CommandText = "INSERT into queue values  ('" + row.Cells[1].Text + "')";
    cn.Close();
}

但不起作用

2 个答案:

答案 0 :(得分:0)

首先你应该使用

GridViewRow row = gridview1.SelectedRow;

而不是运行循环来查找所选行。这将为您提供要添加的行。您的网格已连接到表,因此您尝试将其与DataTable变量绑定,这意味着它将与数据库中的表断开连接。因此,一旦选择了行,您应该获取数据,将其添加到表2中,然后在gridview2上调用刷新

希望有所帮助

答案 1 :(得分:0)

DataGridView dataGridView2 = new DataGridView();
foreach(DataGridViewRow row in dataGridView1.Rows)
{
    DataGridViewRow newRow = (DataGridViewRow)row.Clone();
    for (int i = 0; i < row.Cells.Count; i++)
    {
        newRow.Cells[i].Value = row.Cells[i].Value;
    }
    dataGridView2.Rows.Add(newRow);
}