Show text in a label after refresh - c#

When I update a value in database, it doesn't show anymore in my drop-down-list. I update my page to not show this value in my drop-down-list anymore. Now I refresh the page automatically after removing this item so you can't choose that item again but I want to show in a label that "This value was removed!".
But it won't appear after the page is refresh.
protected void btnBevRekeningVerwijderen_Click(object sender, EventArgs e)
{
B.RekeningVerwijderen(Convert.ToInt32(ddlRekeningVerwijderen.SelectedValue));
Page.Response.Redirect(Page.Request.Url.ToString(), true);
lblRekeningMakenInfo.ForeColor = System.Drawing.Color.Green;
lblRekeningMakenInfo.Text = "The value is removed!";
}

The label won't show if you refresh the page (could be simpler if it didn't), however now you can use Session or Cookie:
if(Session["removed"] == true)
{
lblRekeningMakenInfo.Text = "The value is removed!";
Session["removed"] = null;
}
When removing you should set the session:
Session["removed"] = true;

Related

Saving entire page's controls state in session

I have many aspx pages which are a process to create a final form. eg,
Select Item Type Page -> Select item color page -> Select item quantity page -> Complete Page
Each page have a next and a previous button and when I move from the first page to the second page and the user clicks the previous button returning to the first, the control's states will be reset losing all the user's input
I thought of saving the controls in a session this way:
protected void btn_Next_Click(object sender, EventArgs e)
{
if (validateForm() == true)
{
Session["test1"] = RadioButtonList1;
Response.Redirect("nextpage.aspx");
}
}
And loading it this way:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["test1"] != null)
RadioButtonList1 = (RadioButtonList)Session["test1"];
getInfo();
}
}
However, I selected the 2nd item in the radiobuttonlist1 and when i move to the 2nd page and back to the 1st, it didn't load the exact state of the radiobuttonlist1. The debugging shows it went into the RadioButtonList1 = (RadioButtonList)Session["test1"]; code
Can you try this :
Set the value attribute for each list-item and retrieve the selected value in a session like this
Session["test1"] = RadioButtonList1.SelectedItem.Value;
and while loading
RadioButtonList1.SelectedValue = (String) Session["test1"];

Need to set Property and open link at same time inside a TableCell

I have an asp:Table that is populated in the code behind with TableCells.
I started at this Q&A and was able to set up hyperlinks to the desired page. However, I need to set a C# Property as the link is being clicked.
The first column of the Table has names, my goal was to make the names clickable links that would open a new window or tab (different URL) and pass a Property like described here (In the section : Getting Public Property Values from the Source Page) for the next page to use.
I made the property but for the life of me can't figure out how to set the property as the link is being clicked. I've tried using Hyperlink, Linkbutton, and Button as well as having an HTML a href string placed in the cell.
I think LinkButton came the closest but it did not have a UseSubmitBehavior option to set to false so the link would not process.
I thought that this would be a simple process, set the property and then follow the link.
EDIT
Currently, have the code below, When I click the buttons nothing happens, it never enters the link_Click event, p.ID is what I am going to set the property to, I think I can get it from sender or e parameters somehow.
foreach (Person p in people)
{
DivDetail.Visible = true;
TableRow tRow = new TableRow();
Table2.Rows.Add(tRow);
TableCell tCell = new TableCell();
Button link = new Button();
link.Text = p.FullName;
link.ToolTip = p.ID;
link.UseSubmitBehavior = false;
link.Attributes.Add("OnClick", "link_Click");
tCell.Controls.Add(link);
tCell.Font.Bold = true;
tRow.Cells.Add(tCell);
//other cells of row populated
}
void link_Click(object sender, EventArgs e)
{
Response.Redirect("/Orig.aspx");
}
I think you are looking for a QueryString item. You can put a variable in the url that is being clicked and read that variable on the other page.
Lets say in page 1 you create the hyperlink with the url, and you want to send a variable called myVariable to the next page. You can add it to the link
HyperLink link = new HyperLink();
link.NavigateUrl = "/Page2.aspx?myVariable=" + myVariable;
link.Text = "My Link";
Now on Page 2 you can read that query string item again into a variable for use in code behind
if (Request.QueryString["myVariable"] != null)
{
string myVariable = Request.QueryString["myVariable"];
}
But you can also do a form post to another page, so all the form field items can be read on the other page. So you would add a LinkButton to page 1 and set it's PostBackUrl to page 2.
LinkButton linkbutton = new LinkButton();
linkbutton.PostBackUrl = "/Page2.aspx";
linkbutton.Text = "My LinkButton";
Now when the button is clicked you can get the posted items in code behind of page 2.
foreach (string key in Request.Form.Keys)
{
Response.Write(key + ": " + Request.Form[key] + "<br>");
}
A third option would be to do a normal PostBack on Page 1 and then set a Session and redirect to Page 2 and read the Session there.
LinkButton linkbutton = new LinkButton();
linkbutton.Click += Linkbutton_Click;
linkbutton.Text = "My LinkButton";
private void Linkbutton_Click(object sender, EventArgs e)
{
Session["myVariable"] = myVariable;
Response.Redirect("/Page2.aspx");
}
Assuming you need to set SomeProperty to someValue and then send the browser to someUrl, use a LinkButton and set its Click even handler up like this:
void MyLinkButton_Click(object sender, EventArgs e)
{
SomeProperty = someValue;
Response.Redirect(someUrl);
}
If the property value isn't available server-side, you can pass it in a hidden form variable:
void MyLinkButton_Click(object sender, EventArgs e)
{
SomeProperty = Request.Form["SomeField"];
Response.Redirect(someUrl);
}
Or, if it's a problem to set a form variable, you can set the value up using the OnCommand Method. Set it this way as you bind the table:
protected void Table_ItemDataBound(object sender, EventArgs e)
{
LinkButton lb = e.Item.FindControl("MyLinkID") as LinkButton;
lb.CommandArgument = someValue;
}
and read it this way:
void MyLinkButton_Click(object sender, EventArgs e)
{
SomeProperty = e.CommandArgument;
Response.Redirect(someUrl);
}
If you need to set a property on the destination page (which would make a little more sense) you'll have to temporarily store it in session...
void MyLinkButton_Click(object sender, EventArgs e)
{
Session["Temp"] = Request.Form["SomeField"];
Response.Redirect(someUrl);
}
...and then set it:
//This is the load event handler for the second page
public void Page_Load()
{
this.SomeProperty = Session["Temp"];
Session.Remove("Temp");
}

Add dynamic ASP.NET controls via a DropDownList to the page

- Primary Info:
In my recent project, I need to have a page with a DropDownList with some items like 'firstName' , 'lastName' , 'Age' and etc. I want to add optional controls to the page when every item selected by user. For example when user select the 'Age' another dropdownlist created dynamically with these values : 'Less than 10'
'Between 10 and 30'
'more than 30'
Here is a button that add this user selection to listBox and let user to choice another options. (I made a query at last according to user choices and send it to db)
- What I do:
I create a dropDownList and set it's AutoPostBack property to true and adds some items in it and user must select one of those item. then I add user SelectedValue of dropDownList in a Cache variable before page post back happens:
protected void DropDownListColumnNameSelectedIndexChanged(object sender, EventArgs e)
{
Cache["SelectedKey"] = dropDownListColumnName.SelectedValue;
}
When user select an item from dropDownList *DropDownList_SelectedIndexChanged* fire, and I must create controls dynamically in a place holder:
var textBoxName = new TextBox
{
ID = "textBoxName",
CssClass = "str-search-textbox-highlight",
ViewStateMode = ViewStateMode.Disabled
};
placeHolderFirstItem.Controls.Add(textBoxName);
- What is the problem?
When I try add new control in current Button_Click event, control added successfully to page but I can't find it by placeHolderFirstItem.Controls.Find("textBoxName") actually placeHolderFirstItem.Controls.Count is always zero. So I can't get textBoxName.Text values.
I try to google that for any solution and I found some solution that I must add controls in Page.OnInit so I add controls in overridden OnInit(e):
protected override void OnInit(EventArgs e)
{
if (!Page.IsPostBack) return;
var textBoxName = new TextBox
{
ID = "textBoxName",
CssClass = "str-search-textbox-highlight",
ViewStateMode = ViewStateMode.Disabled
};
placeHolderFirstItem.Controls.Add(textBoxName);
}
after doing this I can find "textBoxName" in placeHolderFirstItem, but it fire before DropDownList_SelectedIndexChanged !
so how can I add new controls to place holder exactly when user change the dropDownList value and how can I read new controls value?
Thanks in advance,
Mohsen.
- Updated:
Here is the better solution
(http://forums.asp.net/p/1959726/5596531.aspx?p=True&t=635244790943067485&pagenum=1)
When you are dynamically adding controls, you have to reload the controls into the control tree everytime thereafter for it to appear. With the help of viewstate, you could change your code sample to have:
ViewState("ShowTextbox") = true
And then in your init routine:
protected override void OnInit(EventArgs e)
{
if (!Page.IsPostBack) return;
if (ViewState("ShowTextBox") == true) {
var textBoxName = new TextBox
{
ID = "textBoxName",
CssClass = "str-search-textbox-highlight",
ViewStateMode = ViewStateMode.Disabled
};
placeHolderFirstItem.Controls.Add(textBoxName);
}
}
Please note it's much easier to have a control on the control tree, and then show/hide by setting Visible to true/false, because of these ASP.NET control tree issues.

ASP Drop Down List postback losing session state in Chrome and IE but firefox works perfect

I have a ddl on my master page that is set to auto postback to retrieve data based on their selection. The values in the list are customerids and they have been setup as a session variable and once someone has selected which one, the code looks at session["selectedCustomer"] and populates the appropriate fields. Now the problem that I have run into, is when the auto postback goes through on Chrome or IE, it populates the fields and then the selected customer is set back to default which is "Please select customer" which has no value behind it. In firefox after the postback it populates the fields and then the drop down list stays on the selected customer.
protected void ddlSelectedCustomer_SelectedIndexChanged(object sender, EventArgs e)
{
CustomerSelected();
Response.AppendHeader("Refresh", "0; URL=" + this.ResolveUrl("~/AcesSetup/storefront.aspx"));
try
{
ViewState["SelectedAccordionIndex"] = ((AjaxControlToolkit.Accordion)FindControl("MyAccordion")).SelectedIndex;
}
catch (Exception ex)
{ }
}
That is the selectedChanged event for my ddl
private void CustomerSelected()
{
//clear the session variable
Session.Remove("selectedCustomer");
//user selected customer
if (ddlSelectedCustomer.SelectedIndex != -1)
{
Session["selectedCustomer"] = ddlSelectedCustomer.SelectedValue;
}
}
private void fillCustomers()
{
//save the value of the current selection to reselect later if still exists
string origSelectedItem = ddlSelectedCustomer.SelectedValue;
//check what role the user is in
string usersRole = Roles.GetRolesForUser(Membership.GetUser().UserName)[0];
MembershipUser user = Membership.GetUser();
switch (usersRole)
{
case "SalesRep":
ddlSelectedCustomer.DataSource = DAL.Util.getSalesRepCustomers((Guid)user.ProviderUserKey);
ddlSelectedCustomer.DataBind();
break;
case "BasicUser":
case "Customer":
ddlSelectedCustomer.DataSource = DAL.Util.getCustomersListForUser((Guid)user.ProviderUserKey);
ddlSelectedCustomer.DataBind();
break;
case "Admin":
case "SuperAdmin":
ddlSelectedCustomer.DataSource = DAL.Util.getAllCustomersList();
ddlSelectedCustomer.DataBind();
break;
default:
break;
}
//if user had a company selected, reselect it if it exists
if (origSelectedItem != string.Empty)
ddlSelectedCustomer.SelectedValue = origSelectedItem;
else if (ddlSelectedCustomer.Items.Count == 1)
{
//if only one item in the list, select it
ddlSelectedCustomer.Items[0].Selected = true;
}
This what populates the drop down list. Also when Firefox does the post back the whole page does not appear to reload, with Chrome or IE the whole page will flash white and reload.. That to me seems like it has something to do with it. Because with Firefox the viewstate I have for my accordion works like it is supposed to, but again not with Chrome or IE.
If you have any help I would appreciate it, if there is anything I can clear up, or any code snipets I could provide I will do my best to update everything.
Thank you.
protected void ContentPlaceHolder1_Load(object sender, EventArgs e)
{
if (Session["selectedCustomer"] != null)
{
ddlSelectedCustomer.SelectedValue = Session["selectedCustomer"].ToString();
}
}
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" OnLoad="ContentPlaceHolder1_Load">
</asp:ContentPlaceHolder>
You don't lose the session , you just clear the selection .so try to handle the Load event of your ContentPlaceHolder by setting the selected value by the stored session.

back to the previous page with values still present in textboxes

I have a start page with textboxes and I am sending the values entered in the textbox to another page using Cache on click of a next button.
Now I have a problem that when the user goes to the next page ad decides to go back again he should be able to do so and the values he entered in the textboxes should still be present.
Is there a way to do so...
My code for sending values is:
protected void Button4_Click(object sender, EventArgs e)
{
if (TextBox2.Text == "" || TextBox3.Text == "")
{
Label1.Text = ("*Please ensure all fields are entered");
Label1.Visible = true;
}
else
{
Cache["PolicyName"] = TextBox2.Text;
Cache["PolicyDesc"] = TextBox3.Text;
Response.Redirect("~/Addnewpolicy3.aspx");
}
}
and I receive this by on the next page as:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string pn = Cache["PolicyName"].ToString();
string pd = Cache["PolicyDesc"].ToString();
string os = Cache["OperatingSystem"].ToString();
}
}
It sounds like you want to take adavantage of Cross-Page postbacks which were added to ASP.NET in version 2.0
The following URL should offer some guidance
http://msdn.microsoft.com/en-us/library/ms178139.aspx
Cache is shared by all users. The code above will result in information being shared between users. If you want per-user temp storage you should use the Session instead. Other than that I can make 2 recommendations:
Proceed with Session, your approach is fine
Look at the Wizard control http://msdn.microsoft.com/en-us/magazine/cc163894.aspx
To make the values restore, in the controls simple do this:
<asp:TextBox ID="txtName" runat="server" text='<%=Session["Name"] %>'></asp:TextBox>
Pretend you got two pages, page1 and page2:
1st you search on page1 and get the result, then click into the link and enter 2nd page.
My suggestion is when you click on hyperlink/button on page1, you can put the textbox field value into session like
Session["key"] = txtbox.Text;
After you enter 2nd page, you can try to set session equal to itself in "Back" button action for bring back to page1.
Session["key"] = Session["key"].ToString();
Insert the code when you back from page2, get value from session and put into search form's textbox
txtbox.Text = Session["key"].ToString();

Categories

Resources