Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 366, trackbacks - 0

My Links

News

Archives

Image Galleries

Move Multiple Rows Between GridViews

This example shows how to move multiple rows between GridViews. The main idea here is to use a CheckBox control for selecting the rows to be removed from one GridView to another and vise versa.

 

Take a look at sample screen shots below:

 

On initial load:



 Selecting rows from the left GridView:


 

After Moving the selected rows to the right GridView:

As you notice the selected rows are automatically sorted by its ID upon moving.

Selecting rows from the Right GridView:

After Moving the selected rows to the Left GridView:



Here are the code blocks below for the implementation:


ASPX SOURCE:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    </div>

    <table>

        <tr>

            <td valign="top">

                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

                <Columns>

                    <asp:TemplateField>

                        <ItemTemplate>

                            <asp:CheckBox ID="CheckBox1" runat="server" />

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:BoundField DataField="EmployeeID" HeaderText="ID" />

                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />

                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />

                </Columns>

                </asp:GridView>

            </td>

            <td>

                <asp:Button ID="Button1" runat="server" Text=">>>" onclick="Button1_Click" />

                <br />

                <asp:Button ID="Button2" runat="server" Text="<<<" onclick="Button2_Click" />

            </td>

            <td valign="top">

               <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">

                <Columns>

                    <asp:TemplateField>

                        <ItemTemplate>

                            <asp:CheckBox ID="CheckBox1" runat="server" />

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:BoundField DataField="EmployeeID" HeaderText="ID" />

                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />

                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />

                </Columns>

              </asp:GridView>

            </td>

        </tr>

    </table>

    </form>

</body>

</html>

 

 

RELEVANT CODES:

 

public partial class AddMultipleRowsGridView : System.Web.UI.Page

{

    private DataTable _clonedTable;

 

    private string GetConnectionString()

    {

        return @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Northwind.mdf;Integrated Security=True;User Instance=True";

    }

 

    private DataTable QueryData()

    {

        DataTable dt = new DataTable();

        SqlConnection connection = new SqlConnection(GetConnectionString());

        try

        {

            connection.Open();

            string sqlStatement = "SELECT TOP(10)EmployeeID, LastName, FirstName FROM Employees";

            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);

            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            string msg = "Fetch Error:";

            msg += ex.Message;

            throw new Exception(msg);

        }

        finally

        {

            connection.Close();

        }

 

        return dt;

    }

 

    private void BindGrid(DataTable dt, GridView gv)

    {

        if (dt.Rows.Count > 0)

        {

            dt = TrimEmptyRow(dt);

            gv.DataSource = SortData(dt);

            gv.DataBind();

        }

        else

        {

            ShowNoResultFound(dt, gv);

        }

        if (gv.ID == "GridView1")

            ViewState["OrigData"] = dt;

        else

        {

            ViewState["MovedData"] = dt;

        }

    }

    private DataTable SortData(DataTable dt)

    {

        DataView dv = dt.DefaultView;

        dv.Sort = "EmployeeID ASC";

        dt = dv.ToTable();

 

        return dt;

    }

       

    private void MoveRows(DataTable dt, GridView gv)

    {

            for (int i = gv.Rows.Count - 1; i >= 0; i--)

            {

                CheckBox cb = (CheckBox)gv.Rows[i].Cells[0].FindControl("CheckBox1");

                if (cb != null)

                {

                    if (cb.Checked)

                    {

                        AddRow(dt.Rows[i], gv);

                        dt.Rows.Remove(dt.Rows[i]);

                    }

                }

            }

            BindGrid(dt, gv);

    }

 

    private void AddRow(DataRow row,GridView gv)

    {

        DataTable dt = null;

        if (ViewState["MovedData"] == null)

        {

            dt = (DataTable)ViewState["ClonedTable"];

            dt.ImportRow(row);

            dt.Rows.Remove(dt.Rows[0]);

            ViewState["MovedData"] = dt;

            BindGrid(dt, GridView2);

        }

        else

        {

            if (gv.ID == "GridView1")

            {

                dt = (DataTable)ViewState["MovedData"];

                dt.ImportRow(row);

                ViewState["MovedData"] = dt;

                BindGrid(dt, GridView2);

            }

            else

            {

                dt = (DataTable)ViewState["OrigData"];

                dt.ImportRow(row);

                ViewState["OrigData"] = dt;

                BindGrid(dt, GridView1);

            }

        }

    }

 

    private DataTable TrimEmptyRow(DataTable dt)

    {

        if (dt.Rows[0][0].ToString() == string.Empty)

        {

            dt.Rows.Remove(dt.Rows[0]);

        }

        return dt;

    }

 

    private void ShowNoResultFound(DataTable source, GridView gv)

    {

 

        source.Rows.Add(source.NewRow()); // create a new blank row to the DataTable

        // Bind the DataTable which contain a blank row to the GridView

        gv.DataSource = source;

        gv.DataBind();

        // Get the total number of columns in the GridView to know what the Column Span should be

        int columnsCount = gv.Columns.Count;

        gv.Rows[0].Cells.Clear();// clear all the cells in the row

        gv.Rows[0].Cells.Add(new TableCell()); //add a new blank cell

        gv.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell

        //You can set the styles here

        gv.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;

        gv.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;

        gv.Rows[0].Cells[0].Font.Bold = true;

        //set No Results found to the new added cell

        gv.Rows[0].Cells[0].Text = "NO ITEMS FOUND!";

 

    }

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            BindGrid(QueryData(), GridView1);

            _clonedTable = QueryData().Clone();

            ViewState["ClonedTable"] = _clonedTable;

 

            ShowNoResultFound(_clonedTable, GridView2);

        }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        DataTable dtOrigData = (DataTable)ViewState["OrigData"];

        MoveRows(SortData(dtOrigData), GridView1);

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        DataTable dtMovedData = (DataTable)ViewState["MovedData"];

        MoveRows(SortData(dtMovedData), GridView2);

    }

}

 


As you can see the code above was very self explanatory and straight forward. Hope you will find this example useful!


Print | posted on Thursday, October 08, 2009 11:19 PM |

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: