get data from two different pages - c#

Here is my problem. suppose by example, when I click on repeater row id then it will transfer to particular customers invoice.
But in customer invoice page, it opens only when customer Id logged in. So here two different pages accessing one page data. my code is as below.
In repeater's page.
<th>
<asp:LinkButton ID ="lnkbtnStmt" Text ="Statement" OnClick ="lnkbtnStmt_Click" runat="server"></asp:LinkButton>
<asp:HiddenField ID ="hfStmt" runat ="server" Value='<% #Eval("No")%>'/>
</th>
in repeater .cs page :
public void lnkbtnStmt_Click(object sender, EventArgs e)
{
int rptIndex = ((RepeaterItem)((LinkButton)sender).NamingContainer).ItemIndex;
string hfItem = Convert.ToString(((HiddenField)RptEmpCustInvoise.Items[rptIndex].FindControl("hfStmt")).Value);
Customer_Ledger_Entries custlist = new Customer_Ledger_Entries();
List<Customer_Ledger_Entries_Filter> cFilter = new List<Customer_Ledger_Entries_Filter>();
Customer_Ledger_Entries_Filter cfield = new Customer_Ledger_Entries_Filter();
cfield.Field = Customer_Ledger_Entries_Fields.Customer_No;
cfield.Criteria = hfItem;
cFilter.Add(cfield);
Customer_Ledger_Entries[] culist = cls.wsCustInvoice.ReadMultiple(cFilter.ToArray(), null, 1);
if (culist.Length > 0)
{
Response.Redirect("frmCustomerInvoice.aspx?Customer_No=" + hfItem);
}
}
And in another Customer page.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
GetOpeningBal();
bindCustInvoice(objSession.getSession(HttpContext.Current, "NonEmpCode"));
string empCustId = Request.QueryString["Customer_No"];
if (empCustId.Length != 0)
{
CustInvoice("empCustId");
}
GetClosingBal();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), string.Empty, "alert('" + ex.Message.ToString() + "');", true);
}
}
In this page,bindCustInvoice() method works when customer get logged in and CustInvoice("empCustId"); method works when we clicked on repeater id.
can any one give me solution?

When you clicked on Repeater Id , try to send the Page Name from Query String . and check the page name in your another customer page
Pseudo code
string PageName ="";
if(Request.QueryString["PageName"] != null)
{
PageName= Request.QueryString["PageName"];
}
if(PageName != "")
{
string empCustId = Request.QueryString["Customer_No"];
if (empCustId.Length != 0)
{
CustInvoice("empCustId");
}
}
else{
bindCustInvoice(objSession.getSession(HttpContext.Current, "NonEmpCode"));
}

Related

C# PostBack Issue

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);
}
}

Populating textBoxes with

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
}
}

Load data in a webpart lifecycle works first time, but in a popup reload it doesnt refresh

