Click here to Skip to main content
15,173,031 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Im trying to transfer rows from gridview in one page to gridview in another page. Im stuck up in middle. I dont have errors but the result is not as expected. pls check my code n help me out with proper code.
i have 9 columns(with same column names) both in gridview1(page 1) and gridview2(page2).
gridview1 has checkbox column so that multiple checkbox can be selected and on clickin a button rows moved to gridview2.

page1: source code
<%@ Page Title="" Language="C#" Debug="true" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ADDSTENT.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">


<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<asp:SqlDataSource ID="Sqlview" runat="server"
ConnectionString="<%$ ConnectionStrings:ProjectConnectionString %>"
SelectCommand="SELECT * FROM [Stent_table1]"
UpdateCommand="UPDATE [Stent_table1] Set [StentCat]=@StentCat, [StentID]=@StentID, [Date]=@Date, [DCNo]=@DCNo, [Company]=@Company, [Name]=@Name, [Size]=@Size, [Expiry]=@Expiry ">


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

Width="1132px" AllowPaging="True" >
<pagerstyle forecolor="Black" horizontalalign="Center">
BackColor="#C6C3C6">
<columns> <asp:TemplateField HeaderText="Select">
<itemtemplate>
<asp:CheckBox ID="chkSelect" runat="server" />


<asp:BoundField DataField="StentCat" HeaderText="StentCat"
SortExpression="StentCat" />
<asp:BoundField DataField="StentID" HeaderText="StentID"
SortExpression="StentID" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="DCno" HeaderText="DCno" SortExpression="DCno" />
<asp:BoundField DataField="Company" HeaderText="Company"
SortExpression="Company" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Size" HeaderText="Size" SortExpression="Size" />
<asp:BoundField DataField="Batch" HeaderText="Batch" SortExpression="Batch" />
<asp:BoundField DataField="Expiry" HeaderText="Expiry"
SortExpression="Expiry" />
<asp:TemplateField HeaderText="Edit/Delete/TakenBack" HeaderStyle-Width="15%">

<itemtemplate>

<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />



<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />


<asp:LinkButton ID="btnTaken" Text="Takenback" runat="server" CommandName="Takenback" />



<edititemtemplate>

<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />

<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />



<HeaderStyle Width="15%"></HeaderStyle>





<asp:Button ID="btnGetSelectedRecords" runat="server"
Text="Pass Selected Records to Grid View"
onclick="btnGetSelectedRecords_Click" />

You are viewing page
<%=GridView1.PageIndex + 1%>
of
<%=GridView1.PageCount%>



<asp:Label ID="Label1" runat="server" Text="StentCat">
             
<asp:DropDownList ID="DropDownList1" runat="server" Height="29px"
Width="163px" >
<asp:ListItem>coronary bms
<asp:ListItem>coronary des
<asp:ListItem>peripheral self expandable
<asp:ListItem>peripheral balloon mounted
<asp:ListItem Value="others">



<asp:Label ID="Label2" runat="server" Text="StentID">
               
<asp:TextBox ID="TextBox1" runat="server" Width="163px">
       


 <asp:Label ID="Label3" runat="server" Text="Date">
                  
<asp:TextBox ID="TextBox2" runat="server">
  


 <asp:Label ID="Label4" runat="server" Text="DCno">
                 
<asp:TextBox ID="TextBox3" runat="server">
  



 <asp:Label ID="Label6" runat="server" Text="Company">
           
<asp:TextBox ID="TextBox5" runat="server">
  


  <asp:Label ID="Label10" runat="server" Text="Name">
               
<asp:TextBox ID="TextBox9" runat="server">
  


 <asp:Label ID="Label7" runat="server" Text="Size">
                  
<asp:TextBox ID="TextBox6" runat="server">
  


 <asp:Label ID="Label8" runat="server" Text="Batch">
                 
<asp:TextBox ID="TextBox7" runat="server">
  


 <asp:Label ID="Label9" runat="server" Text="Expiry">
                
<asp:TextBox ID="TextBox8" runat="server">
  


<asp:Button ID="Button1" runat="server" Text="Add" OnClick="Button1_Click" />
                  
<asp:Button ID="Button2" runat="server" Text="Clear"
onclick="Button2_Click" />







page1:code behind

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}

}
private void BindGrid()
{
try{

// Function to bind the data to Grid.
SqlConnection con = new SqlConnection("Data Source=bop;Initial Catalog=Project;Integrated Security=True");
con.Open();
string sqlSelect = "SELECT * FROM Stent_table1";
SqlCommand cmd = new SqlCommand(sqlSelect, con);
cmd.ExecuteNonQuery();
/* SqlCommand getcontent = new SqlCommand("GetCountriesList", con);
getcontent.CommandType = CommandType.StoredProcedure;*/
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
protected void btnGetSelectedRecords_Click(object sender, EventArgs e)
{
// creation of data table
DataTable dtgetselectedRecords = new DataTable();
// Adding Dynamic Column to the datatable using the add range method

dtgetselectedRecords.Columns.AddRange(new DataColumn[] { new DataColumn("StentCat"), new DataColumn("StentID"), new DataColumn("Date"), new DataColumn("DCno"), new DataColumn("Company"), new DataColumn("Name"), new DataColumn("Size"), new DataColumn("Batch"), new DataColumn("Expiry") });

// Running a For Loop accross the First Grid View
foreach (GridViewRow gvrow in GridView1.Rows)
{

if (gvrow.RowType == DataControlRowType.DataRow)
{
//Finding the Checkbox in the Gridview
CheckBox chkSelect = (gvrow.Cells[0].FindControl("chkSelect") as CheckBox);
// Checking which checkbox are selected
if (chkSelect.Checked)
{
// assigning the records to a string to the cells


string dd1 = gvrow.Cells[1].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(dd1);
string stentid = gvrow.Cells[2].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(stentid);
string date = gvrow.Cells[3].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(date);
string dcno = gvrow.Cells[4].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(dcno);
string company = gvrow.Cells[5].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(company);
string name = gvrow.Cells[6].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(name);
string size = gvrow.Cells[7].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(size);
string batch = gvrow.Cells[8].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(batch);
string expiry = gvrow.Cells[9].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(expiry);


}
}

}
// Adding the Data table to Session for passing it to another page.
Session.Add("dtgetselectedRecords", dtgetselectedRecords);
Server.Transfer("~/USEDSTOCK.aspx");


}


protected void Button1_Click(object sender, EventArgs e)
{

SqlConnection MyConnection= new SqlConnection("Data Source=bop;Initial Catalog=Project;Integrated Security=True");
SqlDataReader rdr1;
string dd1 = DropDownList1.SelectedItem.ToString();
string stentid = TextBox1.Text;
string date = TextBox2.Text;
string dcno = TextBox3.Text;
string company = TextBox5.Text;
string name = TextBox9.Text;
string size = TextBox6.Text;
string batch = TextBox7.Text;
string expiry = TextBox8.Text;
try
{

MyConnection.Open();
string sqlInsert = "INSERT into Stent_table1(StentCat,StentID,Date,DCno,Company,Name,Size,Batch,Expiry) values('" + dd1 + "','" + stentid + "','" + date + "','" + dcno + "','" + company + "', '" + name + "','" + size + "','" + batch + "','" + expiry + "')";
SqlCommand cmd = new SqlCommand(sqlInsert, MyConnection);
cmd.ExecuteNonQuery();

System.Windows.Forms.MessageBox.Show("Added successfully");
GridView1.DataBind();

}
catch (Exception ex1)
{
System.Windows.Forms.MessageBox.Show(ex1.ToString());
}
finally
{
MyConnection.Close();
}


}


protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = null;
TextBox2.Text = null;
TextBox3.Text = null;
TextBox5.Text = null;
TextBox9.Text = null;
TextBox6.Text = null;
TextBox7.Text = null;
TextBox8.Text = null;
}

page2: source code

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="USEDSTOCK.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<asp:SqlDataSource ID="Sqldata" runat="server"
ConnectionString="<%$ ConnectionStrings:ProjectConnectionString2 %>"
SelectCommand="SELECT * FROM [UsedStent_table]">


<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
Width="1132px" AllowPaging="True">
<pagerstyle forecolor="Black" horizontalalign="Center">
BackColor="#C6C3C6">




<columns> <asp:BoundField DataField="StentCat" HeaderText="StentCat"
SortExpression="StentCat" />
<asp:BoundField DataField="StentID" HeaderText="StentID"
SortExpression="StentID" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="DCno" HeaderText="DCno" SortExpression="DCno" />
<asp:BoundField DataField="Company" HeaderText="Company"
SortExpression="Company" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Size" HeaderText="Size" SortExpression="Size" />
<asp:BoundField DataField="Batch" HeaderText="Batch" SortExpression="Batch" />
<asp:BoundField DataField="Expiry" HeaderText="Expiry"
SortExpression="Expiry" />




You are viewing page
<%=GridView2.PageIndex + 1%>
of
<%=GridView2.PageCount%>



page2:code behind

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ // Over here we fetch the datatable from session i.e. stored in previous page and //passed here
DataTable dtselectedRows = Session["dtgetselectedRecords"] as DataTable;
GridView2.DataSource = dtselectedRows;
GridView2.DataBind();
}
}}
Posted
Comments
Sinisa Hajnal 15-Jan-15 8:05am
   
Too much code. Extract only the relevant part. Describe HOW it doesn't behave in the way you're expecting - since you're not getting any errors we cannot guess in what way it doesn't behave.

Critically, you should take the rows from one grdid, put them into separate datatable, put datatable into session object and Server.Transfer to page2. There, you unwrap datatable from the session and set it as datasource to grid2.

1 solution

Your code is just too messy and not readable. Instead, let's do a simple exercise to demonstrate the approach step by step:
Say you have a GridView and a button for transferring checked rows in "webform1.aspx" like this:
XML
<form id="form1" runat="server">
<div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="chkbox" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-Width="200" />
            <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="200" />
        </Columns>
    </asp:GridView>
    <br>
    <asp:Button ID="btnTransfer" runat="server" Text="Transfer selected records" OnClick="TransferSelectedRecords" />
</div>
</form>

and its code behind "webform1.aspx.cs" like this (note the comments):
protected void Page_Load(object sender, EventArgs e)
 {
     if (!this.IsPostBack)
     {
         DataTable dt = new DataTable();
         dt.Columns.AddRange(new DataColumn[2] { new DataColumn("ID"), new DataColumn("Name") });
         dt.Rows.Add("1", "Steve");
         dt.Rows.Add("2", "Bill");
         dt.Rows.Add("3", "Mary");
         dt.Rows.Add("4", "Tanaka");
         GridView1.DataSource = dt;
         GridView1.DataBind();
     }
 }

 protected void TransferSelectedRecords(object sender, EventArgs e)
 {
     // flag to indicate the present of any checked row
     bool isAnyRowSelected = false;

     // loop thru the rows to find the first checked row
     foreach (GridViewRow row in GridView1.Rows)
     {
         if (row.RowType == DataControlRowType.DataRow)
         {
             CheckBox chkRow = (row.Cells[0].FindControl("chkbox") as CheckBox);
             if (chkRow.Checked)
             {
                 // set flag to true if a checked row is found
                 isAnyRowSelected = true;
                 // and exit the loop
                 break;
             }
         }
     }

     if (isAnyRowSelected)
     {
         // do a server.transfer to the new page
         Server.Transfer("WebForm2.aspx");
     }
     else
     {
         ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
     }
 }


Now, create the "webform2.aspx" with a similar GridView like this:
XML
<form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView2"  runat="server" AutoGenerateColumns="false">
<Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-Width="200" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="200" />
 </Columns>
</asp:GridView>
    </div>
    </form>

The code behind "webform2.aspx.cs":
protected void Page_Load(object sender, EventArgs e)
 {
     if (this.Page.PreviousPage != null)
     {
         GridView GridView1 = (GridView)this.Page.PreviousPage.FindControl("GridView1");

         DataTable dt = new DataTable();
         dt.Columns.Add("ID");
         dt.Columns.Add("Name");
         dt.AcceptChanges();

         for (int i = 0; i < GridView1.Rows.Count; i++)
         {
             GridViewRow row = GridView1.Rows[i];
             CheckBox chkbox = (CheckBox)row
                                 .Cells[0].FindControl("chkbox");
             if (chkbox.Checked)
             {
                 string id = row.Cells[1].Text;
                 string name = row.Cells[2].Text;
                 dt.Rows.Add(id, name);

             }
         }

         // bind the datatable to GridView2
         GridView2.DataSource = dt;
         GridView2.DataBind();
     }
 }

Take your time to study this and adapt to your need.
   
v2
Comments
Member 11377180 16-Jan-15 8:49am
   
This code has one problem..2nd gridview is in Webform1 itself not in webform2.. when i click button to transfer it must just show successfully sent msg,thats it.Later wen i open webform2 gridview2 must be shown..
Peter Leow 16-Jan-15 10:13am
   
Read this: http://www.codeproject.com/Articles/775221/Server-Transfer-VS-Response-Redirect-Simplified

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900