Using panels in ASP.net - asp.net

i created a textbox, a button and a panel in a page. So my aim is to create links which will be put inside a panel. However, it turns out that every time i add another one, it seems to replace the previously created link. Is there a way to just add the links, not replacing previously created links? I really don't have a background that much in ASP.
This is the code I researched.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim link As New HyperLink()
Dim ltr As New Literal()
link.Text = TextBox1.Text
link.NavigateUrl = "Default.aspx?field1=" + TextBox2.Text + " "
ltr.Text = "<br/>"
Panel1.Controls.Add(ltr)
Panel1.Controls.Add(link)
Please help me. Thanks!

As said by #Rex, when post back occurs dynamically controls will be removed from the page until we retain them in Init Event.
While adding controls to PlaceHolder, save the same data like ID, Text..etc. in a object like session variable and retrieve the same data in Page Init event and add to the place holder.
protected void Page_Init(object sender, EventArgs e)
{
// Retrieve from session variable and add the same data to the place holder.
}

Related

Gridview - Greying out checkboxes once one is checked

I'm new to all of this code, so please be patient.
On my gridview, I am trying to make it so, once I check on of the checkboxes, the others get greyed out, making it impossible to select another. How would I code this?
Thanks in advance.
PS: I'm using vb, rather than C#.
Edit: Here is the code I want to run.
Protected Sub btnOK_Click(ByVal sender As Object, ByVal e As
System.Web.UI.ImageClickEventArgs) Handles btnOK.Click
Dim TxtbxID As TextBox
Dim RB As System.Web.UI.WebControls.RadioButton
For Each row As GridViewRow In GridView1.Rows
RB = row.FindControl("select")
If RB.Checked Then
Me.txtHiddenProblem.Text = row.Cells(3).Text & " on " & row.Cells(5).Text
TxtbxID = FormView1.FindControl("ProblemTextbox")
TxtbxID.Text = txtHiddenProblem.Text
End Sub
Take a look at this article: http://www.ezzylearning.com/tutorial.aspx?tid=5187857
It has some lines of code which help you determine the particular gridview row the checkbox element was associated with...
public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
//other code
}
Now all we need to do is when the checkbox element is checked, iterate through the grid, find the checkbox, and disable them if its not the same as the one which caused the event...

Get a webuserControl's value automatically created

I have added a WebUserControl dynamically ,and then i wanted to get it, here is my story :( i don't know how to do it , here is my code,
thanks in advance,
Protected Sub btngenerate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btngenerate.Click
For Each Str As String In Tstring
Dim addressControl As WebUC = CType(LoadControl("WebUC.ascx"), WebUC)
addressControl.plbl.Text = Str
form1.Controls.Add(addressControl)
Next
End Sub
Protected Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOk.Click
'here is what i did , but it didn't work
'For Each ct As WebUCIn form1.Controls
' ltlres.Text = ltlres.Text & ", " & ct.plbl.Text & " " & ct.ptxt.Text
'Next
End Sub
There is a rule to adding controls dynamically. You had to add them back on Init for as long as you need them.
Just adding them on a button click will show them the first time, but you will not receive any inputs from them.
You can keep a flag in the session to denote that they have to be added on Init
Because you added that control dynamically, when you post back, you'll need to add it again in order for its ViewState and postback data to be associated with it.
Re-create it in the Init event, and then when you process control events (like button clicks) it will exist and will have its data (such as the contents of its child controls) associated with it.
Since you're creating the control as a response to another event, you'll need to keep some kind of flag (a boolean? A counter?) in Session in order to know whether or not to re-create it on Init.

Event of dynamically created Control not firing

I'm having a problem with a Web Control that is dynamically created and inserted in my page. I create a couple of LinkButtons, depending on the data of the search that was made, and I'm trying to add an Event Handler to each of the Buttons, so it would filter the result.
The controls are initialized properly, but the event is never fired.
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
Controls.Clear()
Dim btn As Controls.LocalizableLinkButton
For Each element As Generic.KeyValuePair(Of String, ResultFilterData) In m_list
btn = New LocalizableLinkButton
btn.ID = m_Name & "$lnk" & count
btn.Label = element.Value.Label.Append(" (" + CStr(element.Value.Count) + ")")
btn.CommandArgument = element.Value.Key
AddHandler btn.Click, AddressOf Me.btn_Click
Controls.Add(btn)
Next
End Sub
Since this code is in Page_Init all the controls should be recreated on a postback. (The LocalizableLinkButton is just an extension of a LinkButton to add multilingual features to the text).
The problem is that the method btn_Click is never called. The Link Buttons are properly initialized on the callback, with the same ID's as before. But the event doesn't fire.
I'm using ASP.Net 2.0
Any ideas?
I finally figured out the problem ASP.NET had with my Link Buttons.
The error was in using a '$' sign in my ID for each LinkButton. ASP.NET apparently uses the $ sign to build the control hierarchy when it creates the Postback Javascript. Therefore it thinks that the LinkButtons are nested within a control that does not exist. And so the events aren't fired of course.
Once I removed the $ signs it worked properly.
You probably want to put this piece of code in the Page_Load and see. It's generally advised not to access controls in this Page_Init as there is no guarantee of the controls been created at this stage.
I'm no VB guy but i put this into the codebehind of the default.aspx and it works fine.
protected void Page_Load(object sender, EventArgs e)
{
Button button = new Button();
button.Click += new EventHandler(button_Click);
button.Text = "test";
Form.Controls.Add(button);
}
void button_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}

Deleting Dynamically Populated images from a Directory (NOT GridView) ASP.NET (VB)

