Passing data to another page for bookmarking function - c#

I have 1 gridview look like this:
Anytime user click on Bookmark button, I want to send the data in ProgramID column of that row to the List and pass it to second gridview in another page.But my second gridview doesn't display any data. What am I doing wrong?
This is my code for Bookmark button:
protected void btnSelect_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
GridViewRow row = (GridViewRow)b.NamingContainer;
var ProgramID = row.FindControl("lblProgramID") as Label;
string stringProgramID = ProgramID.Text;
List<string> bookmarkPrograms = new List<string>();
bookmarkPrograms.Add(stringProgramID);
Session["BookmarkProgram"] = bookmarkPrograms;
}
And here is the code in Bookmark page:
protected void Page_Load(object sender, EventArgs e)
{
List<string> bookMarkPrograms = (List<string>)Session["BookMarkPrograms"];
GridView1.DataSource = bookMarkPrograms;
GridView1.DataBind();
}

Related

Dynamically created linkbuttons' common event not firing

Whenever DropDownList SelectedIndexChanged, I am adding LinkButtons as ul-li list in codebehind. Each linkbuttons were assigned with IDs and a common Click event. Problem is code in Click event is not executed or maybe event is not triggered. My code below: [Edit] I tried like this as suggested in other posts (dynamically created list of link buttons, link buttons not posting back)
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
populate();
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
populate();
}
void populate()
{
HtmlGenericControl ulList = new HtmlGenericControl("ul");
panel.Controls.Add(ulList);
foreach (DataRow dr in drc)
{
HtmlGenericControl liList = new HtmlGenericControl("li");
ulList.Controls.Add(liList);
var lnk = new LinkButton();
lnk.ID = dr["col1"].ToString();
lnk.Text = dr["col1"].ToString();
lnk.Click += Clicked;
liList.Controls.Add(lnk);
}
}
private void Clicked(object sender, EventArgs e)
{
var btn = (LinkButton)sender;
label1.Text = btn.ID.ToString();
}
Im missing something. Any help please.
Here the issue is with the ViewState. When the selected index of the dropdownlist changes there is a postback which takes place and the previous state is lost, so at this point you have to maintain the state of the controls.
Now in your code actually the state of the control is lost and so the click event does not fire. So the solution is to maintain the state of the controls.
The Below is a working example, you can just paste it and try.
This is my page load.
protected void Page_Load(object sender, EventArgs e)
{
for (var i = 0; i < LinkButtonNumber; i++)
AddLinkButton(i);
}
Similarly you have to maintain the state of the previously added control like this.
private int LinkButtonNumber
{
get
{
var number = ViewState["linkButtonNumber"];
return (number == null) ? 0 : (int)number;
}
set
{
ViewState["linkButtonNumber"] = value;
}
}
The below is my SelectedIndexChanged Event for the DropDownList
protected void Example_SelectedIndexChanged(object sender, EventArgs e)
{
AddLinkButton(LinkButtonNumber);
LinkButtonNumber++;
}
I have a function which dynamically creates the controls, which is called on the page load and on SelectedIndexChanged.
private void AddLinkButton(int index)
{
LinkButton linkbutton = new LinkButton { ID = string.Concat("txtDomain", index) };
linkbutton.ClientIDMode = ClientIDMode.Static;
linkbutton.Text = "Link Button ";
linkbutton.Click += linkbutton_Click;
PanelDomain.Controls.Add(linkbutton);
PanelDomain.Controls.Add(new LiteralControl("<br />"));
}
And this is the Click event for the LinkButton
void linkbutton_Click(object sender, EventArgs e)
{
//You logic here
}
I solved it using brute code lol.
Since controls' event were not bound on postback then we recreate them on postback. So in my Page_Load I called the module that re-creates the controls, thus binding them to corresponding event. This works, but...
Re-creating these controls create duplicates (Multiple Controls with same ID were found) and you will get into trouble in instances of finding a control by ID like using panel.FindControl.
To remedy this scenario, I put a check if same control ID already existed before recreating them, and voila! It works.
protected void Page_Load(object sender, EventArgs e)
{
populate();
}
void populate()
{
HtmlGenericControl ulList = new HtmlGenericControl("ul");
panel.Controls.Add(ulList);
foreach (DataRow dr in drc)
{
HtmlGenericControl liList = new HtmlGenericControl("li");
ulList.Controls.Add(liList);
if (liList.FindControl(dr["col1"].ToString()) == null)
{
var lnk = new LinkButton();
lnk.ID = dr["col1"].ToString();
lnk.Text = dr["col1"].ToString();
lnk.Click += Clicked;
liList.Controls.Add(lnk);
}
}
}

how to bind database field to a drop downs?

i'm requesting data from database through a D A L file. I want to data bind and show a drop down menu's single option selected against that of the database. How should i do it?
here's my code:
Pages pg = new Pages();
public static string pgId;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Bind_ddlParentPage();
Bind_ddlPageModel();
Bind_ddlArticleModel();
if (!IsPostBack)
{
pgId = Request.QueryString["pageId"];
if (pgId != null)
{
GetData();
}
}
}
}
public void GetData()
{
ddlParentPage.SelectedValue = pg.ParentPage;
//Bind_ddlParentPage();---dropdownlist which is causing problem.
//I want to set this data:: pg.ParentPage to dropdownlist in another
page
ddlPageModel.SelectedValue = pg.PageModel;
//Bind_ddlPageModel();
//All the three drop downs have same table for the source,
'Pages' table and this page is the same page for adding new entry to
Pages table.
ddlArticleModel.SelectedValue = pg.ArticleModel;
//Bind_ddlArticleModel();
}
First, you have a duplication in your conditional statement:
if(!IsPostBack) {
...
if(!IsPostBack) {
...
}
}
Second, you need to bind the data to the dropdown, then set the selected value. Refer: this post
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataBind(); // get the data into the list you can set it
DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
}
}

ASP.NET GridView does not update its row

I followed this tutorial on MSDN for ASP.NET GridView Update Row, but it does not work.
updatedItem.DepartureCity = ((TextBox)(row.Cells[2].Controls[0])).Text;
Still gives the original value from the cell and not the updated one.
public partial class ManagePage : System.Web.UI.Page
{
BusScheduleModelContainer modelContainer = new BusScheduleModelContainer();
protected void Page_Load(object sender, EventArgs e)
{
//FormsAuthentication.RedirectFromLoginPage()
//if (!HttpContext.Current.User.Identity.IsAuthenticated)
//{
// Server.Transfer("LoginPage.aspx");
//}
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
}
protected void RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var routeID = int.Parse(e.Values[0].ToString());
var removedItem = modelContainer.BusRoutes.FirstOrDefault(
item => item.RouteID == routeID);
if (removedItem != null)
{
modelContainer.BusRoutes.Remove(removedItem);
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
modelContainer.SaveChanges();
}
}
protected void RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var routeID = int.Parse(e.NewValues[0].ToString());
var updatedItem = modelContainer.BusRoutes.FirstOrDefault(
item => item.RouteID == routeID);
if (updatedItem != null)
{
GridViewRow row = resultsGridView.Rows[e.RowIndex];
var res = row.FindControl("ctl00$ContentPlaceHolder1$resultsGridView$ctl02$ctl03");
updatedItem.DepartureCity = ((TextBox)(row.Cells[2].Controls[0])).Text;
updatedItem.ArrivalCity = ((TextBox)(row.Cells[3].Controls[0])).Text;
updatedItem.DepartureTime = DateTime.Parse(((TextBox)(row.Cells[4].Controls[0])).Text);
updatedItem.ArrivalTime = DateTime.Parse(((TextBox)(row.Cells[5].Controls[0])).Text);
}
resultsGridView.EditIndex = -1;
BindData();
}
protected void RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
resultsGridView.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
}
protected void RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
resultsGridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
private void BindData()
{
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
}
}
<div>
<asp:GridView runat="server" ID="resultsGridView"
AutoGenerateColumns="true" AllowPaging="true"
AutoGenerateDeleteButton="true" OnRowDeleting="RowDeleting"
AutoGenerateEditButton="true" OnRowUpdating="RowUpdating"
OnRowEditing="RowEditing" OnRowCancelingEdit="RowCancelingEdit">
</asp:GridView>
</div>
Do you use CommandField for update controler?
If so, when you click update button, first it will do Page_Load event handler, after that do the implementation in RowUpdating event handler.
You should try to check post back in Page_Load event handler like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
}
}
By this way, it will bind data to the GridView only first time you open this page.
For post back event such as clicking update button, it will not bind the original data to GridView again.
In RowUpdating method you need to add modelContainer.SaveChanges(); like below:
if (updatedItem != null)
{
GridViewRow row = resultsGridView.Rows[e.RowIndex];
var res = row.FindControl("ctl00$ContentPlaceHolder1$resultsGridView$ctl02$ctl03");
updatedItem.DepartureCity = ((TextBox)(row.Cells[2].Controls[0])).Text;
updatedItem.ArrivalCity = ((TextBox)(row.Cells[3].Controls[0])).Text;
updatedItem.DepartureTime = DateTime.Parse(((TextBox)(row.Cells[4].Controls[0])).Text);
updatedItem.ArrivalTime = DateTime.Parse(((TextBox)(row.Cells[5].Controls[0])).Text);
modelContainer.SaveChanges();
}

Linkbutton click event does not work inside gridview

I have a webpage where I have a gridview. I have populated the gridview on page load event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadGridView();
}
}
This is the load gridview method.
private void loadGridView()
{
dataTable dt = getData(); // this function populates the data table fine.
gridView1.dataSource = dt;
gridview1.dataBind();
}
Now I have added linkButtons in one of the gridview columns in the RowDataBound event of the grid view.
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lb = new LinkButton();
lb.Text = str1; // some text I am setting here
lb.ID = str2; // some text I am setting here
lb.Click += new EventHandler(lbStatus_click);
e.Row.Cells[3].Controls.Add(lb);
}
Finally This is the event Handler code for the link button click event.
private void lbStatus_click(object sender, EventArgs e)
{
string str = ((Control)sender).ID;
// next do something with this string
}
The problem is, the LinkButtons appear in the data grid fine, but the click event does not get execute. the control never reaches the event handler code. when I click the link button, the page simply gets refreshed. What could be the problem?
I have tried calling the loadGridView() method from outside the (!isPostBack) scope, but it did not help!
Try to work with the "Command" property instead of Click event
LinkButton lnkStatus = new LinkButton();
lnkStatus.ID = string.Format("lnkStatus_{0}", value);
lnkStatus.Text = "some text here";
lnkStatus.CommandArgument = "value";
lnkStatus.CommandName = "COMMANDNAME";
lnkStatus.Command += new CommandEventHandler(lnkStatus_Command);
Otherwise, if my proposal doesn't satisfy you, you have to remove the !Postback on Page_Load event.
you have to use OnRowCommand event of the GridView.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("LinkButton1")) //call the CommandArgument name here.
{
//code
}
}

Textbox value doesn't get updated

I have a asp.net page with a datalist with a textbox and a button on it, on page load the textbox gets text in it, if I change the text and press the button the text doesn't get updated.
What am I doing wrong?
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable table = CategoryAccess.GetProducts();
ProductList.DataSource = table;
ProductList.DataBind();
}
}
protected void btn_Click(object sender, EventArgs e)
{
string Name = textbox.Text;
CategoryAccess.UpdateProducts(Name);
}
}
I had same problem. I found that I put textbox.text = "xxx" in Page_Load() but outside if(!ispostback).
Try to add EnableViewState property in your textBox control and set the value to true.
e.g.
<asp:TextBox ID="textBox1"
EnableViewState="true"
MaxLength="25"
runat="server"/>
or you can do it programatically:
protected void Page_Load(object sender, EventArgs e)
{
textBox1.EnableViewState = true;
}
You need to bing again the new data...
protected void btn_Click(object sender, EventArgs e)
{
string Name = textbox.Text;
// you update with the new parametre
CategoryAccess.UpdateProducts(Name);
// you get the new data
DataTable table = CategoryAccess.GetProducts();
// and show it
ProductList.DataSource = table;
ProductList.DataBind();
}

Categories