Pass ASP.Net GridView from one page to another page - c#

I want to pass all the gridview value into another page
I have one gridview in PatientDetails.aspx page and one button as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" AutoGenerateSelectButton="true"
AutoGenerateDeleteButton="true" OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>"
SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" OnCommand="btnformatric_Command" />
on codebehind of PatientDetails.aspx is as below
protected void btnformatric_Click(object sender, EventArgs e)
{
if (gvDoctorList.SelectedRow != null)
{
Server.Transfer("Patientstaticformatrix.aspx");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
}
}
Now on the second page name Patientstaticformatrix.aspx the code behind is as below
protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.PreviousPage != null)
{
GridView gvDoctorList = (GridView)this.Page.PreviousPage.FindControl("gvDoctorList");
GridViewRow selectedRow = gvDoctorList.SelectedRow;
Response.Write("PatientId: " + selectedRow.Cells[0].Text + "<br />");
Response.Write("firstname: " + selectedRow.Cells[1].Text + "<br />");
Response.Write("lastname: " + selectedRow.Cells[2].Text + "<br />");
}
}
I had debug the code in second page....the value for gvDoctorList is null as well as the selectedRow is showing error of nullreference.
Can you please let me where I am wrong?

As i have seen your previous question also, So i can suggest you one thing, rather than keeping your gridview in session(which is expensive) you can use RowCommand event, and after having button here i don't think you need checkbox or chk_CheckedChanged event, you can pass the PatientID to your next page there you can write query to insert selected row data to your new table.
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged"
AutoPostBack="true" />
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'>
</asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%#
Eval("PatientId") %>' CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
int pID = Convert.ToInt32(e.CommandArgument);
// either put ID in session and check
Session["PatientID"] = Convert.ToString(pID);
Server.Transfer("Patientstaticformatrix.aspx");
}
}
On page_Load Event
protected void Page_Load(object sender, EventArgs e)
{
string pID = Convert.ToString(Session["PatientID"]);
if(!string.IsNullOrEmpty(pID))
{
int patientID = Convert.ToInt32(pID);
//Call Stored procedure which will insert this record with this ID
// to another table
}
}

Try using Session Variables. You can set the GridView into a Session variable that can then be retreived later so long as the same session is still active.
You can use the following code to set the Session Variable on your first page :
Session["gvDoctorList"] = gvDoctorList;
And then to retreive from the variable on your second page :
GridView gvDoctorList = (GridView)Session["gvDoctorList"];
For more information on Sessions see the MSDN Session State Overview.

I have decided to add a second answer based on the correct comments from Ahmed, The session variables really shouldn't hold the amount of data of the gridview due to memory issues.
The following should work accordingly for what I assume you are doing :
Essentially when you are selecting the row to go to the next page you are trying to retrieve the data of that row onto the new page. Is this Assumption correct? If so then you have a number of options for you to use.
Again you could use the Session Variables to store the data of the row once extracted on the first page :
protected void btnformatric_Click(object sender, EventArgs e) {
if (gvDoctorList.SelectedRow != null) {
GridViewRow selectedRow = gvDoctorList.SelectedRow;
Session["PatientId"] = selectedRow.Cells[0].Text;
Session["firstname"] = selectedRow.Cells[1].Text;
Session["lastname"] = selectedRow.Cells[2].Text;
Server.Transfer("Patientstaticformatrix.aspx");
} else {
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
}
}
Essentially here you are on the first page and you get the data from the row. You then store this data in session variables and you can use the following to find the data from the next page :
protected void Page_Load(object sender, EventArgs e) {
if (this.Page.PreviousPage != null) {
//Retrieve values from Session Variables
Response.Write("PatientId: " + Session["PatientId"].ToString() + "<br />");
Response.Write("firstname: " + Session["firstname"].ToString() + "<br />");
Response.Write("lastname: " + Session["lastname"].ToString() + "<br />");
}
}
You also have a second option of using Query Strings to pass the data. Although for this method I believe you will have to change the Server.Transfer("Patientstaticformatrix.aspx"); to be Response.Redirect("Patientstaticformatrix.aspx");
Below is an example on using Query Strings :
protected void btnformatric_Click(object sender, EventArgs e) {
if (gvDoctorList.SelectedRow != null) {
GridViewRow selectedRow = gvDoctorList.SelectedRow;
//Create URL with Query strings to redirect to new page
Response.Redirect("Patientstaticformatrix.aspx?parentid=" + selectedRow.Cells[0].Text + "&firstname=" + selectedRow.Cells[1].Text + "&lastname=" + selectedRow.Cells[2].Text);
} else {
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
}
}
And to retrieve the values from the Request.QueryString object on the second page.
protected void Page_Load(object sender, EventArgs e) {
if (this.Page.PreviousPage != null) {
//Retrieve values from Query Strings
Response.Write("PatientId: " + Request.QueryString["parentid"].ToString() + "<br />");
Response.Write("firstname: " + Request.QueryString["firstname"].ToString() + "<br />");
Response.Write("lastname: " + Request.QueryString["lastname"].ToString() + "<br />");
}
}
Both of these solutions should meet your requirements, however they are both slightly different. The Session Variable solution is probably the preferred method as it will stop users from being able to see all of the data passed (if you need to pass confidential information) where as the Query String values will be available to anyone who can see the URL.
For more information on Session Variables and Query Strings see the below resources :
ASP.NET Session State Overview
Request.QueryString Collection

#Nunners answer is ownsome, but can also try with following way:
on anothoer page's pageload event fetch grid like:
GridView GridView1 = (GridView)this.Page.PreviousPage.FindControl("GridView1");
All the technique is given below:
http://www.aspsnippets.com/Articles/Pass-Selected-Row-of-ASPNet-GridView-control-to-another-Page.aspx
Refer above doccument.

The real answer is that you should create the same gridview on another page. This is how 99% of ASP.NET sites work since that page at some point will be writing/updating/deleting data. Or just use the same page - why redirect to show the same data?

I found some solution:
In Source aspx after grid databind:
Session["gridtoexcel"] = yourgrid;
In destination aspx
var grid = ((GridView)Session["gridtoexcel"]);
gridToExcel.Columns.Clear();
foreach (DataControlField col in grid.Columns)
gridToExcel.Columns.Add(col);
gridToExcel.DataSource = grid.DataSource;
gridToExcel.DataBind();
this way i can 'clone' exact grid to another page. if you need some css style don't forget of add them in destination page
PS: gridToExcel is your destination grid

Related

How to call a function when drop down list in gridview is changed?

I have a GridView and for one of the columns I'm using a drop down list that displays a list of users:
<asp:GridView style="float:left"
ID="gvBookings"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvBookings_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false"
<Columns>
<asp:BoundField DataField="FinishDate" HeaderText="Finish Date"></asp:BoundField>
<asp:TemplateField HeaderText="Time Spent By">
<ItemTemplate>
<asp:DropDownList id="ddlUsers" runat="server" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code behind I need to call a function that updates the database when the drop down list is changed. I have done this already for the FinishDate column so is there a similar way to do this for the drop down menu?
Code behind:
protected void gvBookings_RowDataBound(object sender, GridViewRowEventArgs e)
{
BHTaskClass.BookingTask booking = (BHTaskClass.BookingTask)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (TableCell c in e.Row.Cells)
{
if (count == 1)
{
string FinishTime = booking.FinishTime.HasValue ? booking.FinishTime.Value.ToString("hh':'mm") : "";
c.Text = "<input type=\"text\" id=\"txtFinishTime" + booking.ID + "\" style=\"width:70px\" type=\"text\" onblur=\"UpdateFinishTime(" + booking.ID + ",this.value)\" value=\"" + FinishTime + "\" >";
}
if (count == 2)
{
ddlUsers.SelectedValue = booking.TimeSpentName;
}
count++;
}
}
}
So when the FinishDate textbox is changed it calls the UpdateFinishTime function and this updates the database. How do I call a function for the drop down list?
ASPX
<asp:DropDownList id="ddlUsers" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="YourFunction_Changed">
</asp:DropDownList>
Code behind:
protected void YourFunction_Changed(object sender, EventArgs e)
{
//do stuff...
}
To get the Row ID you can do it as below
protected void YourFunction_Changed(object sender, EventArgs e)
{
//do stuff...
int Index = ((GridViewRow)((sender as Control)).NamingContainer).RowIndex;
// your logic follows based on the Index
}

How to redirect to another page from gridview edit event

I don't know am I using good approach.
I have a view page with gridview and edit page.
In gridview I have added:
...
<Columns>
<asp:CommandField ShowEditButton="True" ShowDeleteButton="true"></asp:CommandField>
...
And event:
OnRowEditing="rgrContact_RowEditing"
In event method I have tried to add:
protected void rgrContact_RowEditing(object sender, GridViewEditEventArgs e)
{
var id = (int)rgrContact.DataKeys[e.RowIndex].Value;
Response.Redirect("..." + id);
But there is no e.RowIndex.
How to get ID of the selected row so I can pass it to edit page?
Am I using good event?
try this:
NewEditIndex returns index of row on which you click for Edit
protected void rgrContact_RowEditing(object sender, GridViewEditEventArgs e)
{
var id = (int)rgrContact.DataKeys[e.NewEditIndex].Value;
Response.Redirect("MyEditPage.aspx?MyID=" + id);
EDIT:
DataKeyNames="DataKey1,DataKey2"
You can Use Like this
string DataKey1= rgrContact.DataKeys[e.NewEditIndex].Values[0].ToString();
string DataKey2= rgrContact.DataKeys[e.NewEditIndex].Values[1].ToString();
OR
rgrContact.DataKeys[e.NewEditIndex].Values["DataKey1"];
rgrContact.DataKeys[e.NewEditIndex].Values["DataKey2"];
As Others said No Need to Use what you said
another solution :
<ItemTemplate>
<asp:HyperLink ID="hyper" Text="this is link"
NavigateUrl= '<%# String.Format("{0}","MYpage.aspx?id=" + Eval("MY_ID_COL")) %>' runat="server" />
</ItemTemplate>

Generated ASP table add buttons that pull row values

ok so I have this ASP:Table which pulls its rows of info from a stored procedure query, only two columns but wish to add a third with a button for each row that when clicked will grab the information in the prior columns for use in another function.
not sure how the hell to code it though as the buttons are generated per row and how can I programme events for a unknown number of buttons there must be a way of doing It programmatically.
Table Header
Datacolumn1 Datacolumn2
a 2 Select
b 4 Select
e 9 Select
so when I press select on the second row it gives me string1=b string2=4
I imagine the code would look something like this (not likely but in a ideal world :D)
protected void select_row (eventargs as e)
{
string data1 = Row(e).cell(0).text
int data2 = Row(e).cell(1).text
}
For a grid like this
<asp:GridView ID="Grid1" runat="server" onrowcommand="Grid1_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Datacolumn1" HeaderText="Data column1" />
<asp:BoundField DataField="Datacolumn2" HeaderText="Data column2" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" CommandName="SelectIt" Text="Select" CommandArgument='<%# Eval("Datacolumn1") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Use RowCommand event
protected void Grid1_RowCommand(object sender, GridViewCommandEventArgs e)
{
var btn = (Button)e.CommandSource ;
if (e.CommandName == "SelectIt")
{
var Row =(GridViewRow) btn.NamingContainer;
var Datacolumn1 = Row.Cells[0].Text;
var Datacolumn2 = Row.Cells[1].Text;
btn.Text = "selected: " + Datacolumn1 + "," + Datacolumn2;
}
}

Add text from c# code to a gridview label

I need to add an specific text in an itemtemplate on a gridview...
right now I have this in my gridview
<asp:TemplateField HeaderText="Total" SortExpression="Total" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
in the part where it says
<asp:Label ID="lblTotal" runat="server" Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'>
I made an specific text, but it will always be the same text (well except in the Eval of course)... But I need to get the format I need from this method.
public static string GetFormatoMoneda(decimal decCantidad)
{
//Get data from currency (Dollars, Pesos, Euros, etc.)
DataRow dr = ConexionBD.GetInstanciaConexionBD().GetTipoDeMonedaPrincipal((int)HttpContext.Current.Session["Grupo"]);
return dr["Signo"] + Math.Round(decCantidad, 2).ToString("C").Substring(1) + " " + dr["Abreviatura"];
}
I use this method to get a specific string and use it on labels (I assign it on code on the cs file)..
But in this case... I have to insert that text on the column of a gridview...
How can I get that string value and insert it on a label inside of a templatefield/itemtemplate??
Instead of ...
Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'
...use
Text='<%#GetFormatoMoneda(Eval("Total"))%>'
However, this assumes that GetFormatoMoneda is in the same class as the web form. If not, then you need to include the class name, e.g.
Text='<%#MyClass.GetFormatoMoneda(Eval("Total"))%>'
Then you either need to make a change to GetFormatoMoneda to use an object type parameter, e.g.
public static string GetFormatoMoneda(object objCantidad)
{
var decCantidad = Convert.ToDecimal(decCantidad);
//Get data from currency (Dollars, Pesos, Euros, etc.)
DataRow dr = ConexionBD.GetInstanciaConexionBD().GetTipoDeMonedaPrincipal((int)HttpContext.Current.Session["Grupo"]);
return dr["Signo"] + Math.Round(decCantidad, 2).ToString("C").Substring(1) + " " + dr["Abreviatura"];
}
or use another method with an object parameter and call GetFormatoMoneda(decimal), passing in the correct value, such as
protected string CorrectFormat(object obj)
{
return GetFormatoMoneda(Convert.ToDecimal(obj));
}
in which case you would use
Text='<%#CorrectFormat(Eval("Total"))%>'
If you wanted to do it programmatically, this would work:
Default.aspx:
<asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvGrid_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Generate fake data
var data = Enumerable.Range(1, 20);
//Give the data to the grid
gvGrid.DataSource = data;
gvGrid.DataBind();
}
}
protected void gvGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the control
var lblTotal = (Label)e.Row.FindControl("lblTotal");
//Get the data for this row
var data = (int)e.Row.DataItem;
//Display the data
lblTotal.Text = data.ToString();
}
}

firing problem of selected_indexchanged(cant even print cell value in grid view by any event)

//code in aspx.
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="MobilePhone"
HeaderText="Mobile Phone" />
<asp:ButtonField Text="Button" ButtonType="Button" CommandName="Select" />
</Columns>
</asp:GridView>
<asp:Label ID="Label" runat="server" Text="Label"></asp:Label>
//code behind file()
protected void grid_SelectedIndexChanged(object sender,
EventArgs e)
{
int selectedRowIndex;
selectedRowIndex = grid.SelectedIndex;
GridViewRow row = grid.Rows[selectedRowIndex];
string name = row.Cells[0].Text;
Label.Text = "You selected " + name + ".";
}
Q: iam not even able to print the selected row.If anyone could help me with this issue.
You should really be getting this value from the underlying data item. But, if for some reason that value is being manipulated after it has been data-bound and you need to get the actual value of the control in that cell then you probably want something like this:
protected void grid_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = (GridViewRow)grid.Rows[grid.SelectedIndex];
string name = ((Label)row.Cells[1].Controls[1]).Text;
Label.Text = "You selected " + name + ".";
}
but... that's a pretty messy way of achieving this. Also "Label" is a pretty bad name for a label. Also, Cell[0] like you posted is going to be the column with the select button most likely, not the column with the value you want. And, once you're in the correct cell, there are 3 controls, 2 literals and a label for a normal boundfield. Control[1], the second control, is the label control that will have the value you're looking for.
You have to use a RowCommand Event instead of a SelectedIndexChanged Event.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow row = ((GridViewRow)((Button)e.CommandSource).NamingContainer);
string name = row.Cells[0].Text;
Label.Text = "You selected " + name + ".";
}
}

Categories

Resources