Event won't fire in webpart lifecycle - c#

I have a webpart that is quire simple. CLick on "Add" link that sets a 2 text boxes visible. Type in some text and click "Save" button but the click event won't fire. I'm pasting the code it hopes of some suggestion. I've searched for solutions but haven't found anything I can go on. I realize what maight be the issue but don't know how to corrct it. I need to be able to wireup and event with the handler sotimes before the page renders and I tried to override the OnPreRender method but it did not work in right moment.
Other minor issue that I will need to address is that the onFocus method doesn't work in txtMyLinkName.Focus(). Thanks for your help! - Risho
public class MyLinks : WebPart
{
public static string m_Portal = ConfigurationManager.ConnectionStrings["dbPortal"].ConnectionString;
Panel pnlMyLinks = new Panel();
Label lblError = new Label();
Label lblMyLinkURL = new Label();
Label lblMyLinkName = new Label();
TextBox txtMyLinkName = new TextBox();
TextBox txtMyLinkURL = new TextBox();
Button btnSaveMyLink = new Button();
LinkButton lbMyLinkAdd = new LinkButton();
Literal litP1 = new Literal();
Literal litBR1 = new Literal();
public cisf_MyLinks()
{
this.Title = "MyLinks";
this.ExportMode = WebPartExportMode.All;
}
protected override void CreateChildControls()
{
GetLinks();
base.CreateChildControls();
}
//protected override void OnPreRender(EventArgs e)
//{
// btnSaveMyLink.Text = "Save";
// btnSaveMyLink.Click += new EventHandler(btnSaveMyLink_Click);
// Controls.Add(btnSaveMyLink);
// base.OnPreRender(e);
//}
protected void GetLinks()
{
pnlMyLinks.Controls.Clear();
int i = 0;
lbMyLinkAdd.Text = "Add";
pnlMyLinks.Controls.Add(lbMyLinkAdd);
lbMyLinkAdd.Click += new EventHandler(lbMyLinkAdd_Click);
pnlMyLinks.Controls.Add(new LiteralControl("<br />"));
IDataReader drMyLinks = Get_MyLinks(Page.Request.ServerVariables["Logon_User"].Split("\\".ToCharArray())[1].ToLower());
while (drMyLinks.Read())
{
HyperLink hlMyLink = new HyperLink();
LinkButton lbDelMyLink = new LinkButton();
lbDelMyLink.Text = "(del)";
lbDelMyLink.ToolTip = "Delete this link";
lbDelMyLink.CssClass = "verytiny";
lbDelMyLink.Command += new CommandEventHandler(DelMyLink);
lbDelMyLink.CommandName = drMyLinks["id"].ToString();
pnlMyLinks.Controls.Add(lbDelMyLink);
pnlMyLinks.Controls.Add(new LiteralControl(" "));
hlMyLink.ID = "hl" + drMyLinks["ID"].ToString();
hlMyLink.Text = drMyLinks["Title"].ToString();
hlMyLink.NavigateUrl = drMyLinks["url"].ToString();
hlMyLink.Target = "_blank";
hlMyLink.ToolTip = drMyLinks["Title"].ToString();
pnlMyLinks.Controls.Add(hlMyLink);
pnlMyLinks.Controls.Add(new LiteralControl("<br />"));
if (drMyLinks["ID"].ToString() != "") { i += 1; }
}
this.Controls.Add(pnlMyLinks);
}
protected void lbMyLinkAdd_Click(object sender, EventArgs e)
{
lbMyLinkAdd.Visible = false;
lblMyLinkName.Visible = true;
txtMyLinkName.Visible = true;
litBR1.Visible = true;
lblMyLinkURL.Visible = true;
txtMyLinkURL.Visible = true;
btnSaveMyLink.Visible = true;
litP1.Visible = true;
(txtMyLinkName - dot focus)
lblMyLinkName.Text = "Link Name: ";
lblMyLinkURL.Text = "Link URL: ";
btnSaveMyLink.Text = "Save";
btnSaveMyLink.Click += new EventHandler(btnSaveMyLink_Click);
pnlMyLinks.Controls.Add(new LiteralControl("<table class='mylinksTable' cellpadding='0' cellspacing='0' border='1'><tr valign='top'><td>"));
pnlMyLinks.Controls.Add(lblMyLinkName);
pnlMyLinks.Controls.Add(new LiteralControl("</td><td>"));
pnlMyLinks.Controls.Add(txtMyLinkName);
pnlMyLinks.Controls.Add(new LiteralControl("</td></tr><tr valign='top'><td>"));
pnlMyLinks.Controls.Add(lblMyLinkURL);
pnlMyLinks.Controls.Add(new LiteralControl("</td><td>"));
pnlMyLinks.Controls.Add(txtMyLinkURL);
pnlMyLinks.Controls.Add(new LiteralControl("</td></tr><tr valign='top'><td colspan='2'>"));
pnlMyLinks.Controls.Add(btnSaveMyLink);
pnlMyLinks.Controls.Add(new LiteralControl("</td></tr></table>"));
this.Controls.Add(pnlMyLinks);
}
protected void btnSaveMyLink_Click(object sender, EventArgs e)
{
string thisURL;
if ((txtMyLinkName.Text != "") && (txtMyLinkURL.Text != ""))
{
if (txtMyLinkURL.Text.StartsWith("http"))
{ thisURL = txtMyLinkURL.Text; }
else { thisURL = "http://" + txtMyLinkURL.Text; }
AddMyLink(txtMyLinkName.Text, thisURL, Page.Request.ServerVariables["Logon_User"].Split("\\".ToCharArray())[1].ToLower());
GetLinks();
txtMyLinkName.Text = "";
txtMyLinkURL.Text = "";
lbMyLinkAdd.Visible = true;
}
lbMyLinkAdd.Visible = true;
lblMyLinkName.Visible = false;
txtMyLinkName.Visible = false;
litBR1.Visible = false;
lblMyLinkURL.Visible = false;
txtMyLinkURL.Visible = false;
btnSaveMyLink.Visible = false;
litP1.Visible = false;
}
}

