简体   繁体   中英

How can i transfer one gridview row to another gridview row in asp.net

I have two grid views :

  1. gvdetails and
  2. gvTranferRows

gvdetails are bind from selected database. The fields are :

  • id ,

  • moduleName and

  • Item fields.

In gvTransferRows fields are :

  • id ,

  • ModuleName ,

  • Item and

  • BatchNo .

BatchNo is selected from dropdownlist .

But I want to transfer selected rows from gvdetails to gvTranferRows .

In this process I successfully remove and add gvdetails selected rows to gvTranferRows by clicking remove button at same time and vice versa.

But after clicking the remove button it done and again same operation to second time clicking the add button the gvdetails gridview will completely remove it transfer to gvTransferRows .

What I need is to select second time in add button, it will not remove only selected values remove and transfer to second gridview.

This is the code I tried for code :

.aspx:

  <table align="center">
                <tr>
                    <td class="auto-style2"></td>
                    <td class="auto-style1">
                        <asp:DropDownList ID="ddlbatchno" runat="server" Height="16px" Width="131px">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style2"></td>
                </tr>
                <tr>
                    <td class="auto-style2" valign="top">
                        <asp:GridView ID="gvDetails" runat="server" DataKeyNames="ModuleName" AutoGenerateColumns="false" CellPadding="5">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField DataField="id" HeaderText="id" />
                                <asp:BoundField DataField="ModuleName" HeaderText="ModuleName" />
                                <asp:BoundField DataField="Item" HeaderText="Item" />
                                  <asp:BoundField DataField="BatchNo" HeaderText="BatchNo" />

                            </Columns>
                            <HeaderStyle BackColor="#6699ff" Font-Bold="true" ForeColor="White" />
                        </asp:GridView>
                    </td>
                    <td class="auto-style1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="ADD" />
                        <br />
                        <label>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &gt;&gt;<br />
                        <br />
                        </label>
                        <br />
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <asp:Button ID="btnRemove" runat="server" OnClick="btnRemove_Click"  Text="Remove" />
                        <br />
                        <label>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;&lt;</label> </td>
                    <td valign="top">
                        <asp:GridView ID="gvTranferRows" runat="server" DataKeyNames="ModuleName" AutoGenerateColumns="false" CellPadding="5" EmptyDataText="No Records Found">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkSelect2" runat="server" AutoPostBack="true" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                 <asp:BoundField DataField="id" HeaderText="id" />
                                <asp:BoundField DataField="ModuleName" HeaderText="ModuleName" />
                                <asp:BoundField DataField="Item" HeaderText="Item" />
                                <asp:BoundField DataField="BatchNo" HeaderText="BatchNo" />
                            </Columns>
                            <HeaderStyle BackColor="#6699ff" Font-Bold="true" ForeColor="White" />
                        </asp:GridView>
                        <br />

                    </td>
                </tr>
            </table>  

.cs page:

      protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    ddlbatch();
                    BindGridview();
                    BindSecondGrid();
                }
            }