The code below displays a thumbnail of each image in a specific server directory and when I click on the image it pops up a nice full sized picture. It works perfectly.
I would however, like to be able to delete an image. I first thought I could have a button at the bottom of the page with a checkbox next to each image, giving it a uniqueID as per the filename but as they are dynamically created I couldn’t figure how to handle the Click Event on the button for a randomly named Checkbox ID. Then I tried adding a button next to each item and then tried an OnClick & OnServerClick to call a Sub but this didn’t work either.
Any/All suggestions welcomed :)
Private Sub ImageList()
If Directory.Exists(Server.MapPath("JobImages\" & DBC_JOB_JobID.Text)) Then
Dim MySB As New StringBuilder
Dim dirInfo As New DirectoryInfo(Server.MapPath("JobImages\" & DBC_JOB_JobID.Text))
MySB.Append("<ul class=""clearfix"">")
MySB.AppendLine()
For Each File In dirInfo.GetFiles()
MySB.Append("<li><a rel=""jobpic"" href=""JobImages\" & DBC_JOB_JobID.Text & "\" & File.Name & """><img src=""JobImages\" & DBC_JOB_JobID.Text & "\Thumbs\" & File.Name & """ width=""150"" height=""100"" /> <span class=""size"">" & File.Name & " </span></a></li>")
MySB.AppendLine()
Next
MySB.Append("</ul>")
MySB.AppendLine()
lblMyPictures.Text = MySB.ToString
End If
End Sub
OK what Kendrick is talking about (basically) is using server side controls to keep track of which file to delete. What you are doing right now is dumping markup into a Label control, which on postback won't fire an event on the server side. However you can accomplish this easily with server side controls.
The basic idea is you use a container control such as a Panel and add each child control to it. Then you hook events to each row with data identifying that row (such as filename).
Markup:
<asp:Panel ID="pnlList" runat="server">
</asp:Panel>
Code-Behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Directory.Exists(Server.MapPath("Files")) Then
Dim objDirInfo As New DirectoryInfo(Server.MapPath("Files"))
For Each objFile As FileInfo In objDirInfo.GetFiles()
Dim objLabel As New Label
objLabel.Text = objFile.Name
Dim objLinkButton As New LinkButton
objLinkButton.Text = "Delete"
objLinkButton.CommandName = "Delete"
objLinkButton.CommandArgument = objFile.Name
AddHandler objLinkButton.Command, AddressOf DeleteFile
Dim objLiteral As New LiteralControl
objLiteral.Text = "<br/>"
pnlList.Controls.Add(objLabel)
pnlList.Controls.Add(objLinkButton)
pnlList.Controls.Add(objLiteral)
Next
End If
End Sub
Public Sub DeleteFile(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
If e.CommandName = "Delete" Then
Dim strFileName As String = Server.MapPath("Files\" & e.CommandArgument)
If File.Exists(strFileName) Then
Dim objFile As New FileInfo(strFileName)
objFile.Delete()
End If
End If
End Sub
This would be an excellent example of where using a data aware would make your life a lot easier.
That said, if you didn't want to use a server-side control, you could assign an ID to each checkbox (i.e. DeleteImage_1) and then store the ID and associated image name in the viewstate on the page. Go through the checked checkboxes and refer back to the viewstate for the name that goes with each ID when they click the delete button.

Incrementing variables in ASP.net on button click

I am new to asp.net. I am creating a ASP.net website using VB.net. So here's my problem
Dim myCounter as Integer = 0
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Button1.Click
myCounter = myCounter + 1
Label1.Text = myCounter.ToString()
end Sub
As expected I always get Label Text as 0 each time click the button. How to I create global variable and increment it.
Every time the page posts back, it is essentially starting over from scratch - anything initialized to 0, for example, will be zero again. This is because the server doesn't know anything about the last time the page ran - all it knows is you clicked a button which submits a form to that page, so it creates another instance of the page and starts again.
If you need to persist a value across postbacks, the standard method is to use ViewState:
Public Property MyCounter() As Integer
Get
Dim val As Object = ViewState("MyCounter")
Return If(val IsNot Nothing, CInt(val), 0)
End Get
Set(ByVal value As Integer)
ViewState("MyCounter") = value
End Set
End Property
It's also possible to use Session, which will persist the value across all pages and requests for the life of the user's session. For that to work, you can use the same sample above, replacing ViewState with Session.
Put this code in your Button Click Event
int count=0;
count++;
ViewState["count"] = Convert.ToInt32(ViewState["count"]) + count;
Label1.Text = ViewState["count"].ToString();
#Rex M's suggestion for using Viewstate is good.
If the counter is not sensitive information or something you're worried about someone tampering with., here's an easier idea:
You can also use an <asp:HiddenField> and store the value there. Then it will persist between postbacks and you can increment it each time..
Her's another method that doesn't use hidden field, viewstate, session or cache
Probably not something very 'safe' but probably saves you some time.
Assuming initial Label1.Text = 0
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Button1.Click
Label1.Text = (Integer.Parse(Label1.Text) + 1).ToString()
end Sub
your page class gets recreated on each request... so myCounter won't exist the next time.
you can either
make myCounter static (not a great idea)
put it in the Application, Session, or Cache collection
depends on what you're trying to do
You can use view count :---
Code on event of button_click..
ViewState["count"] = Convert.ToInt32(ViewState["count"])+1;
Label2.Text = "This button has been clicked " + ViewState["count"].ToString() + " times";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["Count"] = 0;
}
}
protected void btnCount_Click(object sender, EventArgs e)
{
ViewState["Count"] = (int)(ViewState["Count"]) + 1;
lblCount.Text = "Page Visited " +ViewState["Count"].ToString() +" times !";
//Response.Write(ViewState["Count"].ToString());
}

Resources