~/Admin/AdimHome.aspx.cs C# code
protected void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>function Open() {");
sb.Append(string.Format("window.open('Chat.aspx?rid={0}'", lstRooms.SelectedValue));
sb.Append(", 'newwindow','toolbar=no,location=no,menubar=no,width=290,height=330,resizable=no,scrollbars=no,top=350,left=980,right=500');return false;");
sb.Append("}</script>");
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
}
lblFacultyNo.Text = Session["User_Id"].ToString();
lblUserType.Text = Session["User_Type"].ToString();
pnlChat.Visible = false;
}
~/Admin/Chat.aspx.cs page C# code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User_Id"] == null)
Response.Redirect("~/Admin/AdimHome.aspx");
if (string.IsNullOrEmpty(Request.QueryString["rid"]))
Response.Redirect("~/Admin/AdminHome.aspx");
txtMsg.Attributes.Add("onkeypress", "return clickButton(event,'btn')");
if (!IsPostBack)
{
hdnRoomID.Value = Request.QueryString["rid"];
ChatRoom room = ChatEngine.GetRoom(hdnRoomID.Value);
string prevMsgs = room.JoinRoom(Session["User_Id"].ToString(), Session["User_Id"].ToString());
txt.Text = prevMsgs;
foreach (string s in room.GetRoomUsersNames())
{
lstMembers.Items.Add(new ListItem(s, s));
}
}
}
want to pass lstRooms.SelectedValue to Chat.aspx.cs page to check as per client request to differentiate their chat rooms:
sb.Append(string.Format("window.open('Chat.aspx?rid={0}'", lstRooms.SelectedValue));
onclicking the btnChat event:
<asp:Button ID="btnChat" Runat="server" CssClass="btn" OnClientClick="JavaScript:Open()" OnClick="btnChat_Click" Text="Join Room" />
The simple solution to your problem could be if you want to change your code...
//Javascript function
function Open()
{
var ddl = document.getElementbyId('<%= lstRooms.ClientID%>');
var ddlvalue = ddl.options[ddl.selectedIndex].value;
Window.Open("Chat.aspx?rid=" + ddlvalue );
}
remove all the code for JS in pageload and put this on aspx page.
let me know if it solves
Related
I'm reading a list of id numbers from a database table into a placeholder textbox but however; if I do a button click the data is removed.
protected void btnSearch_Click(object sender, EventArgs e)
{
while (myReader.Read())
{
TextBox txt = new TextBox();
txt.Text = (string)myReader["idNumber"];
txt.ID = "txt" + i;
txt.ReadOnly = true;
ContentPlaceHolder1.Controls.Add(txt);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
i++;
}
}
This is a common problem when working with dynamically added controls in web forms (especially if you're coming from a winforms background). Pages in ASP.NET Web Forms are stateless, and reconstructed on each postback. Therefore, if you add a control to a page during a server event, you'll also have to add it to the page on subsequent Page loads if you want it to appear. You can accomplish this with something similar to the following:
protected List<Control> ControlCache
{
get => (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>());
set => Session["cachedControlsForPageX"] = value;
}
/* If you can't use C# 7's expression bodied property accessors, here's the equivalent in blocks:
protected List<Control> ControlCache
{
get { return (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>()); }
set { Session["cachedControlsForPageX"] = value; }
}
*/
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
foreach (var control in ControlCache)
{
ContentPlaceHolder1.Controls.Add(control);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
}
}
else
ControlCache = null;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
while (myReader.Read())
{
TextBox txt = new TextBox();
txt.Text = (string)myReader["idNumber"];
txt.ID = "txt" + i;
txt.ReadOnly = true;
ContentPlaceHolder1.Controls.Add(txt);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
ControlCache.Add(txt);
i++;
}
}
I am quite new to ASP and I have been stuck on an issue for about a week. The issue is probably something to do with the Asp Page Life Cycle but I am unable to find how this can be resolved. The issue is that skipto(..) is never called when I click the LinkButton (that were created on first Page Load), which means the LinkButtons are not rendered.
Sample Code below:
// Code Behind
protected void Page_Load(object sender, EventArgs e)
{
loadData();
if (!Page.IsPostBack)
{
skiptof();
}
}
public void loadData() {
// Loads from database
}
public void skipto(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
if (btn != null)
{
if (btn.CommandArgument != null && btn.CommandArgument != "0")
{
int currPage = 1;
int.TryParse(btn.CommandArgument, out currPage);
skiptof(currPage);
}
}
}
public void skiptof(int currPage = 1)
{
int lastPage = // calculate from LoadData()
string pageDisabled = "";
// pages
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage)
{
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "")
{
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
pagesPageLink.Click += new EventHandler(skipto);
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
// page
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<asp:UpdatePanel runat="server" id="UpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<div id="details" runat="server"></div>
<div class="pagination text-center" id="pagination" runat="server"></div>
</ContentTemplate>
</asp:UpdatePanel>
Your problem is:
You didn't bind the data again on postback, I've modified your code a little bit, there are several problems:
in the method skipof:
public void skiptof(int currPage = 1) {
//Clear the controls here then add them again
pagination.Controls.Clear();
int lastPage = // calculate from LoadData()
string pageDisabled = "";
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage) {
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "") {
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
// you can directly assign the method to be called here, there is no need to create a new EventHandler
pagesPageLink.Click += PagesPageLink_Click;
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
You didn't bind the data again in postback, so I modified it:
Page Load:
protected void Page_Load(object sender, EventArgs e) {
//Remove the Page.IsPostBack checking
skiptof();
}
Please take note that the controls you added dynamically will be cleared and you have to add it again on postback to avoid data lost.
Then you'll be able to get the value on PagesPageLink_Click event:
The whole sample is here:
http://pastie.org/10503291
First time poster, long time lurker. I am having some trouble with my ASP.NET page, and I hope someone can help me resolve my issue.
Basically, I have a bunch of checkboxes in a gridview, and two buttons: a 'find' button, and a 'save' button. The 'find' can set the value of the checkbox, but if a user unchecks it, I want to capture that change when the user hits 'save'. Currently, it does not work.
Relevant ASPX:
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeBehind="FindTransactions.aspx.cs" Inherits="Basic.FindTransactions" MasterPageFile="~/Trans.Master" %>
Relevant Code Behind here:
Page:
public partial class FindTransactions : System.Web.UI.Page
{
GridView _gridview = new GridView() { ID = "_gridView" };
DataTable _datatable = new DataTable();
Int32 _buyerID = new Int32();
protected void Page_Load(object sender, EventArgs e)
{
}
"Find" button:
protected void Find_Click(object sender, EventArgs e)
{
//truncated
_datatable.Rows.Add(
//filled with other data from a custom object.
);
ViewState["_datatable"] = _datatable;
ViewState["_buyerID"] = _buyerID;
BuildGridView((DataTable)ViewState["_datatable"],(Int32)ViewState["buyerID"]);
}
BuildGridView function:
protected void BuildGridView(DataTable d, Int32 b)
{
_gridview.DataKeyNames = new String[] {"Transaction ID"};
_gridview.AutoGenerateColumns = false;
_gridview.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
for(Int32 i = 0; i < d.Columns.Count; i++)
{
Boundfield boundfield = new BoundField();
boundfield.DataField = d.Columns[i].ColumnName.ToString();
boundfield.HeaderText = d.Columns[i].ColumnName.ToString();
_gridview.Columns.Add(boundfield);
}
_gridview.DataSource = d;
_gridview.DataBind();
//truncated
Panel1.Controls.Add(_gridview);
}
Row Bound Event handler:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String controlID = "checkBox";
CheckBox c = new CheckBox() { ID = controlID};
c.Enabled = true;
Boolean success;
Boolean v;
success = Boolean.TryParse(e.Row.Cells[8].Text, out v);
e.Row.Cells[8].Controls.Add(c);
if (success)
{
c.Checked = v;
if (c.Checked)
{
//Will uncomment once other things work
//e.Row.Visible = false;
}
}
else
{
c.Checked = false;
}
}
}
All of that works. Here is where it starts to break down:
"Save" button:
protected void Save_Click(object sender, EventArgs e)
{
//Both for troubleshooting and both return 0. (Expected for datatable)
Label1.Text = _gridview.Rows.Count.ToString();
Label2.Text = _datatable.Rows.Count.ToString();
/*truncated
*/
if (grid.Rows.Count == 0)
{
BuildGridView((DataTable)ViewState["infoTable"], (Int32)ViewState["guestID"]);
}
foreach (GridViewRow r in grid.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)r.FindControl("checkBox");
if (cb != null && cb.Checked)
{
//This never seems to modify the label.
//Will put code to modify database here.
Label2.Text += "Hi " + r.RowIndex.ToString();
}
}
}
}
After I hit the save button, PostBack occurs and GridView is empty (Rows.Count is 0). ViewState appears to be lost before I get a chance to loop through the GridView rows to determine the checkbox values.
At the end of it all, I just want to capture the status of those checkboxes, changed by user interaction or not, by hitting the 'Save' button.
I found some other articles, but a lot of them haven't worked when I tried implementing the various fixes.
This one seems to be the closest that describes my issue, and the code is structured similarly, but I don't quite understand how to implement the fix: GridView doesn't remember state between postbacks
[New simplified code to illustrate problem:]
namespace GridViewIssue
{
public partial class GridViewNoMaster : System.Web.UI.Page
{
GridView _gridView = new GridView() { ID = "_gridView" };
DataTable _dataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Find_Click(object sender, EventArgs e)
{
BuildDataTable();
List<String> list = new List<String>();
list.Add("1");
list.Add("User");
list.Add("10/12/2014");
foreach (String s in list)
{
_dataTable.Rows.Add(
list[0],
list[1],
list[2]
);
}
BuildGridView();
//Feedback.Text = _gridView.Rows.Count.ToString();
}
protected void Save_Click(object sender, EventArgs e)
{
Feedback.Text = "Save Clicked, PostBack: " + IsPostBack + ", GridView Row Count: " + _gridView.Rows.Count + ", GridView ViewState: " + _gridView.EnableViewState;
foreach (GridViewRow r in _gridView.Rows)
{
if(r.RowType == DataControlRowType.DataRow)
{
Feedback.Text = "In DataRow type" + _gridView.Rows.Count;
}
}
}
protected void BuildDataTable()
{
_dataTable.Columns.Add("Transaction ID", typeof(String));
_dataTable.Columns.Add("Name", typeof(String));
_dataTable.Columns.Add("Date", typeof(String));
}
protected void BuildGridView()
{
for (Int32 i = 0; i < _dataTable.Columns.Count; i++)
{
BoundField b = new BoundField();
b.DataField = _dataTable.Columns[i].ColumnName.ToString();
b.HeaderText = _dataTable.Columns[i].ColumnName.ToString();
_gridView.Columns.Add(b);
}
_gridView.DataKeyNames = new String[] { "Transaction ID" };
_gridView.AutoGenerateColumns = false;
_gridView.DataSource = _dataTable;
_gridView.DataBind();
Panel1.Controls.Add(_gridView);
}
}
}
I have a somewhat complicated setup for an ASP.NET TextBox. It is inside of a user control that's inside a repeater that's inside a repeater.
I am able to load text into the TextBox and also get TextChanged to fire when text is changed to anything EXCEPT FOR blank/empty. The event doesn't fire when the user clears out the TextBox.
Does anyone know why ASP.NET might discriminate between text and blank?
I made a simplified version of my problem to separate it from possible other factors. I get the same results.
Below is my aspx markup:
<div>
<asp:Repeater runat="server" ID="rptRepeat" EnableViewState="False">
<ItemTemplate>
<asp:repeater runat="server" ID="rptChild" EnableViewState="False">
<ItemTemplate>
<uc:Things runat="server" ID="ucChild"></uc:Things>
</ItemTemplate>
</asp:repeater>
</ItemTemplate>
</asp:Repeater>
</div>
<asp:Button runat="server" ID="btnBtn" Text="click"/>
Below is my user control markup
<asp:TextBox runat="server" ID="txtText"></asp:TextBox>
Below is the aspx code behind
private List<List<TestObj>> data = null;
protected void Page_Init(object sender, EventArgs e)
{
this.rptRepeat.ItemCreated += rptRepeat_ItemCreated;
this.rptRepeat.ItemDataBound += rptRepeat_ItemDataBound;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Session["data"] = data = new List<List<TestObj>>();
for (var x = 0; x < 5; x++)
{
data.Add(new List<TestObj>());
for (var y = 0; y < 5; y++)
{
data[0].Add(new TestObj
{
Text = x + "_" + y
});
}
}
}
else
{
data = (List<List<TestObj>>)Session["data"];
}
this.rptRepeat.DataSource = data;
this.rptRepeat.DataBind();
}
void rptRepeat_ItemCreated(object sender, RepeaterItemEventArgs e)
{
var rptChild = (Repeater)e.Item.FindControl("rptChild");
rptChild.ItemDataBound += rptChild_ItemDataBound;
}
void rptRepeat_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var rptChild = (Repeater)e.Item.FindControl("rptChild");
var rowObj = (List<TestObj>)e.Item.DataItem;
rptChild.DataSource = rowObj;
rptChild.DataBind();
}
void rptChild_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var ucChild = (WebUserControl1)e.Item.FindControl("ucChild");
var rowObj = (TestObj)e.Item.DataItem;
ucChild.data = rowObj;
}
Below is the user control code behind
public TestObj data = null;
protected void Page_Init(object sender, EventArgs e)
{
this.txtText.TextChanged += txtText_TextChanged;
}
protected void Page_PreRender(object sender, EventArgs e)
{
this.txtText.Text = data.Text;
}
void txtText_TextChanged(object sender, EventArgs e)
{
data.Text = this.txtText.Text;
}
You can download the whole project at https://www.dropbox.com/s/p6zkqqsw71fvuyw/textchangetest.zip?dl=0 if you want to try tinkering with stuff to get me an answer.
The databinding of the repeater was intentionally put in Page_Load because otherwise child controls' events don't fire.
I am getting an error "Object Reference is not set to an Instance of an object" in the ContentPage of my MasterPage Facebook Application.
Site.master.cs
public FacebookSession CurrentSession
{
get { return (new CanvasAuthorizer()).Session; }
}
protected void Page_Load(object sender, EventArgs e)
{
var auth = new CanvasAuthorizer { Perms = "email,read_stream,publish_stream,offline_access,user_about_me" };
if (auth.Authorize())
{
ShowFacebookContent();
}
}
private void ShowFacebookContent()
{
var fb = new FacebookClient(this.CurrentSession.AccessToken);
dynamic myInfo = fb.Get("me");
lblName.Text = myInfo.name;
imgProfile.ImageUrl = "https://graph.facebook.com/" + myInfo.id + "/picture";
lblBirthday.Text = myInfo.birthday;
pnlHello.Visible = true;
}
This master Page works OK & displays UserName & ProfilePic.
Default.aspx.cs
SiteMaster myMasterPage;
protected void Page_Load(object sender, EventArgs e)
{
myMasterPage = this.Page.Master as SiteMaster;
}
public void LinkButton1_Click(object sender, EventArgs e)
{
var fb = new FacebookClient(this.myMasterPage.CurrentSession.AccessToken);
dynamic feedparameters = new ExpandoObject();
feedparameters.message = (message_txt.Text == null ? " " : message_txt.Text);
feedparameters.user_message_prompt = "userPrompt";
/*Dictionary<string, object> feedparameters = new Dictionary<string, object>();
feedparameters.Add("message", "Testing Application");
feedparameters.Add("user_message_prompt", "Post To Your Wall");
feedparameters.Add("display", "iframe");*/
dynamic result = fb.Post("me/feed", feedparameters);
}
Even this Page Loads OK but Problem comes when I try to Post using LinkButton.
Following Line gives the error.
var fb = new FacebookClient(this.myMasterPage.CurrentSession.AccessToken);
On LinkButton Click Object Reference is not set to an Instance of an object...
I will really appreciate some help.
Wel finally found what was the problem. Needed to add a hidden field.
<input type="hidden" name="signed_request" value="<%: Request.Params["signed_request"]%>"/>
I think this is neither mentioned any where in the documentation nor in the Provided Samples.