Hi acne.star52,
Please get the session value inside the page load.
Please refer below sample.
HTML
Default
<asp:GridView runat="server" AutoGenerateColumns="false" ID="gvDetails">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkED" Text="Edit" runat="server" OnClick="lnkED_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="CustomerId" DataField="CustomerId" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Country" DataField="Country" />
</Columns>
</asp:GridView>
<asp:Button ID="btnNew" Text="Create New" runat="server" OnClick="btnNew_Click" />
Home
<table>
<tr>
<td>Name:</td>
<td>
<asp:TextBox runat="server" ID="txtName" />
</td>
</tr>
<tr>
<td>Country</td>
<td>
<asp:TextBox runat="server" ID="txtCountry" />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSave" Text="Save" runat="server" OnClick="btnSave_Click" />
</td>
</tr>
</table>
Namespaces
Default
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Home
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
Code
Default
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId,Name,Country FROM Customers", con))
{
con.Open();
gvDetails.DataSource = cmd.ExecuteReader();
gvDetails.DataBind();
con.Close();
}
}
}
protected void btnNew_Click(object sender, EventArgs e)
{
Response.Redirect("Home.aspx");
}
protected void lnkED_Click(object sender, EventArgs e)
{
GridViewRow gvRow = (sender as LinkButton).NamingContainer as GridViewRow;
int customerId =int.Parse(gvRow.Cells[1].Text);
string name = gvRow.Cells[2].Text;
string country = gvRow.Cells[3].Text;
Session["customerId"] = customerId.ToString();
Session["name"] = name.ToString();
Session["country"] = country.ToString();
Response.Redirect("Home.aspx");
}
Home
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
txtName.Text = Session["name"].ToString();
txtCountry.Text = Session["country"].ToString();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES (@Name,@Country)", con))
{
cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());
cmd.Parameters.AddWithValue("@Country", txtCountry.Text.Trim());
con.Open();
cmd.ExecuteReader();
con.Close();
}
}
Response.Redirect("Default.aspx");
}
Screenshot