So, here is the scenarion
I have a webpart that loads some data.
I have in another place of the page a button, that opens a popup, when the user does something in that page (create action), the popup is closed and the calling page is reloaded.
When this happen, I can see in the browser that the page is reloaded, but my new data is not shown on the webpart.
I am binding the data in the create child controls, I tried to do it in the page load but then it doesnt work.
If I put my cursor on the address bar then it shows me the new data, but if I press F5 it doesnt.
public class LastCreatedJobs : WebPart
{
private GridView _lastCreatedJobsGrid;
protected override void CreateChildControls()
{
base.CreateChildControls();
CreateGridControl();
}
private void CreateGridControl()
{
try
{
_lastCreatedJobsGrid = new GridView();
_lastCreatedJobsGrid.RowDataBound += _lastCreatedJobsGrid_RowDataBound;
var bJobCode = new BoundField { DataField = "JobCode", HeaderText = "Job Code" };
bJobCode.ItemStyle.CssClass = "ms-cellstyle ms-vb2";
bJobCode.HeaderStyle.CssClass = "ms-vh2";
_lastCreatedJobsGrid.Columns.Add(bJobCode);
var jobName = new HyperLinkField
{
DataNavigateUrlFields = new[] { "JobWebsite" },
HeaderText = "Job Name",
DataTextField = "JobName"
};
jobName.ItemStyle.CssClass = "la";
jobName.HeaderStyle.CssClass = "ms-vh2";
jobName.ControlStyle.CssClass = "ms-listlink";
_lastCreatedJobsGrid.Columns.Add(jobName);
var biPowerLink = new HyperLinkField
{
Target = "_blank",
DataNavigateUrlFields = new[] { "IPowerLink" },
HeaderText = "iP Link",
Text = #"<img src='" + ResolveUrl("/_layouts/15/PWC/DMS/Images/iclient.gif") + "' /> "
};
biPowerLink.ItemStyle.CssClass = "ms-cellstyle ms-vb-icon";
biPowerLink.HeaderStyle.CssClass = "ms-vh2";
_lastCreatedJobsGrid.Columns.Add(biPowerLink);
_lastCreatedJobsGrid.CssClass = "ms-listviewtable"; //Table tag?
_lastCreatedJobsGrid.HeaderStyle.CssClass = "ms-viewheadertr ms-vhlt";
_lastCreatedJobsGrid.RowStyle.CssClass = "ms-itmHoverEnabled ms-itmhover";
_lastCreatedJobsGrid.AutoGenerateColumns = false;
_lastCreatedJobsGrid.EmptyDataText = Constants.Messages.NoJobsFound;
Controls.Add(_lastCreatedJobsGrid);
LoadGridData();
}
catch (Exception ex)
{
LoggingService.LogError(LoggingCategory.Job, ex);
}
}
private void _lastCreatedJobsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
JobInfo jobInfo = (JobInfo)e.Row.DataItem;
if (jobInfo.IsConfidential)
{
var newHyperLink = new HyperLink
{
Text = #"<img src='" + ResolveUrl("/_layouts/15/PWC/DMS/Images/spy-icon.gif") + "' /> ",
NavigateUrl = jobInfo.xlink
};
e.Row.Cells[2].Controls.RemoveAt(0);
e.Row.Cells[2].Controls.Add(newHyperLink);
}
}
}
catch (Exception ex)
{
LoggingService.LogError(LoggingCategory.Job, ex);
}
}
#region Private methods
private void LoadGridData()
{
try
{
String currentUrl = SPContext.Current.Site.Url;
var jobInfoList = new List<JobInfo>();
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (var clientSiteCollection = new SPSite(currentUrl))
{
foreach (
SPWeb web in
clientSiteCollection.AllWebs.Where(
c =>
c.AllProperties[Constants.WebProperties.General.WebTemplate] != null &&
c.AllProperties[Constants.WebProperties.General.WebTemplate].ToString() ==
Constants.WebTemplates.JobWebPropertyName).OrderByDescending(d => d.Created).Take(5)
)
{
SPList jobInfoListSp = web.Lists.TryGetList(Constants.Lists.JobInfoName);
if (jobInfoListSp != null)
{
if (jobInfoListSp.Items.Count > 0)
{
var value =
new SPFieldUrlValue(
jobInfoListSp.Items[0][Constants.FieldNames.Job.iPowerLink].ToString());
jobInfoList.Add(new JobInfo
{
JobName = jobInfoListSp.Items[0][Constants.FieldNames.Job.JobName].ToString(),
JobCode = jobInfoListSp.Items[0][Constants.FieldNames.Job.JobCode].ToString(),
xlink= value.Url,
JobWebsite = web.Url,
IsConfidential = HelperFunctions.ConvertToBoolean(jobInfoListSp.Items[0][Constants.FieldNames.Job.Confidential].ToString())
});
}
}
web.Dispose();
}
}
});
_lastCreatedJobsGrid.DataSource = jobInfoList;
_lastCreatedJobsGrid.DataBind();
}
catch (Exception ex)
{
LoggingService.LogError(LoggingCategory.Job, ex);
}
}
#endregion
}
and the page that opens the popup:
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="sp.js" OnDemand="false" Localizable="false" LoadAfterUI="true"/>
<script type="text/javascript">
//Just an override from the ClientField.js - Nothing Special to do here
function DisableClientValidateButton() {
}
function waitMessage() {
window.parent.eval("window.waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Creating Job','Working on the Job site. Please wait.',90,450);");
}
</script>
</asp:Content>
and the code behind of that page, in a button click, just the important part, after the button is clicked.
ClientScript.RegisterStartupScript(GetType(), "CloseWaitDialog",
#"<script language='javascript'>
if (window.frameElement != null) {
if (window.parent.waitDialog != null) {
window.parent.waitDialog.close();
window.frameElement.commonModalDialogClose(1, 'New call was successfully logged.');
}
}
</script>");
The trick here is that the loadgrid data has to be executed in the OnPreRender.

Problems with textboxes and page load in C#

Okay here I have some code from my project at the moment.
Basically the user goes onto the page and their current password is in the password textbox, and their avatar is selected in the droplist.
They can change their password by editing the text in the textbox and change their avatar by selecting a new one from the list. This is then written to the file where this information is kept. It writes to the file okay, but it writes what was initially in the textbox and droplist.
If i comment out these lines in the page load:
avatarDropList.SelectedValue = Session["avatar"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
It updates the file properly, but this is not what I want as I want the old password displayed there initially as well as the avatar to be selected in the dropbox.
Code below:
public partial class TuitterProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
protected void okButton_Click(object sender, ImageClickEventArgs e)
{
string username = Session["user"].ToString();
string password = Session["password"].ToString();
string newPassword = newPasswordTextbox.Text;
string newAvatar = avatarDropList.SelectedValue;
int allDataReference = -1;
//Each element in the array is a string(Username Password Avatar)
string[] allData = File.ReadAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers.txt");
for (int i = 0; i < allData.Length; i++)
{
string[] user = allData[i].Split(' ');
if (user[0] == username && user[1] == password)
{
allDataReference = i;
}
}
if (allDataReference > -1)
{
Session["avatar"] = newAvatar;
Session["password"] = newPassword;
allData[allDataReference] = username + " " + newPassword + " " + newAvatar;
File.WriteAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers3.txt", allData);
}
}
}
In the ASP.Net page event lifecycle, Page_Load is called on every request. What you are doing here is resetting the value of the TextBox every time the page loads, which will include the time that you press the button to save the profile.
All you need to do is check for the current request being a postback when you set your initial values:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
}

Poor List Item Submit Logic in Sandbox Solution

I have a web part for managing comments related to ongoing promotions. The web part is hosted in a Sandbox Solution because server access of all kinds is restricted (//sharepoint)
I have two main issues with my code.
1: Items submitted do not appear after postback, leaving user to think their comments was not saved,
2: PostBack data refires after page refresh, meaning if a user refreshes hoping to see their comments, it is re-submitted and saved.
What am I doing wrong here?
public string OfferID { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
OfferID = Context.Request.QueryString["ItemID"];
LoadOffers();
}
protected void LoadOffers()
{
if (!String.IsNullOrEmpty(OfferID))
{
PopulateOfferDetails(OfferID);
PopulateComments(OfferID);
PopulateBestPractices(OfferID);
}
else
{
OfferID = "123";
PopulateOfferDetails(OfferID);
PopulateComments(OfferID);
PopulateBestPractices(OfferID);
}
}
protected void PopulateComments(string offerID)
{
rcOiD.InnerText += " " + offerID;
List<Comment> Comments = new List<Comment>();
SPList TargetList = web.Lists.TryGetList("Offer Comments");
SPQuery query = new SPQuery();
query.RowLimit = 100;
query.Query = "<Where><Eq><FieldRef Name=\"OfferID\"/><Value Type=\"Text\">" + offerID + "</Value></Eq></Where>";
try
{
SPListItemCollection items = TargetList.GetItems(query);
if (items.Count > 0)
{
commentsCount.InnerText = items.Count.ToString();
SPUser user = web.CurrentUser;
string alias = user.Email.Substring(0, user.Email.IndexOf('#'));
string profilePicBase = "<div class=\"profilePic\" " + "style=\"background-image:url('http://who/Photos/XX.jpg');\"" + "> </div>";
foreach (SPListItem item in items)
{
Comment c = new Comment();
c.Author = ((string)item["Created By"]).CleanUserName();
c.Body = (string)item["Body"];
c.Date = String.Format("{0:MMM dd, yyyy}", (DateTime)item["Created"]);
c.ProfilePic = profilePicBase.Replace("XX", alias);
Comments.Add(c);
}
Comments.Reverse();
CommentRepeater.DataSource = Comments;
CommentRepeater.DataBind();
}
else
{
commentsCount.InnerText = "0";
}
}
catch (Exception ex)
{
}
}
protected void SubmitListItem(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
SPUser user = web.CurrentUser;
string alias = user.Email.Substring(0, user.Email.IndexOf('#'));
if (ListChoice.SelectedItem.Text == "comment")
{
SPList TargetList = web.Lists.TryGetList("Offer Comments");
SPListItem item = TargetList.Items.Add();
item["Title"] = TitleBox.Text;
item["Body"] = BodyBox.Text;
item["OfferID"] = OfferID;
item["Alias"] = alias;
item.SystemUpdate();
TargetList.Update();
}
else
{
SPList TargetList = web.Lists.TryGetList("Offer Best Practices");
SPListItem item = TargetList.Items.Add();
item["Title"] = TitleBox.Text;
item["Body"] = BodyBox.Text;
item["OfferID"] = OfferID;
item.SystemUpdate();
TargetList.Update();
}
}
}
EDIT: I can confirm this isn't a databind() issue. The item.count being pulled on postback is being rendered properly, but is still 1 item short.
I assume SubmitListItem is an event handler of an control on the page.
If that is so then as in your previous question, Page_Load is is fired before any control's event handler.
Therefore on postback your repeater is getting bound before the item addition occurs so on that load you do not get to see the new item.
To prevent this rebind the repeater after item addition.
I think you should do this only if not is page postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
OfferID = Context.Request.QueryString["ItemID"];
LoadOffers();
}
}

Categories