Why composite control click event not firing? - c#

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.

Related

Recreating many dynamic controls in ASP NET (individually actions)

I have problem with ASP.NET and dynamic controls. I have three ASCX. One of them creates two textboxes and some labels. The second containing control created if first ASCX (two textboxes and some labels). In addiction, second control also have link button named “Add Next” which on click event adding another control (two textboxes and some labels). The third ASCX control contains many the second ASCX (amount depend on SQL result). I made simple image to clarify:
The orange box contains many controls. The red box adding many black boxes on click “ADD NEXT”.
For now I use session variable to save state during recreate. For one “red box” it is working, but if I add more “red boxes”, clicking every “ADD NEXT” adding new control with textboxes and labels to every “red box” instead of in this where was clicked button “ADD NEXT”. I suppose why it is happening. Because every “red box” refers to the same Session variable, but I don’t know how to fix it. I was trying during OnClick event passing unique ID and setting this ID as session variable name, but it wasn’t working as I expected.
Could you tell me, how to manage it? How looks the best way to recreate controls, how I can manage controls individually? If something is not clear, I will clarify. Always I was finding answers in stackoverflow, but this problem has outgrow me.
Best wishes.
(Sorry for my English, it doesn’t my native language)
My code.
Code for creating textboxes and some labels (Calculator.cs):
public string FLong
{
get
{
object o = ViewState["FLong"];
if (o == null)
return String.Empty;
return (string)o;
}
set { ViewState["FLong"] = value; }
}
public string FWide
{
get
{
object o = ViewState["FWide"];
if (o == null)
return String.Empty;
return (string)o;
}
set
{
ViewState["FWide"] = value;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateControlHierarchy();
ClearChildViewState();
}
protected virtual void CreateControlHierarchy()
{
Literal row = new Literal();
row.Text = "<div class='row surface'>";
Controls.Add(row);
//Add new TextBox;
Literal col = new Literal();
col.Text = "<div class='col-xs-4'>";
Controls.Add(col);
TextBox fLong = new TextBox();
fLong.ID = "fLong";
fLong.CssClass = "form-control";
//fLong.TextChanged += new EventHandler(Calculate_TextChanged);
//fLong.AutoPostBack = true;
fLong.Text = FLong;
Controls.Add(fLong);
Literal textLong = new Literal();
textLong.Text = "<span>ft. long x</span>";
Controls.Add(textLong);
RegularExpressionValidator flongValidate = new RegularExpressionValidator();
flongValidate.ControlToValidate = "fLong";
flongValidate.ErrorMessage = "Only Numbers allowed";
flongValidate.ValidationExpression = #"\d+";
flongValidate.ForeColor = System.Drawing.Color.Red;
flongValidate.Attributes["style"] = "display:block";
Controls.Add(flongValidate);
Literal colEnd = new Literal();
colEnd.Text = "</div>";
Controls.Add(colEnd);
//Add new Textbox
Literal col2 = new Literal();
col2.Text = "<div class='col-xs-4'>";
Controls.Add(col2);
TextBox fWide = new TextBox();
fWide.ID = "fWide";
fWide.CssClass = "form-control";
fWide.Text = FWide;
Controls.Add(fWide);
Literal textWide = new Literal();
textWide.Text = "<span>ft. wide</span>";
Controls.Add(textWide);
RegularExpressionValidator fwideValidate = new RegularExpressionValidator();
fwideValidate.ControlToValidate = "fWide";
fwideValidate.ErrorMessage = "Only Numbers allowed";
fwideValidate.ValidationExpression = #"\d+";
fwideValidate.ForeColor = System.Drawing.Color.Red;
fwideValidate.Attributes["style"] = "display:block";
Controls.Add(fwideValidate);
Literal col2End = new Literal();
col2End.Text = "</div>";
Controls.Add(col2End);
Literal rowEnd = new Literal();
rowEnd.Text = "</div>";
Controls.Add(rowEnd);
}
Code handling recreating (SurfaceCalculator.cs):
private int DefaultAmountControls = 1;
private string surfaceID;
public string SurfaceID
{
get { return surfaceID; }
set { surfaceID = value; }
}
public int Visibility
{
get
{
//store the object in session if not already stored
if (Session[surfaceID] == null)
Session[surfaceID] = DefaultAmountControls;
//return the object from session
return (int)Session[surfaceID];
}
set
{
if (value <= 5)
Session[surfaceID] = value;
else
Session[surfaceID] = 5;
}
}
protected void addSurface_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
surfaceID = b.CommandArgument;
Visibility += 1;
}
protected override void OnInit(EventArgs e)
{
LinkButton addSurface = new LinkButton();
addSurface.Text = "+ Add surface";
addSurface.CommandArgument = surfaceID;
addSurface.Click += new EventHandler(addSurface_Click);
base.OnInit(e);
List<Calculator> c = Surface.Controls.OfType<Calculator>().ToList();
for (int i = 1; i <= Visibility; i++)
{
c.ElementAt(i - 1).Visible = true;
}
if (Visibility >= 5)
{
addSurface.Enabled = false;
}
Controls.Add(addSurface);
}
Code to adding many controls depending on SQL result
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var listOfProjects = //GETTING FROM SQL
if(listOfProjects != null)
{
foreach (var proj in listOfProjects)
{
Panel placeHolder = new Panel();
placeHolder.CssClass = "surface";
placeHolder.ID = "placeHolder" + proj.DocumentID;
surfacesContainer.Controls.Add(placeHolder);
SurfaceCalculator newElement = (SurfaceCalculator)LoadControl("~/PATH_TO/CONTROL.ascx");
newElement.ID = "surfaceCalculator" + proj.DocumentID;
newElement.SurfaceID = newElement.ID;
placeHolder.Controls.Add(newElement);
}
}
}

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.