If you are creating the button in code, then it needs to be wired up in the Page_Load event so that the click event can fire. Page_PreRender is too late.

In addition to adding the control in Load event as already posted, you should set the ID field e.g. btnSaveMyLink.ID = "SaveLink"; to a unique value.

Related

Why composite control click event not firing?

i wrote a composite asp.net control named as (WebDbConnection) to manage connection string of my database.
i added a button "btnConnect" and created click event for it in "CreateChildControls" method.
public WebDbConnection(string extraParameters, string configConnectionName, string databaseName,
bool showDbName, string dialogName, bool isEncrypted,ref Page page)
{
_currentPage = page;
_extraParameters = extraParameters;
_dialogName = dialogName;
IsEncrypted = isEncrypted;
_showDbName = showDbName;
_configConnectionName = configConnectionName;
LoadDefaultConnectionString(IsEncrypted);
_databaseName = databaseName;
}
protected void BtnConnect_Click(object sender, EventArgs e)
{
try
{
EnsureChildControls();
_server = Dbconnection_txtServer.Text;
_userName = Dbconnection_txtUser.Text;
_password = Dbconnection_txtPass.Text;
_databaseName = Dbconnection_txtdbname.Text;
if (Connection.State == ConnectionState.Connecting)
return;
Connect();
if (Connection.State == ConnectionState.Open)
this.Controls.Clear();
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertbox",
"alert('Can not connect to server.')", true);
Dbconnection_txtServer.Text = _server;
Dbconnection_txtUser.Text = _userName;
Dbconnection_txtPass.Text = _password;
Dbconnection_txtdbname.Text = _databaseName;
}
}
catch (Exception ex)
{
LastError = ex.Message;
LoadDefaultConnectionString(IsEncrypted);
Dbconnection_txtServer.Text = _server;
Dbconnection_txtPass.Text = _password;
Dbconnection_txtUser.Text = _userName;
}
}
protected override void CreateChildControls()
{
Controls.Clear();
lbl_HeaderName = new Label();
lbl_HeaderName.ID = "lbl_HeaderName";
lbl_HeaderName.Text = "Server Credential";
lbl_servername = new Label();
lbl_servername.ID = "lbl_servername";
lbl_servername.Text = "Server Name";
Dbconnection_txtServer = new TextBox();
Dbconnection_txtServer.ID = "Dbconnection_txtServer";
lbl_username = new Label();
lbl_username.ID = "lbl_username";
lbl_username.Text = "User Name:";
Dbconnection_txtUser = new TextBox();
Dbconnection_txtUser.ID = "Dbconnection_txtUser";
lbl_password = new Label();
lbl_password.ID = "lbl_password";
lbl_password.Text = "Password:";
Dbconnection_txtPass = new TextBox();
Dbconnection_txtPass.ID = "Dbconnection_txtPass";
lbl_databasename = new Label();
lbl_databasename.ID = "lbl_databasename";
lbl_databasename.Text = "Database Name:";
Dbconnection_txtdbname = new TextBox();
Dbconnection_txtdbname.ID = "Dbconnection_txtdbname";
btnConnect = new Button();
btnConnect.ID = "btnConnect";
btnConnect.Text = "Connect";
btnConnect.Click += BtnConnect_Click;
btnCancel = new Button();
btnCancel.ID = "btnCancel";
btnCancel.Text = "Cancel";
btnCancel.Click += BtnCancel_Click;
//add controls
Controls.Add(lbl_password);
Controls.Add(lbl_databasename);
Controls.Add(lbl_servername);
Controls.Add(lbl_username);
Controls.Add(lbl_HeaderName);
Controls.Add(Dbconnection_txtdbname);
Controls.Add(Dbconnection_txtPass);
Controls.Add(Dbconnection_txtServer);
Controls.Add(Dbconnection_txtUser);
Controls.Add(btnConnect);
Controls.Add(btnCancel);
}
void ShowPage()
{
EnsureChildControls();
if (!_currentPage.Form.Controls.Contains(this))
_currentPage.Form.Controls.Add(this);
else
{
_currentPage.Form.Controls.Remove(this);
_currentPage.Form.Controls.Add(this);
}
Dbconnection_txtdbname.Text = _databaseName;
if (!_showDbName)
{
lbl_databasename.Visible = false;
Dbconnection_txtdbname.Visible = false;
}
//----------------------
if (_dialogName.IsEmptyOrNull()) return;
lbl_HeaderName.Text = "Fill " + _dialogName + " Information";
}
The idea is to show composite control when i call "ShowPage" method internally.
the issue is when i create composite control in other pages,"ShowPage" work correctly but on the postbackes the "BtnConnect" click event not firing and only postback form occurs!!!
within couple of hours i found that when i add instance of WebDbConnection class to form controls in page_load event, my control work fine.
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Controls.Add(WebDbConnection_instance);
}
but how to do this adding controls inside my control not on customer page_load event?
after 10 days of googling and testing some approaches, i found a solution to intercept my code behind class object and HTML tags sending to users.
so instead of using composite control, i using HTTPModule "myModule1" to catch Ajax request and then create HTML tags i needed and send that to users.
see this post for details: How to search and replace the requestContext.Response in a IHttpModule?
the nightmare is not ended !!!
after above approach you should register HTTPModule in web.config file (<system.webserver> tag) so i want to register "myModule1" dynamically whenever on demand. to achieve this i use below directive in top of "myModule1" class.
[assembly: PreApplicationStartMethod(typeof(DreamyTools.DataBase.Web.MyModule1), "Initialize")]
namespace DataBase.Web
{
public class MyModule1 : IHttpModule
{
public static void Initialize()
{
Microsoft.Web.Infrastructure.DynamicModuleHelper
.DynamicModuleUtility.RegisterModule(MyModule1);
}
so whenever this object referenced,the "Initialize" method is called and registration to web.config occurs.
I hope this approach was helpful for developers to create Ajax calls and get requests in own SDKs.

Show WinFrm from C# console application and wait to close

I am trying to show a WinForm (inputbox) from a console application in C# and wait until the user closes the form. It is important for me to have the inputbox ontop and active when it opens. ShowDialog() is not working in my case as in some cases it does not appears as an active form. So I'd like to change my code and use Show(). This way I can manually make find out if the form is active or not and if not activate it myself. With ShowDialog(). my code stops and I can not do anything until the from is closed.
Below is my code. It does show the inputbox, however it is frozen. What am I doing wrong please? As clear the while-loop after "inputBox.Show();" is not doing anything, but if I can manage to run the loop and the inputbox does not freeze, I will sort out the rest myself. I appreciate your help.
public static string mInputBox(string strPrompt, string strTitle, string strDefaultResponse)
{
string strResponse = null;
Form inputBox = new Form();
inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
inputBox.ClientSize = new Size(500, 85);
inputBox.Text = strTitle;
inputBox.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
inputBox.Left = (Screen.PrimaryScreen.Bounds.Size.Width / 2) - (inputBox.ClientSize.Width / 2);
inputBox.Top = (Screen.PrimaryScreen.Bounds.Size.Height / 2) - (inputBox.ClientSize.Height / 2);
Label lblPrompt = new Label();
lblPrompt.Text = strPrompt;
inputBox.Controls.Add(lblPrompt);
TextBox textBox = new TextBox();
textBox.Text = strDefaultResponse;
inputBox.Controls.Add(textBox);
Button okButton = new Button();
okButton.Text = "&OK";
inputBox.Controls.Add(okButton);
Button cancelButton = new Button();
cancelButton.Text = "&Cancel";
inputBox.Controls.Add(cancelButton);
okButton.Click += (sender, e) =>
{
strResponse = textBox.Text;
inputBox.Close();
};
cancelButton.Click += (sender, e) =>
{
inputBox.Close();
};
inputBox.AcceptButton = okButton;
inputBox.CancelButton = cancelButton;
SetWindowPos(inputBox.Handle, HWND_TOPMOST, inputBox.Left, inputBox.Top, inputBox.Width, inputBox.Height, NOACTIVATE);
inputBox.Show();
while {true}
Thread.Sleep(100);
Application.DoEvents();
return strResponse;
}
I'm not sure why you are taking this route, I'm sure there are better ways to do it (explain one at the end). however to make your code run you should add Application.DoEvents() inside your loop
the code should be something like this:
var formActive = true;
inputBox.FormClosed += (s, e) => formActive = false;
inputBox.Show();
inputBox.TopMost = true;
inputBox.Activate();
while (formActive)
{
Thread.Sleep(10);
Application.DoEvents();
}
and the whole method will be:
public static string mInputBox(string strPrompt, string strTitle, string strDefaultResponse)
{
string strResponse = null;
Form inputBox = new Form();
inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
inputBox.ClientSize = new Size(500, 85);
inputBox.Text = strTitle;
inputBox.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
inputBox.Left = (Screen.PrimaryScreen.Bounds.Size.Width/2) - (inputBox.ClientSize.Width/2);
inputBox.Top = (Screen.PrimaryScreen.Bounds.Size.Height/2) - (inputBox.ClientSize.Height/2);
Label lblPrompt = new Label();
lblPrompt.Text = strPrompt;
inputBox.Controls.Add(lblPrompt);
TextBox textBox = new TextBox();
textBox.Text = strDefaultResponse;
inputBox.Controls.Add(textBox);
Button okButton = new Button();
okButton.Text = "&OK";
inputBox.Controls.Add(okButton);
Button cancelButton = new Button();
cancelButton.Text = "&Cancel";
inputBox.Controls.Add(cancelButton);
okButton.Click += (sender, e) =>
{
strResponse = textBox.Text;
inputBox.Close();
};
cancelButton.Click += (sender, e) =>
{
inputBox.Close();
};
inputBox.AcceptButton = okButton;
inputBox.CancelButton = cancelButton;
var formActive = true;
inputBox.FormClosed += (s, e) => formActive = false;
inputBox.Show();
inputBox.TopMost = true;
inputBox.Activate();
while (formActive)
{
Thread.Sleep(10);
Application.DoEvents();
}
return strResponse;
}
but I think it would be a better Idea to Derive from Form and create a InputBox and set TopMost and call Activate OnLoad to create what you need, then simply call ShowDialog, something like:
class Inputbox : Form
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
TopMost = true;
Activate();
}
}
and better to put UI code in InputBox class as the whole code and usage would be like:
class Inputbox : Form
{
public string Response { get; set; }
public Inputbox(string strTitle, string strPrompt, string strDefaultResponse)
{
//add UI and Controls here
FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
ClientSize = new Size(500, 85);
Text = strTitle;
StartPosition = System.Windows.Forms.FormStartPosition.Manual;
Left = (Screen.PrimaryScreen.Bounds.Size.Width/2) - (ClientSize.Width/2);
Top = (Screen.PrimaryScreen.Bounds.Size.Height/2) - (ClientSize.Height/2);
Label lblPrompt = new Label();
lblPrompt.Text = strPrompt;
Controls.Add(lblPrompt);
TextBox textBox = new TextBox();
textBox.Text = strDefaultResponse;
Controls.Add(textBox);
Button okButton = new Button();
okButton.Text = "&OK";
Controls.Add(okButton);
Button cancelButton = new Button();
cancelButton.Text = "&Cancel";
Controls.Add(cancelButton);
okButton.Click += (sender, e) =>
{
Response = textBox.Text;
Close();
};
cancelButton.Click += (sender, e) =>
{
Close();
};
AcceptButton = okButton;
CancelButton = cancelButton;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
TopMost = true;
Activate();
}
}
public static string mInputBox(string strPrompt, string strTitle, string strDefaultResponse)
{
string strResponse = null;
Inputbox inputBox = new Inputbox(strPrompt,strTitle,strDefaultResponse);
inputBox.ShowDialog();
return inputBox.Response;
}
You need to run a message loop:
Application.Run(inputBox);

Click event of dynamically created Button not firing

I'm creating dynamically generated buttons, and when I click on the button, the Add_Click method doesn't get fired up.
Here is a sample from my code:
protected void SearchRec(object sender, EventArgs e)
{
SearchResultsPanel.Controls.Clear();
string text_to_search = SearchTB.Text;
Friends RecToSearch = new Friends();
List<Friends> ListNFU = DBS.getNonFriendUsers(User.Identity.Name.ToString(), text_to_search);
if (ListNFU.Count != 0)
{
foreach (Friends NFRIndex in ListNFU)
{
string _FriendsOutput = FR_output(NFRIndex);
HyperLink RecHyperLink = new HyperLink();
RecHyperLink.Text = _FriendsOutput;
RecHyperLink.CssClass = "HyperLinkFriends";
RecHyperLink.ID = NFRIndex.UdName;
SearchResultsPanel.Controls.Add(new LiteralControl("<div style='height:32px'>"));
SearchResultsPanel.Controls.Add(RecHyperLink);
Button addUser = new Button();
addUser.CssClass = "ApproveBTN";
addUser.Text = "send";
addUser.Click += new EventHandler(Add_Click);
addUser.ID = NFRIndex.UdName + "3";
SearchResultsPanel.Controls.Add(addUser);
}
}
else
{
Label NoResultsLabel = new Label();
NoResultsLabel.Text = "Nothing is found";
SearchResultsPanel.Controls.Add(NoResultsLabel);
}
SearchResultsPanel.Controls.Add(new LiteralControl("</div>"));
}
private void Add_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string _tempID = btn.ID;
string id = _tempID.Substring(0, _tempID.LastIndexOf('3'));
DateTime cdate = new DateTime();
cdate = DateTime.Now;
DBS.AddFriend(User.Identity.Name, id, cdate);
btn.Visible = false;
btn.NamingContainer.FindControl(id).Visible = false;
}
Note: I did something very similar on page_load and it does work.
That is because when the page is reloaded, the control is most probably not recreated. That means that the event won't fire indeed.
You need to place this kind of code in the Page_Load so it gets recreated at postback.

OnTextChanged event not firing inside UpdatePanel - both created dynamically

What I am trying to do is to populate column of GridView with textboxes and to execute some function OnTextChanged.
This is my code:
if (e.Row.RowType == DataControlRowType.DataRow)
{
UpdatePanel UP_AmountToBuy = new UpdatePanel();
UP_AmountToBuy.ContentTemplateContainer.Controls.Clear();
UP_AmountToBuy.Triggers.Clear();
UP_AmountToBuy.UpdateMode = UpdatePanelUpdateMode.Conditional;
UP_AmountToBuy.ChildrenAsTriggers = false;
UP_AmountToBuy.Attributes["runat"] = "server";
//Create and add TextBox
TextBox TB_AmountToBuy = new TextBox();
TB_AmountToBuy.Text = "0";
TB_AmountToBuy.TextChanged += new EventHandler(TB_AmountToBuy_TextChanged);
TB_AmountToBuy.Attributes["OnTextChanged"] = "TB_AmountToBuy_TextChanged";
TB_AmountToBuy.Attributes["runat"] = "server";
TB_AmountToBuy.AutoPostBack = true;
TB_AmountToBuy.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
TB_AmountToBuy.ID = "buyID" + count;
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(TB_AmountToBuy);
//Create and add AsyncPostBackTrigger
AsyncPostBackTrigger APBT_trig = new AsyncPostBackTrigger();
APBT_trig.EventName = "TextChanged";
APBT_trig.ControlID = TB_AmountToBuy.ID;
UP_AmountToBuy.Triggers.Add(APBT_trig);
Label newLBL = new Label();
newLBL.Text = "123";
newLBL.Attributes["runat"] = "server";
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(newLBL);
e.Row.Cells[5].Controls.Add(UP_AmountToBuy);
count++;
}
}
public void TB_AmountToBuy_TextChanged(object sender, EventArgs e)
{
((sender as TextBox).Parent.Controls[1] as Label).Text = (sender as TextBox).Text;
}
The problem is, that event OnTextChanged never fired...
Dynamically generated controls needs to be created every time in page load in order to restore their view state ,fire events and get value from them.Like this
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var dt = new System.Data.DataTable();
dt.Columns.Add("Col1");
dt.Rows.Add("Hi");
GridView1.DataSource = dt;
GridView1.DataBind();
}
CreateDynamicControles();
}
public void CreateDynamicControles()
{
var count = 0;
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
UpdatePanel UP_AmountToBuy = new UpdatePanel();
UP_AmountToBuy.ContentTemplateContainer.Controls.Clear();
UP_AmountToBuy.Triggers.Clear();
UP_AmountToBuy.UpdateMode = UpdatePanelUpdateMode.Conditional;
UP_AmountToBuy.ChildrenAsTriggers = false;
UP_AmountToBuy.Attributes["runat"] = "server";
//Create and add TextBox
TextBox TB_AmountToBuy = new TextBox();
TB_AmountToBuy.Text = "0";
TB_AmountToBuy.TextChanged += new EventHandler(TB_AmountToBuy_TextChanged);
TB_AmountToBuy.Attributes["OnTextChanged"] = "TB_AmountToBuy_TextChanged";
TB_AmountToBuy.Attributes["runat"] = "server";
TB_AmountToBuy.AutoPostBack = true;
TB_AmountToBuy.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
TB_AmountToBuy.ID = "buyID" + count;
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(TB_AmountToBuy);
//Create and add AsyncPostBackTrigger
AsyncPostBackTrigger APBT_trig = new AsyncPostBackTrigger();
APBT_trig.EventName = "TextChanged";
APBT_trig.ControlID = TB_AmountToBuy.ID;
UP_AmountToBuy.Triggers.Add(APBT_trig);
Label newLBL = new Label();
newLBL.Text = "123";
newLBL.Attributes["runat"] = "server";
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(newLBL);
row.Cells[0].Controls.Add(UP_AmountToBuy);
count++;
}
}
}
public void TB_AmountToBuy_TextChanged(object sender, EventArgs e)
{
((sender as TextBox).Parent.Controls[1] as Label).Text = (sender as TextBox).Text;
}
}
Try this, since you are using UpdatePanel. So use following property.
Set property:
EnableViewstate="True"

Using Sessions in dynamic texboxes

Alright so I need to save each input from the textbox's in a session variable. The problem is that this is dynamic, meaning that the texbox ID is NatureTextbox_1, NatureTexbox_2 ect. And this makes it hard to save per session variable due to the infintite amount of texbox's available. I have been pounding my head against the wall trying to figure this out and am resorting to being a noob and asking you guys for your advice. If you can give me any information on what to do I'd appreciate it.
This is the C# Code (Remember the textbox's are dynamic meaning infinite):
protected void Page_Load(object sender, EventArgs e)
{
// Add any controls that have been previously added dynamically
for (int i = 0; i < TotalNumberAdded; ++i)
{
AddControls(i + 1);
}
}
private void AddControls(int controlNumber)
{
var newPanel = new Panel();
var natureLabel = new Label();
var dateLabel = new Label();
var fatalLabel = new Label();
var injurLabel = new Label();
var natureTextbox = new TextBox();
var dateTextbox = new TextBox();
var fatalTextbox = new TextBox();
var injurTextbox = new TextBox();
//Validations
var dateRegex = new RegularExpressionValidator();
//*****CURRENT IDEA THAT ISNT WORKING***********************************
Session["Nature" + (TotalNumberAdded - 1)] = natureTextbox.Text.ToString();
Session["Date" + (TotalNumberAdded - 1)] = dateTextbox.Text.ToString();
Session["Fatal" + (TotalNumberAdded - 1)] = fatalTextbox.Text.ToString();
Session["injury" + (controlNumber - 1)] = injurTextbox.Text.ToString();
//**********************************************************************
// textbox needs a unique id to maintain state information
natureTextbox.ID = "NatureTextBox_" + controlNumber;
dateTextbox.ID = "DateTextbox_" + controlNumber;
fatalTextbox.ID = "fatalTextbox_" + controlNumber;
injurTextbox.ID = "injurTextbox_" + controlNumber;
natureLabel.Text = "Nature Of Accident: ";
dateLabel.Text = "Date: ";
fatalLabel.Text = "Fatalities: ";
injurLabel.Text = "Injuries: ";
dateRegex.ID = "DateRegex_" + controlNumber;
dateRegex.Text = "Please enter in format MM/DD/YYY";
dateRegex.ValidationExpression = #"^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$";
dateRegex.ControlToValidate = dateTextbox.ID;
// add the label and textbox to the panel, then add the panel to the form
newPanel.Controls.Add(new LiteralControl("<table><tr>"));
newPanel.Controls.Add(new LiteralControl("<br />"));
newPanel.Controls.Add(new LiteralControl("<td class='title-text' >"));
newPanel.Controls.Add(natureLabel);
newPanel.Controls.Add(new LiteralControl("</td><td class='title-text'width='180px'>"));
newPanel.Controls.Add(natureTextbox);
newPanel.Controls.Add(new LiteralControl("</td><td class='title-text' >"));
newPanel.Controls.Add(dateLabel);
newPanel.Controls.Add(new LiteralControl("</td><td class='title-text'>"));
newPanel.Controls.Add(dateTextbox);
newPanel.Controls.Add(new LiteralControl("<br />"));
newPanel.Controls.Add(dateRegex);
newPanel.Controls.Add(new LiteralControl("</td></tr>"));
newPanel.Controls.Add(new LiteralControl("<tr><td class='title-text'>"));
newPanel.Controls.Add(fatalLabel);
newPanel.Controls.Add(new LiteralControl("</td><td class='title-text'>"));
newPanel.Controls.Add(fatalTextbox);
newPanel.Controls.Add(new LiteralControl("</td><td class='title-text'>"));
newPanel.Controls.Add(injurLabel);
newPanel.Controls.Add(new LiteralControl("</td><td class='title-text'>"));
newPanel.Controls.Add(injurTextbox);
newPanel.Controls.Add(new LiteralControl("</td></tr></table><br /><hr />"));
AccidentPlaceHolder.Controls.Add(newPanel);
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void AccidentButton_Click(object sender, EventArgs e)
{
TotalNumberAdded++;
AddControls(TotalNumberAdded);
}
protected void PrevPage_Click(object sender, EventArgs e)
{
Response.Redirect("employment_driversapplication_personalinfo.aspx");
}
}
This works for me, bear in mind that the values are only persisted when you click 'add' - so i would suggest another save button or something to persist the values when not adding a new item.
public partial class TestRJF2 : System.Web.UI.Page
{
private IList<TextBox> AddedControls = new List<TextBox>();
protected override void CreateChildControls()
{
BuildControls();
base.CreateChildControls();
}
private void BuildControls()
{
for (var x = 0; x < TotalNumberAdded; x++)
{
var id = String.Format("NatureTextBox{0}", x);
//Check if control was already added
//only create controls that are new for this postback
if (AccidentPlaceHolder.FindControl(id) == null)
{
var textBox = new TextBox() {ID = id};
AccidentPlaceHolder.Controls.Add(textBox);
AddedControls.Add(textBox);
}
}
}
protected override void OnPreRender(EventArgs e)
{
foreach (var ctrl in AddedControls)
{
var key = ctrl.ID.Replace("TextBox", String.Empty);
Session[key] = ctrl.Text;
}
foreach (string session in Session.Keys)
{
System.Diagnostics.Debug.WriteLine(String.Format("{0} = {1}", session, Session[session]));
}
base.OnPreRender(e);
}
protected void AccidentButton_Click(object sender, EventArgs e)
{
TotalNumberAdded++;
BuildControls();
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
}

Categories

Resources