如何将已选中的行添加到数据表中

时间:2014-02-12 10:30:50

标签: c# asp.net

我在网格视图(gvrow)的复选框点击事件中编写代码。使用以下代码

但我检查过的行应该单独进入数据表(dt)。如果检查后未检查任何行,则不应该进入数据表。

我在下面显示的代码是添加行但未选中一行

protected void chkCall_CheckedChanged(object sender, EventArgs e)
{
    foreach (GridViewRow gvrow in gvDetails.Rows)
    {
        CheckBox chk = (CheckBox)gvrow.FindControl("chkCall");
        if (chk != null & chk.Checked)
        {

            //dt.Rows.Add();
            DataRow row = dt.NewRow();
            row["shopno"] = gvDetails.Rows[i].Cells[0].Text.ToString();
            row["Lineitem"] = gvDetails.Rows[i].Cells[1].Text;
            row["Suppliername"] = gvDetails.Rows[i].Cells[2].Text;
            row["Dunsnumber"] = gvDetails.Rows[i].Cells[3].Text;
            row["AgingDays"] = gvDetails.Rows[i].Cells[4].Text;
            // row["lastfollowupmail"] = gvDetails.Rows[i].Cells[7].Text;
            dt.Rows.Add(row);
            i++;
        }

    }

    GridView1.DataSource = dt;
    GridView1.DataBind();

}

请帮帮我

2 个答案:

答案 0 :(得分:1)

保持i++外部复选框状态。

protected void chkCall_CheckedChanged(object sender, EventArgs e)
{
    int i=0;
    foreach (GridViewRow gvrow in gvDetails.Rows)
    {
        CheckBox chk = (CheckBox)gvrow.FindControl("chkCall");
        if (chk != null & chk.Checked)
        {

            //dt.Rows.Add();
            DataRow row = dt.NewRow();
            row["shopno"] = gvDetails.Rows[i].Cells[0].Text.ToString();
            row["Lineitem"] = gvDetails.Rows[i].Cells[1].Text;
            row["Suppliername"] = gvDetails.Rows[i].Cells[2].Text;
            row["Dunsnumber"] = gvDetails.Rows[i].Cells[3].Text;
            row["AgingDays"] = gvDetails.Rows[i].Cells[4].Text;
            // row["lastfollowupmail"] = gvDetails.Rows[i].Cells[7].Text;
            dt.Rows.Add(row);

        }
        i++;

    }

    GridView1.DataSource = dt;
    GridView1.DataBind();

}

答案 1 :(得分:0)

您可以尝试使用

代替您的代码

假设您的复选框列名为 ChkBox

  DataTable tbl = ((DataTable)GridView1.DataSource).Clone();//Clone structure first
  var rows = dataGridView1.Rows.OfType<GridViewRow>()
                         .Where(r=>Convert.ToBoolean(r.Cells["ChkBox"].Value))
                         .Select(r=>((DataRowView)r.DataBoundItem).Row);
  foreach(var row in rows)
  tbl.ImportRow(row);