Dynamically wire up Button Click event in Composite Control

I have a custom composite control NoteHeaderDiv, containing a Button:
//NoteHeaderControl snippet
public event EventHandler OnEditClick;
protected void btnEdit_Click(object sender, EventArgs e)
{
if (OnEditClick != null)
{
OnEditClick(sender, e);
}
}
public NoteHeaderControl()
{
this.noteHeaderDiv = new HtmlGenericControl("div");
this.noteHeaderDiv.ID = "noteHeaderDiv";
this.noteHeaderDiv.Attributes.Add("class", "noteHeaderDiv");
this.imagePlaceHolder = new HtmlGenericControl("span");
this.imagePlaceHolder.ID = "imagePlaceHolder";
this.imagePlaceHolder.Attributes.Add("class", "noteCollapsed");
this.lblNoteDate = new Label();
this.lblNoteDate.ID = "lblNoteDate";
this.lblNoteDate.CssClass = "noteDate";
this.lblNoteTitle = new Label();
this.lblNoteTitle.ID = "lblNoteTitle";
this.lblNoteTitle.CssClass = "noteTitle";
this.lblNoteAuthorName = new Label();
this.lblNoteAuthorName.ID = "lblNoteTitle";
this.lblNoteAuthorName.CssClass = "noteAuthor";
this.editButton = new Button();
this.editButton.CssClass = "editNoteButton";
this.editButton.ToolTip = "Editovat";
this.editButton.ID = "editButton";
this.editButton.OnClientClick = "showEditDialog('editPerson');";
this.editButton.Click += btnEdit_Click;
this.addTeamTaskButton = new HtmlGenericControl("button");
this.addTeamTaskButton.ID = "addTeamTaskButton";
this.addTeamTaskButton.Attributes.Add("class", "addTeamTaskButton");
this.addTeamTaskButton.Attributes.Add("onclick", "showDialog('editPerson');");
this.addTeamTaskButton.Attributes.Add("title", "Nový Team Task");
}
#region protected override void CreateChildControls()
protected override void CreateChildControls()
{
base.CreateChildControls();
this.lblNoteDate.Text = String.Format("{0}.{1}.", this.noteDate.Day, this.noteDate.Month);
this.lblNoteTitle.Text = noteTitle;
this.lblNoteAuthorName.Text = noteAuthorName;
//this.editButton.Click += btnEdit_Click;
this.noteHeaderDiv.Controls.Add(imagePlaceHolder);
this.noteHeaderDiv.Controls.Add(lblNoteDate);
this.noteHeaderDiv.Controls.Add(lblNoteTitle);
this.noteHeaderDiv.Controls.Add(lblNoteAuthorName);
this.noteHeaderDiv.Controls.Add(editButton);
this.noteHeaderDiv.Controls.Add(addTeamTaskButton);
this.Controls.Add(noteHeaderDiv);
}
protected override void OnInit(EventArgs e)
{
CreateChildControls();
base.OnInit(e);
}
Then in Page_Load, I wire up the public event to another handler. Problem is, that btnEdit_Click never fires. If I dynamically create a button in my Page_Load and wire it up directly to the event handler defined in my Page, everything works as expected.
Any suggestions about how to get it to work? I'm at a loss as to what I'm doing wrong.

How to prevent my textbox from clearing text on postback.

I have a pretty interesting dilemma that is giving me a hurricane of a headache. I've seen a similar question asked here, but the user posted no code, so it was unresolved. This is a asp.net, sql server, and c# app.
In my application, I use JavaScript to display dummy data in a TextBox to entertain the user while a long process is running. (please note, this is a project, not a professional app).
The problem is, once the app is done executing, the app (I believe) refreshes the page and clears the TextBox. I want to prevent this from happening and continue to display the text after the program is completed.
My question is, where in the following code is the page being refreshed? How can I re-code it to prevent the text from being cleared?
I know there is no issue with the JavaScript or the .aspx page. I have not set or programmed any property to clear the text. If anyone could shed light on the issue, I would greatly appreciate it. If you need more code from me please let me know. I will be very active on this page until it is resolved. Thanks again!
public partial class SendOrders : System.Web.UI.Page
{
protected enum EDIType
{
Notes,
Details
}
protected static string NextBatchNum = "1";
protected static string FileNamePrefix = "";
protected static string OverBatchLimitStr = "Batch file limit has been reached. No more batches can be processed today.";
protected void Page_Load(object sender, EventArgs e)
{
Initialize();
}
protected void Page_PreRender(object sender, EventArgs e)
{ }
protected void btnExit_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
protected void Button_Click(object sender, EventArgs e)
{
PutFTPButton.Enabled = false;
Thread.Sleep(3000);
Button btn = (Button)sender;
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
KaplanFTP.Transmit transmit = new KaplanFTP.Transmit();
if (btn.ID == PutFTPButton.ID)
{
DirectoryInfo dir = new DirectoryInfo(#"C:\Kaplan");
FileInfo[] BatchFiles = bf.GetBatchFiles(dir);
bool result = transmit.UploadBatchFilesToFTP(BatchFiles);
if (!result)
{
ErrorLabel.Text += KaplanFTP.errorMsg;
return;
}
bf.InsertBatchDataIntoDatabase("CTL");
bf.InsertBatchDataIntoDatabase("HDR");
bf.InsertBatchDataIntoDatabase("DET");
bf.InsertBatchDataIntoDatabase("NTS");
List<FileInfo> allfiles = BatchFiles.ToList<FileInfo>();
allfiles.AddRange(dir.GetFiles("*.txt"));
bf.MoveFiles(allfiles);
foreach (string order in bf.OrdersSent)
{
OrdersSentDiv.Controls.Add(new LiteralControl(order + "<br />"));
}
btnExit.Visible = true;
OrdersSentDiv.Visible = true;
OrdersInfoDiv.Visible = false;
SuccessLabel.Visible = true;
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
BatchesCreatedLbl.Text = int.Parse(NextBatchNum).ToString();
Thread.Sleep(20000);
if (KaplanFTP.errorMsg.Length != 0)
{
ErrorLabel.Visible = false;
SuccessLabel.Visible = true;
ErrorLabel.Text = KaplanFTP.errorMsg;
}
}
}
private void Initialize()
{
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
if (!IsPostBack)
{
FileNamePrefix = bf.FileNamePrefix;
NextBatchNum = bf.NextBatchNum;
BatchesCreatedLbl.Text = (int.Parse(NextBatchNum) - 1).ToString();
if (bf.CheckLocalForNewBatch() == true)
{
NoBatchesToProcessLbl.Visible = false;
BatchesToProcessLbl.Visible = true;
if (int.Parse(NextBatchNum) >= 50)
{
ErrorLabel.Text += ErrorLabel.Text + OverBatchLimitStr;
ErrorLabel.Visible = true;
PutFTPButton.Enabled = false;
}
else
{
bf.ReadyFilesForTransmission();
ErrorLabel.Visible = false;
PutFTPButton.Enabled = true;
List<string[]> detStream = bf.GetBatchStream("DET");
List<string[]> hdrStream = bf.GetBatchStream("HDR");
OrdersInfoDiv.Visible = true;
DataTable dt = new DataTable();
dt.Columns.Add("ORDER NUMBER");
dt.Columns.Add("LINE NUMBER");
dt.Columns.Add("ITEM NUMBER/ISBN");
dt.Columns.Add("DESCRIPTION");
dt.Columns.Add("QUANTITY");
dt.Columns.Add("SHIPPING");
Dictionary<string, string> orderShip = new Dictionary<string, string>();
foreach (string[] hdrItems in hdrStream)
{
orderShip.Add(hdrItems[0], hdrItems[2]);
}
foreach (string[] detItems in detStream)
{
List<string> detLineList = new List<string>(detItems);
detLineList.Add(orderShip[detItems[0]]);
detLineList.RemoveAt(13);
detLineList.RemoveAt(12);
detLineList.RemoveAt(11);
detLineList.RemoveAt(10);
detLineList.RemoveAt(9);
detLineList.RemoveAt(8);
detLineList.RemoveAt(7);
detLineList.RemoveAt(4);
detLineList.RemoveAt(2);
detLineList[1] = detLineList[1].TrimStart('0');
detLineList[4] = detLineList[4].TrimStart('0');
dt.Rows.Add(detLineList.ToArray());
}
BatchDetails.DataSource = dt;
BatchDetails.DataBind();
}
}
else
{
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
}
}
}
}
Yes. You will have to determine the state of your calculation and populate the control inside Page_Load in the case where IsPostBack is true:
protected void Page_Load(object sender, EventArgs e) {
if (IsPostBack) {
// re-populate javascript-fill UI
} else {
}
Initialize();
}
You can probably also move Initialize() into the else clause as well.
Since you are handling the button click server side (I'm assuming the problem is happening once the user clicks the button?) there has to be a postback to handle it.
You could try putting your button and label into an updatepanel control - it uses AJAX to refresh its contents.
See this page for more information on updatepanels.

Event won't fire in webpart lifecycle

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.

Categories

Resources