Persistent dynamic control in ASP.Net - c#

<asp:Button onclick="Some_event" Text="Add TextBox" ID="id1" runat="server" />
//once clicked:
<asp:TextBox ID="txt1" ......></asp:TextBox>
//when clicked again:
<asp:TextBox ID="txt1" ......></asp:TextBox>
<asp:TextBox ID="txt2" ......></asp:TextBox>
//and so on...
Is there a way to create dynamic controls which will persist even after the postback? In other words, when the user clicks on the button, a new textbox will be generated and when clicks again the first one will remain while a second one will be generated. How can I do this using asp.net ? I know that if I can create the controls in the page_init event then they will persist but I dont know if it possible to handle a button click before the page_init occurs, therefore there must be another way.

Yes, this is possible. One way to do this using purely ASP.NET (which seems like what you're asking for) would be to keep a count of the TextBox controls that you have added (storing that value in the ViewState) and recreate the TextBox controls in the Page_Load event. Of course, nowadays most people would probably use Javascript or jQuery to handle this task client side, but I put together a quick example to demonstrate how it works with postbacks:
Front page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicControls.aspx.cs" Inherits="MyAspnetApp.DynamicControls" EnableViewState="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
<asp:Button ID="btnWriteValues" runat="server" Text="Write" OnClick="btnWriteValues_Click" />
<asp:PlaceHolder ID="phControls" runat="server" />
</div>
</form>
</body>
</html>
Code behind:
using System;
using System.Web.UI.WebControls;
namespace MyAspnetApp
{
public partial class DynamicControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Recreate textbox controls
if(Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int) count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void AddTextBox(int index)
{
var txt = new TextBox {ID = string.Concat("txtDynamic", index)};
txt.Style.Add("display", "block");
phControls.Controls.Add(txt);
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void btnWriteValues_Click(object sender, EventArgs e)
{
foreach(var control in phControls.Controls)
{
var textBox = control as TextBox;
if (textBox == null) continue;
Response.Write(string.Concat(textBox.Text, "<br />"));
}
}
}
}
Since you are recreating the controls on each postback, the values entered into the textboxes will be persisted across each postback. I added btnWriteValues_Click to quickly demonstrate how to read the values out of the textboxes.
EDIT
I updated the example to add a Panel containing a TextBox and a Remove Button. The trick here is that the Remove button does not delete the container Panel, it merely makes it not Visible. This is done so that all of the control IDs remain the same, so the data entered stays with each TextBox. If we were to remove the TextBox entirely, the data after the TextBox that was removed would shift down one TextBox on the next postback (just to explain this a little more clearly, if we have txt1, txt2 and txt3, and we remove txt2, on the next postback we'll create two textboxes, txt1 and txt2, and the value that was in txt3 would be lost).
public partial class DynamicControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void btnWriteValues_Click(object sender, EventArgs e)
{
foreach(var control in phControls.Controls)
{
var panel = control as Panel;
if (panel == null || !panel.Visible) continue;
foreach (var control2 in panel.Controls)
{
var textBox = control2 as TextBox;
if (textBox == null) continue;
Response.Write(string.Concat(textBox.Text, "<br />"));
}
}
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int) count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void AddTextBox(int index)
{
var panel = new Panel();
panel.Controls.Add(new TextBox {ID = string.Concat("txtDynamic", index)});
var btn = new Button { Text="Remove" };
btn.Click += btnRemove_Click;
panel.Controls.Add(btn);
phControls.Controls.Add(panel);
}
private void btnRemove_Click(object sender, EventArgs e)
{
var btnRemove = sender as Button;
if (btnRemove == null) return;
btnRemove.Parent.Visible = false;
}
}

I read an article by Scott Mitchell that explains that ViewState only persists changed control state across post-back, and not the actual controls themselves. I did not have your exact scenario, but a project I was working on required dynamically added user controls and I had to add them on every postback. In that case, it is still useful to create them in Init so that they can retain their state. Here is the link: Understanding ASP.NET View State. Check section “View State and Dynamically Added Controls”.
You may have to keep track of all the controls that you are adding (in session state for example) and re-create them on post back. I just did a small test where I keep a List<string> of all the Textbox ids in Session. On postback, I recreate all the textboxes.

Related

ASP.NET Session State & Postback problems

I have a problem that I believe is a session state issue, but I'm at a loss to figure out what's wrong. I have a sample project to illustrate the problem. (Code below) I have 2 buttons. Each populates a List with some unique data and then uses that data to add a row to a table. The row contains text boxes so that the user can edit the data. (For my sample, there's no update button to persist the data.) To reproduce the problem in VS2010, create a new "ASP.NET Web Application" project and copy/paste the aspx code and the c# code-behind into Default.aspx, then run the application.
Press the DataSet 1 button and the grid should populate with 1 row.
Edit the data in one of the text boxes and tab off of the text box. (The newly entered text should remian, and the font should be blue. This is what I want to happen.)
Now click either of the DataSet buttons to reset the List and refresh the table.
Edit the data in one of the text boxes and tab off the text box. (Immediately, the text in the box refreshes back to its original value. This only happens once, though. If you edit either text box now, it will work normally.)
This is repeatable... the first edit after pressing the DataSet buttons a 2nd, 3rd, etc. time gets reset back to the original value. And I can't figure out why.
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DebugPostbackIssue._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
Populate the table with DataSet #1:<asp:Button runat="server" ID="btnDS1" Text="Dataset 1" OnClick="btnDS1_Click" />
</p>
<p>
Populate the table with DataSet #2:<asp:Button runat="server" ID="btnDS2" Text="Dataset 2" OnClick="btnDS2_Click" />
</p>
<p>
<asp:Table runat="server" ID="tblData">
<asp:TableHeaderRow runat="server" ID="thrData">
<asp:TableHeaderCell Scope="Column" Text="Column 1"></asp:TableHeaderCell>
<asp:TableHeaderCell Scope="Column" Text="Column 2"></asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
</p>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DebugPostbackIssue
{
public partial class _Default : System.Web.UI.Page
{
private List<string> _MyData = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
LoadSessionData();
GenerateGrid(false);
}
protected void btnDS1_Click(object sender, EventArgs e)
{
_MyData = new List<string>();
_MyData.Add("111");
_MyData.Add("aaa");
SaveSessionData();
GenerateGrid(true);
}
protected void btnDS2_Click(object sender, EventArgs e)
{
_MyData = new List<string>();
_MyData.Add("222");
_MyData.Add("bbb");
SaveSessionData();
GenerateGrid(true);
}
private void SaveSessionData()
{
Session["MyData"] = _MyData;
}
private void LoadSessionData()
{
if (Session["MyData"] != null)
_MyData = (List<string>)Session["MyData"];
else
_MyData = new List<string>();
}
private void GenerateGrid(bool ClearData)
{
if (ClearData)
while (tblData.Rows.Count > 1)
tblData.Rows.Remove(tblData.Rows[tblData.Rows.Count - 1]);
TableRow tr = new TableRow();
foreach (string s in _MyData)
{
TableCell tc = new TableCell();
TextBox txtBox = new TextBox();
txtBox.Text = s;
txtBox.Attributes.Add("OriginalValue", s);
txtBox.TextChanged += new EventHandler(txtBox_TextChanged);
txtBox.AutoPostBack = true;
tc.Controls.Add(txtBox);
tr.Cells.Add(tc);
}
if (tr.Cells.Count > 0)
tblData.Rows.Add(tr);
}
void txtBox_TextChanged(object sender, EventArgs e)
{
TextBox Sender = (TextBox)sender;
if (Sender.Text == Sender.Attributes["OriginalValue"])
Sender.ForeColor = System.Drawing.Color.Black;
else
Sender.ForeColor = System.Drawing.Color.Blue;
}
}
}
Hi I took some time off of my work to compile your code, and I figured it out, just change your textbox change to the following :
void txtBox_TextChanged(object sender, EventArgs e)
{
TextBox Sender = (TextBox)sender;
if (Sender.Text == Sender.Attributes["OriginalValue"])
Sender.ForeColor = System.Drawing.Color.Black;
else
{
Sender.ForeColor = System.Drawing.Color.Blue;
if (Session["MyData"] != null)
{
List<string> _ss = (List<string>)Session["MyData"];
//_ss.Find(a => a == Sender.Attributes["OriginalValue"]);
_ss.Remove(Sender.Attributes["OriginalValue"]);
_ss.Add(Sender.Text);
}
}
}
ur welcome!
Try creating a datatable. I would, on "event" copy your asp table content to a datatable, then when you get the servers response add that to the datatable. Then copy the datatable back to your asp table, and repeat... Datatables can be used like variables.
Or try using a cookie.
Try changing...
protected void Page_Init(object sender, EventArgs e)
{
LoadSessionData();
GenerateGrid(false);
}
To...
protected override void OnLoadComplete(EventArgs e)
{
LoadSessionData();
GenerateGrid(false);
}
Based on your description I believe that your value is getting reset because of how the page life cycle works in ASP.NET & that is the page_init is getting called before your event due to ASP.NET quirkiness. Above code is how I work around it, I'm sure there's other ways too.
Okay, I have it working, now. Wizpert's answer pointed me in the right direction... Upon discovering that the TextChanged event did not fire during the times when the value was erroneously being reset to the original value, it occurred to me that during the Click events I was calling GenerateGrid(true). This forced the removal of the existing rows and the addition of new rows. (Removing & adding the dynamic controls at that point in the life cycle must be interfering with the TextChange event handler.) Since the Click event fires after Page Init and after Page Load, the state values were already written to the text boxes and I was overwriting them. But the 2nd text box edit did not force GenerateGrid(true) to be called so the state values were not overwritten any more.
If this sounds confusing, I apologize. I'm still wrapping my head around this. But suffice to say that I had to change my GenerateGrid method to reuse any existing rows and not delete them. (If they don't exist, like when GenerateGrid is called from Page Init, then they are added.) So this was a page lifecycle issue after all.
Thank you.

C# - find page control in the page

I has aspx page as below. I want to find the control in the page using code behind.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
{
string name;
foreach (Control ctrl in Controls)
{
if (ctrl.Controls.Count > 0)
{
name = ctrl.GetType().Name;
}
}
}
I can't get the button in the loop. Even i add textbox it also can't get. Any one has idea what wrong? Please help.
Try This.
protected void Button1_Click(object sender, EventArgs e)
{
string Name = "";
string Type = "";
string Id = "";
foreach (Control ctr in form1.Controls)
{
Name = ctr.GetType().Name;
Type = ctr.GetType().ToString(); ;
Id = ctr.ID; // If its server control
}
}
ASP.Net renders the page Hierarchically. This means that only top level controls are rendered directly. If any of these top level control contains some child controls, these top level control provide their own Controls property.
For example, in your case Form is the top level control that contains child controls such as Button. So on your button click call a method recursively.
protected void Button1_Click(object sender, EventArgs e)
{
DisplayControl(Page.Controls);
}
private void DisplayControls(ControlCollection controls)
{
foreach (Control ctrl in controls)
{
Response.Write(ctrl.GetType().ToString() + " , ID::" + ctrl.ID + "<br />");
// check for child OR better to say nested controls
if (ctrl.Controls != null)
DisplayControls(ctrl.Controls);
}
}
This is because you're not getting all the controls in your page. You'd have to get controls recursively. Here's an extension method:
public static class ControlExtensions
{
public static List<Control> GetChildrenRecursive(this Control control)
{
var result = new List<Control>();
foreach (Control childControl in control.Controls)
{
result.Add(childControl);
if (childControl.Controls.Count > 0)
{
result.AddRange(GetChildrenRecursive(childControl));
}
}
return result;
}
}
Now you can rewrite your code as follows:
foreach (Control ctrl in this.Page.GetChildrenRecursive())
{
// Your button element is accessible now.
}

Retrieve value from dynamically created control

I have two dropdown lists, one for days and one for nights. I also have two buttons, one button creates dynamic textboxes where the customer can enter what they want to do in day time and in place where they want to spend night.
e.g., if one customer selects 4 days and 4 nights, a textbox will be created on press of the first button.
When the user clicks the second button, I want to store all those values in database, but I noticed that on postback the fields are lost and I have no data to store.
How do I get the values from the controls created at runtime upon postback?
Here is how you can do it:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["testTextBox"] != null)
{
Request.Form[Session["testTextBox"].ToString()].ToString()
}
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox t = new TextBox { ID = "testTextBox" };
this.Form.Controls.Add(t);
Session["testTextBox"] = t.UniqueID;
}
If you are adding the textbox via a client side call you don't need to store the UniqueID. Button1_Click is the postback method for your button for example.
Even though adding controls in code behind is "fine", it can lead to trouble later. It also isn't very good when editing your view, and you have to change a bunch of code in code-behind. A solution is to use a data bound control, for instance a Repeater control. That way, you can design your view in your aspx file, and leave the coding to the cs-file. It also takes care of holding information when using postbacks, since it's already setup to use the viewstate of the controls, meaning you don't have to do it.
So, using a repeater, your aspx can look something like this.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="RepeaterPage.aspx.cs" Inherits="ASPTest.RepeaterPage" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h1>Test</h1>
<div>
<asp:Button Text="Add textbox" ID="Button1" OnClick="OnAddItem" runat="server" />
<asp:Button Text="Read values" ID="Button2" OnClick="OnReadValues" runat="server" />
</div>
<div>
<asp:Label ID="values" runat="server"></asp:Label>
</div>
<asp:Repeater ID="listofvalues" runat="server">
<ItemTemplate>
<asp:HiddenField ID="ID" Value='<%# Eval("ID") %>' runat="server" />
<asp:TextBox ID="ValueBox" Text='<%# Server.HtmlEncode((string)Eval("Value")) %>' runat="server" />
</ItemTemplate>
</asp:Repeater>
</asp:Content>
Notice that I'm using a master page, so the Content control only links to some ContentPlaceHolder in the master page. In this aspx page, you'll see that the itemtemplate in the repeater control sets up all the design needed to show the values. We'll see how this pans out in the code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASPTest
{
public partial class RepeaterPage : Page
{
private List<Item> cache;
public List<Item> ItemValues
{
get
{
if (cache != null)
{
return cache;
}
// load values from database for instance
cache = Session["values"] as List<Item>;
if (cache != null)
{
return cache;
}
Session["values"] = cache = new List<Item>();
return cache;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
listofvalues.DataBinding += bindValues;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsPostBack)
{
DataBind();
}
}
protected void OnAddItem(object sender, EventArgs e)
{
ItemValues.Add(new Item("some value"));
DataBind();
}
protected void OnReadValues(object sender, EventArgs e)
{
foreach (RepeaterItem repeateritem in listofvalues.Items)
{
TextBox box = (TextBox)repeateritem.FindControl("ValueBox");
HiddenField idfield = (HiddenField)repeateritem.FindControl("ID");
Item item = findItem(idfield.Value);
item.Value = box.Text;
}
StringBuilder builder = new StringBuilder();
foreach (Item item in ItemValues)
{
builder.Append(item.Value).Append(";");
}
values.Text = builder.ToString();
}
private Item findItem(string idvalue)
{
Guid guid = new Guid(idvalue);
foreach (Item item in ItemValues)
{
if (item.ID == guid)
{
return item;
}
}
return null;
}
private void bindValues(object sender, EventArgs e)
{
listofvalues.DataSource = ItemValues;
}
}
public class Item
{
private readonly Guid id;
private string value;
public Item(string value)
{
this.value = value;
id = Guid.NewGuid();
}
public Guid ID
{
get { return id; }
}
public string Value
{
get { return value; }
set { this.value = value; }
}
}
}
Sorry about the long code example, but I wanted it to be thorough. You'll see that I introduced a list of Items, in the ItemValues property. You can load the values from wherever you want. I used the Session collection, but you can load from database or some other place if you want.
Also, notice how the only thing we know about the view is the control type and control ID. There's no code describing how controls should be added or styled, we leave that to the aspx page. This creates an easy separation of concerns between the two.
Instead, when we want to add a TextBox, we instead add a new instance of the data item, an instance of the Item class. In the OnReadValues method we can update the data items values bound to the repeater, and then use either the values from the controls or the values from the items in our data list.
I hope this illustrates how one can use ASP.NET to create dynamic pages, without creating the controls in code behind, because it's not really needed if you do it like this.

asp.net c# is checkbox checked?

How do I determine if the checkbox is checked or not checked?
Very perplexed why this is not working - it is so simple!
On my web form:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" Text="Save" CssClass="publish" />
Code behind which runs in the click event for my save button:
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
When debugging it never steps into the If statement when I have the checkbox checked in the browser. Ideas?!
I think there maybe some other code affecting this as follows...
In Page_load I have the following:
PublishButton.Click += new EventHandler(PublishButton_Click);
if (newsItem.IsDraft == 1)
{
DraftCheckBox.Checked = true;
}
else
{
DraftCheckBox.Checked = false;
}
newsItem is my data object and I need to set the checkbox checked status accordingly.
When the save button is hit I need to update the IsDraft property based on the checked status of the checkbox:
void PublishButton_Click(object sender, EventArgs e)
{
if (IsValid)
{
newsItem.Title = TitleTextBox.Text.Trim();
newsItem.Content = ContentTextBox.Text.Trim();
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
else
{
newsItem.IsDraft = 0;
}
dataContext.SubmitChanges();
}
}
So, isDraft = 1 should equal checkbox checked, otherwise checkbox should be un-checked. Currently, it is not showing this.
Specify event for Button Click
<asp:Button ID="PublishButton" runat="server" Text="Save" onclick="PublishButton_Click" />
What i can see you have not got a OnClick on your button. So like this:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" OnClick="PublishButton_Click"
Text="Save" CssClass="publish" />
And then the function should work like it is:
protected void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
Please replace code as following code..
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked==True)
{
newsItem.IsDraft = 1;
}
}
Try adding onclick="PublishButton_Click" in the button field on the form. And I don't know if it makes a difference, but generated event handlers are protected void.
For me the best solution in the end has been to create 2 separate pages: 1 for editing a news articles & 1 for a new news article. So Ill never then be in the position of a new news data object being created when the page reloads.
Both page return to the article index list page when the save button is pressed and that seems to work with being able to save the state of the draft checkbox and then show the state on the edit page.
The checkbox.checked isn't used in the context you want it to (this is a boolean that if true, will make the checkbox look checked).
What you could do is to use instead a checkboxlist. Then you could do the following:
foreach(Listitem li in CheckBoxList1.Items)
{
if (li.Selected)
{
NewsItem.Isdraft = 1;
}
}

C#/.Net 2.0: Problem with the Repeater control and Checkboxes when inside a User Control!

I have a repeater control with a check box, if I check the box then my delete functionality will delete an item in the underlying table.
When I test the delete functionality on an aspx page with a code behind page, everything works fine. Hooray!
However, when I take the repeater and put it into a User Control, the delete functionality thinks that my repeater control has no items.
Code as below, I've tried to strip out the unnecessary code. I asked this question on the asp.net forums but no-one responded!
asxc:
<%# Control AutoEventWireup="true" Inherits="Moto.Web.UI.UserControls.Messages.MessageListForm" Language="C#" %>
<asp:button id="btnDelete" runat="server" text="Delete" OnClick="btnDelete_Click" ></asp:button>
<asp:Repeater ID="RepeaterMessageList" runat="server" EnableViewState="true" >
<ItemTemplate >
<div class="messageContainer item" >
<div class="messageListLeft">
<div class="messageList">
<asp:Image ID="imgUser" runat="server" CssClass="" />
<asp:CheckBox ID="chkDeleteMe" runat="server" Text="test" />
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Code file:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;
using System.IO;
namespace Moto.Web.UI.UserControls.Messages
{
public class MessageListForm : Moto.Web.UI.UserControls.UserControl//System.Web.UI.UserControl
{
private string userGUID;
private MembershipUser MembershipUser;
private Moto.Business.UserComponent userComponent;
private Moto.Business.User user;
private Button cmdPrev;
private Button cmdNext;
private Button cmdNewest;
private Button cmdOldest;
private Label lblCurrentPage;
private Label lblMessage;
private HyperLink hypPageRedirect;
private Repeater RepeaterMessageList;
private MessageView DisplayMessages = MessageView.Inbox;//default setting
private Button btnDelete;
private Label lblConfirmDelete;
protected Button btnConfirmDelete;
protected Button btnCancelDelete;
enum MessageView
{
Inbox, //0
Sent //1
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.InitializePage();
}
protected void InitializePage()
{
this.cmdNext = (Button)FindControl("cmdNext");
this.cmdPrev = (Button)FindControl("cmdPrev");
this.cmdOldest = (Button)FindControl("cmdOldest");
this.cmdNewest = (Button)FindControl("cmdNewest");
this.lblCurrentPage = (Label)FindControl("lblCurrentPage");
// this.RepeaterMessageList = (Repeater)FindControl("RepeaterMessageList");
this.RepeaterMessageList = (Repeater)FindControlRecursive(this, "RepeaterMessageList");
this.hypPageRedirect = (HyperLink)FindControl("hypPageRedirect");
this.lblMessage = (Label)FindControl("lblMessage");
//delete functionality
this.btnDelete = (Button)FindControl("btnDelete");
this.lblConfirmDelete = (Label)FindControl("lblConfirmDelete");
this.btnConfirmDelete = (Button)FindControl("btnConfirmDelete");
this.btnCancelDelete = (Button)FindControl("btnCancelDelete");
//where are we coming from - are we the Logged in user or just a voyeur?
if (Page.User.Identity.IsAuthenticated)
{
this.userComponent = new Moto.Business.UserComponent();
this.MembershipUser = Membership.GetUser();//user logged in
this.userGUID = this.MembershipUser.ProviderUserKey.ToString();//signed in user
this.user = this.userComponent.GetByUserGUID(this.userGUID);
}
else
{
Response.Redirect("~/default.aspx");
}
if (null != this.Page.Request.QueryString["viewing"])
{
//reset the enum value
DisplayMessages = this.Page.Request.QueryString["viewing"].ToLower() == "sent" ? MessageView.Sent : MessageView.Inbox;
CurrentPage = 0;//if it's a redirect then reset the Current Page
}
}
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ItemsGet();//on post back we'll call it elsewhere
}
switch (DisplayMessages)
{
case MessageView.Sent:
this.hypPageRedirect.Text += "Inbox";
this.hypPageRedirect.NavigateUrl += "?viewing=Inbox";
break;
case MessageView.Inbox:
this.hypPageRedirect.Text += "Sent Items";
this.hypPageRedirect.NavigateUrl += "?viewing=Sent";
break;
}
}
protected void cmdPrev_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage -= 1;
// Reload control
ItemsGet();
}
protected void cmdNext_Click(object sender, EventArgs e)
{
// Set viewstate variable to the next page
CurrentPage += 1;
// Reload control
ItemsGet();
}
protected void cmdNewest_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage = 0;
// Reload control
ItemsGet();
}
protected void cmdOldest_Click(object sender, EventArgs e)
{
}
public void RepeaterMessageList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Are we vieing the Inbox or Sent items?
if (DisplayMessages == MessageView.Inbox)
{
.........Do stuff
}
else
{
.........Do stuff
}
}
}
private void ItemsGet()
{
// this.RepeaterMessageList = (Repeater)FindControl("RepeaterMessageList");
this.RepeaterMessageList.ItemDataBound += new RepeaterItemEventHandler(RepeaterMessageList_ItemDataBound);
// Populate the repeater control with the Items DataSet
PagedDataSource objPds = new PagedDataSource();
if (DisplayMessages == MessageView.Inbox)//which table are we getting data from?
{
List<Moto.Business.MessageReceived> messages;
Moto.Business.MessageReceivedComponent messageComponent =
new Moto.Business.MessageReceivedComponent();
messages = messageComponent.GetByReceiverGUID(this.user.UserGUID);
objPds.DataSource = messages;
}
else
{
List<Moto.Business.MessageSent> messages;
Moto.Business.MessageSentComponent messageComponent =
new Moto.Business.MessageSentComponent();
messages = messageComponent.GetBySenderGUID(this.user.UserGUID);
objPds.DataSource = messages; //Items.Tables[0].DefaultView;
}
// Indicate that the data should be paged
objPds.AllowPaging = true;
// Set the number of items you wish to display per page
objPds.PageSize = 25;
// Set the PagedDataSource's current page
objPds.CurrentPageIndex = CurrentPage;
this.lblCurrentPage.Text = "Page " + (CurrentPage + 1).ToString() + " of "
+ objPds.PageCount.ToString();
// Disable Prev or Next buttons if necessary
this.cmdPrev.Enabled = !objPds.IsFirstPage;
this.cmdNext.Enabled = !objPds.IsLastPage;
this.cmdOldest.Enabled = !objPds.IsLastPage;
this.cmdNewest.Enabled = !objPds.IsFirstPage;
this.RepeaterMessageList.DataSource = objPds;
this.RepeaterMessageList.DataBind();
}
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_messagesCurrentPage"];
if (o == null)
return 0; // default page index of 0
else
return (int)o;
}
set
{
this.ViewState["_messagesCurrentPage"] = value;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in this.RepeaterMessageList.Items)
{
CheckBox chkDeleteMe = item.FindControl("chkDeleteMe") as CheckBox;
TextBox test = item.FindControl("test") as TextBox;
if (chkDeleteMe.Checked)
{
if (DisplayMessages == MessageView.Inbox)//which table are we getting data from?
{
.........Do stuff
}
else
{
.........Do stuff
}
}
}
// Reload control
ItemsGet();
}
protected Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
}
Any help greatly appreciated!
I think the problem is that when the delete button is clicked the Page_Load is fired again and since its a postback it does not execute the ItemsGet method and hence the repeater does not have the data.
Try putting the ItemsGet method call in the OnPreRender event instead of Page_Load.
Jomit
The Delete event fires but in the fornext...loop the repeater thinks it has no items.
After looping it then calls the ItemsGet() Method which returns all data from the table.
So it binds to the repeater and displays all the items correctly but when repeating through the list of items on postback nothing is found?
Is the delete event definately being fired? What is visible after you have hit the delete button? (e.g. is the table empty or does it still display all the items)
Update:
Comment out the GetItems method and see if the table is empty or not on postback. It sounds like your repeaters viewstate isn't populating the control again or something.
Try to move the InitializePage() method to another place. I don´t know why, but I had the same problem and the problem was when I try to access some controls in the OnInit event. I moved to event OnPreLoad() and works.
I hope to help you...
The PreRender solution also worked in our case, where we had such code in two pages of our application. This was working perfect in .Net 1.1 but however broke when we ported this code to .Net 2.0.
Not sure why it broke without any major changes to codebase.
Thanks for the OnPreRender tip!
-Ghanshyam

Categories