public void ddlbatch()
        {
            SqlCommand cmd1 = new SqlCommand("Select BatchNo from Batches", con);
            cmd1.CommandType = CommandType.Text;
            cmd1.Connection = con;
            con.Open();

            ddlbatchno.DataSource = cmd1.ExecuteReader();
            ddlbatchno.DataTextField = "BatchNo";
            ddlbatchno.DataBind();
            con.Close();
            ddlbatchno.Items.Insert(0, new ListItem("--Select batche no--", "0"));
        }

        protected void BindGridview() //Binding gvDetaails gridview
        {

            SqlDataAdapter da = new SqlDataAdapter("select id,ModuleName,Item,BatchNo from ModuleItems", con);
            DataTable dt = new DataTable();

            da.Fill(dt);
            ViewState["dt"] = dt;
            ViewState["dt1"] = dt;
            gvDetails.DataSource = dt;
            gvDetails.DataBind();
        }



        protected void BindSecondGrid() // binding gvtransfer gridview
        {
            DataTable dt = (DataTable)ViewState["GetRecords"];
            gvTranferRows.DataSource = dt;
            gvTranferRows.DataBind();

        }

        string name; 
   protected void btnAdd_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gvDetails.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chkRow = (row.Cells[0].FindControl("chkSelect") as CheckBox);
                    if (chkRow.Checked)
                    {

                        int totalCount = gvDetails.Rows.Cast<GridViewRow>().Count(r => ((CheckBox)r.FindControl("chkSelect")).Checked);

                        name += row.Cells[1].Text + ",";

                    }
                }
            }
            string[] name3 = name.Split(',');

            for (int l = 0; l < name3.Length; l++)
            {

                string str = "UPDATE ModuleItems SET BatchNo = " + ddlbatchno.SelectedItem.ToString() + " WHERE id= '" + name3[l] + "'";

                SqlCommand cmd = new SqlCommand(str, con);
                con.Open();

                int j = cmd.ExecuteNonQuery();
                con.Close();
            }
            foreach (GridViewRow oItemLeft in gvDetails.Rows)
            {
                if (((CheckBox)oItemLeft.FindControl("chkSelect")).Checked)
                {
                    GetSelectedRows();
                    BindSecondGrid();
                    break;
                }

            }

            DataTable dt = ViewState["dt"] as DataTable; //2nd time adding gvdetails to gvtransfer dt will become null

            if (dt != null)
            {
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {

                    DataRow row = dt.Rows[i];
                    string dtname = row["id", DataRowVersion.Original].ToString();
                    string[] name1 = name.Split(',');
                    for (int l = 0; l < name1.Length; l++)
                    {
                        string name2 = name1[l].ToString();
                        if (dtname == name2)
                        {
                            row.Delete();

                        }
                    }

                }
            }


            ViewState["dt"] = dt;

            gvDetails.DataSource = dt;
            gvDetails.DataBind();
        }   
        private void GetSelectedRows()
        {
            DataTable dt;
            if (ViewState["GetRecords"] != null)
                dt = (DataTable)ViewState["GetRecords"];
            else
                dt = CreateTable();
            for (int i = 0; i < gvDetails.Rows.Count; i++)
            {
                CheckBox chk = (CheckBox)gvDetails.Rows[i].Cells[0].FindControl("chkSelect");
                if (chk.Checked)
                {
                    dt = AddGridRow(gvDetails.Rows[i], dt);
                }

            }
            ViewState["GetRecords"] = dt;
        }
        private DataTable CreateTable()
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("ModuleName");
            dt.Columns.Add("Item");
            dt.Columns.Add("BatchNo");

            dt.AcceptChanges();
            return dt;
        }

        private DataTable AddGridRow(GridViewRow gvRow, DataTable dt)
        {
            DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
            if (dr.Length <= 0)
            {
                dt.Rows.Add();
                int rowscount = dt.Rows.Count - 1;
                dt.Rows[rowscount]["id"] = gvRow.Cells[1].Text;
                dt.Rows[rowscount]["ModuleName"] = gvRow.Cells[2].Text;
                dt.Rows[rowscount]["Item"] = gvRow.Cells[3].Text;
                dt.Rows[rowscount]["BatchNo"] = ddlbatchno.SelectedItem.Text;
                dt.AcceptChanges();


            }
            return dt;
        }

        protected void btnRemove_Click(object sender, EventArgs e)
        {

            if (gvTranferRows.Rows.Count > 0)
            {
                foreach (GridViewRow row in gvTranferRows.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        CheckBox chkRow1 = (row.Cells[0].FindControl("chkSelect2") as CheckBox);
                        if (chkRow1.Checked)
                        {

                            int totalCount = gvTranferRows.Rows.Cast<GridViewRow>().Count(r => ((CheckBox)r.FindControl("chkSelect2")).Checked);

                            name += row.Cells[1].Text + ",";
                        }
                    }
                }
                string[] name3 = name.Split(',');
                foreach (GridViewRow oItemLeft in gvTranferRows.Rows)
                {
                    if (((CheckBox)oItemLeft.FindControl("chkSelect2")).Checked)
                    {
                        GetRemoveRows();

                        BindGridview();
                        //break;
                    }

                }
                DataTable dt = ViewState["dt"] as DataTable;
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {

                    DataRow row = dt.Rows[i];
                    string dtname = row["id", DataRowVersion.Original].ToString();
                    string[] name1 = name.Split(',');
                    for (int l = 0; l < name1.Length; l++)
                    {
                        string name2 = name1[l].ToString();
                        if (dtname != name2)
                        {
                            row.Delete();

                        }
                    }

                }


                ViewState["dt"] = dt;

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

            }
        }


        DataTable dt,dt1;

        private void GetRemoveRows()
        {


            if (ViewState["GetRecords"] != null)
                dt = (DataTable)ViewState["GetRecords"];

               ViewState["GetRecords"] = dt;
                ViewState["GetRecords2"] = dt;
                gvDetails.DataSource = dt;
                gvDetails.DataBind();
            this. ViewState.Remove("GetRecords2"); //for  viewstate control

            ViewState["GetRecords2"] = null;//for variables 


        }

I am attaching my result image how the result will process. I posted full of my code can anyone please help me out.

img

use a temporary DataTable to maintain the list selected rows or records and then use the DataTable to bind the secondary GridView.

U will get more idea from here Transfer Selected Rows from one GridView to Another in Asp.net

Another way to transfer data

Please try DataTable.ImportRow method:

DataTable.ImportRow() on MSDN

I'm using this method on many WebForms and MVC pages and it works great.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM