I'm designing a CheckOut page and I want to automatically load the signed in user's information with data from the database using linq. I'm using a method FillPage which I call in PageLoad and so far it looks like this:
void FillPage(int id)
{
using (DatabaseContext db=new DatabaseContext()
{
var query = (from user in db.[tblUser]
where user.ID == id
select user
).First();
if (query != null)
{
txtName.Text = query.Username;
txtEmail.Text = query.Email;
txtAddress.Text = query.PostalAddress;
ddProvice.SelectedValue = query.Province;
lblPassword.Text = query.Password;
lblDate.Text = query.DateRegistered.ToString();
}
}
}
Why does nothing happen when I load the page?
You must insert more of your code .your problem is not clear
May be in your load event of your page you forget to add
If (! IsPostback)
{
}
And may be you have reset your fields
public void MyPage_load( object sender , EventArgs e)
{
//Reset fields
}
This will fix your problem
public void MyPage_load( object sender , EventArgs e)
{
If (! IsPostback)
{
//Reset fields
}
}
Related
I'm creating dynamically controls, assigning it at the same dynamically names and ID's but when I click over a button "A" and then over the button "B" and then again to the button "A" this throw me an error
Multiple controls with the same ID were found. FindControl requires that controls have unique IDs.
this is my code and how I try to avoid the repeating I
protected void DynamicButton()
{
//BAD TOOLS INTO THE LIST AND SHOW
List.ListUsers listsArea = new List.ListUsers();
List<Data.Area> Area = listsArea.AreaList();
List<Data.Area> ListOfEquiposNoOk = Area.Where(x => x.AREA == "ENG" && x.STANDBY == 1).ToList();
List<Button> BotonesBad = new List<Button>();
var TeamBad = ListOfEquiposNoOk.Select(x => x.TEAM).Distinct().ToList();
foreach (var team in TeamBad)
{
Button newButtonBad = new Button();
if (newButtonBad.ID != newButtonBad.ID)
{
BotonesBad = Bad.Controls.OfType<Button>().ToList();
BotonesBad.Add(newButtonBad);
}
else
{
newButtonBad.CommandName = "Btn" + Convert.ToString(team);
newButtonBad.ID = "BtnB_" + Convert.ToString(team);
newButtonBad.Text = team;
newButtonBad.CommandArgument = "ENG";
newButtonBad.Click += new EventHandler(newButton_Click);
Bad.Controls.Add(newButtonBad);
newButtonBad.Click += new EventHandler(newButton_Click);
newButtonBad.CssClass = "btn-primary outline separate";
}
}
I need the ID's to fire an UpdatePanel
ADDED
public partial class Dashboard : System.Web.UI.Page
{
static bool enableGood = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DynamicButton();
}
else if(enableGood)
{
DynamicButton();
}
}
protected void DButton(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);
enableGood = true;
DynamicButton();
}
Assuming "team" is an object in this line:
newButtonBad.ID = "BtnB_" + Convert.ToString(team);
There could be your problem. ".ToString()" usually returns the type as string. So every button will get the same name (since they are all of type "team").
You could override ToString() in your team object, or use a specific team property (e.g team.ID). You could use the property like this:
newButtonBad.ID = "BtnB_" + team.ID.ToString();
Also as already pointed out in the comments, change your evaluation from
if (newButtonBad.ID != newButtonBad.ID)
to
if (team.ID != newButtonBad.ID)
That should do the trick.
I'm having some issues with posting back a RowCommand from a GridView. Not sure if my logic is correct so if somebody could point out where I am going wrong that would be great.
It seems there are lot of similar problems but none of the solutions have a default set of results in the gridview then rebinded with search results like this scenario.
The problem is when the RowCommand is fired I have the wrong result. On default load the button works correctly but if I search for customers and then use the RowCommand, the page posts back and rebinds the grid with the default customers always sending me to the wrong customer.
Page Load: Fill GridView with logged in users default clients
Search Box: Search companies entire client list and repopulate gridview
RowCommand: Send users to the customer
Postback:
if(!IsPostBack)
{
//Check if user logged in
User A_User = new User();
if(!A_User.Check_Logged_In())
{
if(A_User.Should_Redirect(System.IO.Path.GetFileName(Request.PhysicalPath)))
{
//Redirect user to login page
Response.Redirect(A_User.Login_Page());
}
}
//Modify nav buttons
HtmlGenericControl nav = (HtmlGenericControl)this.Page.Master.FindControl("UserPanel").FindControl("li_nav_address_book");
nav.Attributes["class"] = "active";
//Load logged in users customers
BindGrid(false);
}else
{
//Check for request
if(Request.Params["__EVENTTARGET"] != null)
{
//Check for search string
if(Request.Params["__EVENTTARGET"].ToString().Contains("SearchCustomers"))
{
//Load customers by search results
BindGrid(true);
}
//else
//{
// if(Request.Params["__EVENTTARGET"].ToString().Contains("btn2"))
// {
// Console.WriteLine("SENDER: ", "btn2 RowCommand");
// BindGrid(true);
// }
//}
}
}
Search Button:
protected void btn_Search_Click(object sender, EventArgs e)
{
BindGrid(true);
}
Grid Binding:
private void BindGrid(bool Search)
{
if(!Search)
{
//Load customers by rep ID
Contacts Contact_Manager = new Contacts();
gvCustomers.DataSource = null;
DataSet dsCustomers = Contact_Manager.Get_Customers_By_UserID((int)Session["User_ID"]);
DataTable tblCustomers = dsCustomers.Tables[0];
gvCustomers.DataSource = tblCustomers;
gvCustomers.DataBind();
}
else
{
//Load customers by search terms
Contacts Contact_Manager = new Contacts();
//Search by replacing spaces to do a rainbow database search as whole text instead of tags
DataSet dsCustomers = Contact_Manager.Get_Customers_By_Tags(tb_GetContacts.Text.Replace(" ", ""));
DataTable tblCustomers = dsCustomers.Tables[0];
gvCustomers.DataSource = null;
gvCustomers.DataSource = tblCustomers;
gvCustomers.DataBind();
}
}
RowCommand:
protected void gvCustomers_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if(e.CommandName == "Customer_Detail")
{
int Customer_ID = Convert.ToInt32(e.CommandArgument);
Response.Redirect("~/Customer/" + Customer_ID);
}
}
So I'm trying to update a row in a database using the text from a textbox using .net forms.
On pageload I load the value and assign it to the text property of the textbox. Next I allow the user to change the text and click a button to upload, however the value in the database is not changed.
If I change the holter.companyName value to a static string the database updates. Also if I do not assign a companyNameTB.text value at pageloads the update button works as expected.
Any ideas?
protected void Page_Load(object sender, EventArgs e)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
string companyName = holter.CompanyName;
CompanyNameTB.Text = companyName;
}
protected void Button1_Click(object sender, EventArgs e)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
holter.CompanyName = CompanyNameTB.Text;
holter.Id = 1;
db.SaveChanges();
}
It looks like the Page_Load method is overwriting the textbox when the form is submitted. Put it inside of a conditional statement in order to check to see if the request is a post back, like so:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
string companyName = holter.CompanyName;
CompanyNameTB.Text = companyName;
}
}
This should allow the textbox to be populated from the database when the page is initially loaded, but then when the user submits the form that section of code should be skipped so that the new value in the textbox doesn't get overwritten.
Do this in the Page_Load method, otherwise the value in the textBox is refreshed to the original one at any page request (so the post back request too)
if(!Page.IsPostBack)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
string companyName = holter.CompanyName;
CompanyNameTB.Text = companyName;
}
And you don't need this line is the Button1_Click method
holter.Id = 1;
In a Windows Runtime app, I load data like this:
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
then user can select an item from ListView:
private void ContentListView_ItemClick(object sender, ItemClickEventArgs e)
{
var selectedItem = e.ClickedItem as User;
if (!Frame.Navigate(typeof(FollowersPage), selectedItem.UserId))
{
throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
}
}
So it navigates forward to the same page, but shows new followers.
The problem is that when it navigates back, it loads data again and shows from the beginning of the list rather than showing the last item selected.
So how to save a List of data in NavigationHelper_SaveState and how to load it again in NavigationHelper_LoadState with last position in the list? thanks.
Here's a basic semi-tested example you can start from. You'll need to modify it to fit your exact circumstances. Some of it is adapted from here.
void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
var isp = (ItemsStackPanel)listview.ItemsPanelRoot;
int firstVisibleItem = isp.FirstVisibleIndex;
e.PageState["FirstVisibleItemIndex"] = firstVisibleItem;
// This must be serializable according to the SuspensionManager
e.PageState["Followers"] = this.DefaultViewModel["Followers"];
}
void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// Do we have saved state to restore?
if (e.PageState != null)
{
// Restore list view items
this.DefaultViewModel["Followers"] = (WhateverType)e.PageState["Followers"];
// Restore scroll offset
var index = (int)e.PageState["FirstVisibleItemIndex"];
var container = listview.ContainerFromIndex(index);
listview.ScrollIntoView(container);
}
else
{
// Load data for the first time
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
}
So I have made a log in system and now I wan't to allow the users to update their information. I thought that this code would work but it did not, here it is:
public partial class Account_Update : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MembershipUser usr = Membership.GetUser();
if (usr.IsApproved == false)
{
Response.Redirect("~/Login.aspx");
}
var p = Profile.GetProfile(usr.UserName);
/* Displays all current profile information once the page loads */
FirstName.Text = p.fName;
LastName.Text = p.lName;
Address.Text = p.Address;
Email.Text = usr.Email;
Company.Text = p.Company;
}
/* Simple button to take you to the home screen */
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("~/default.aspx");
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
MembershipUser usr = Membership.GetUser();
var p = Profile.GetProfile(usr.UserName);
/* Update all information that the user has changed */
p.fName = FirstName.Text;
p.Save();
p.lName = LastName.Text;
p.Save();
p.Address = Address.Text;
p.Save();
usr.Email = Email.Text;
Membership.UpdateUser(usr);
p.Company = Company.Text;
p.Save();
Success.Text = "User Information has been updated";
/* Redisplaying the updated user information */
FirstName.Text = p.fName;
LastName.Text = p.lName;
Address.Text = p.Address;
Email.Text = usr.Email;
Company.Text = p.Company;
}
}
The problem seems to be that whatever I change the text to in the text-box is not changing from what was originally in the text-box. So if initially the users first name was Bob and I change it to Robert when I hit the update button it does not change it to Robert. this seems like a simple fix but I'm sort of lost. So to summarize the main question is how do I update the users information to the new text that the user enters in the textbox.
put !Ispostback at the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MembershipUser usr = Membership.GetUser();
if (usr.IsApproved == false)
{
Response.Redirect("~/Login.aspx");
}
var p = Profile.GetProfile(usr.UserName);
/* Displays all current profile information once the page loads */
FirstName.Text = p.fName;
LastName.Text = p.lName;
Address.Text = p.Address;
Email.Text = usr.Email;
Company.Text = p.Company;
}
}
If you don't use it, alwyas when the info going to the server you will get the olds value.
cheers.