Showing posts with label form. Show all posts
Showing posts with label form. Show all posts

Saturday, March 31, 2012

the asp.net equivalent of the "Request.Form" in asp

i am having problems with a simple web service i am creating in asp.net using C#. does anybody know what Request.Form is in asp.net.
cheers
much appreciatedI've never done classic ASP code, but I think what you're looking for is Request.Params[]

Should still be Request.Form. What is the problem that you are having?


Hi,
Request.Form method was used in classic ASP(3.0)
<form action="hello.aspx" method="post">
Your name: <input type="text" name="fname" size="20">
<input type="submit" value="Submit">
</form>
<%
dim fname
fname=Request.Form("fname")
Response.Write("Hello " & fname)
%>
As in Asp.net forms are posted to itself So Request.Form was not actively used in asp.net.
Iam still now able to understand why you require this in web services.


You can still use Request.Form, but you'll have to make sure the value exists before trying to use it. In Classic ASP, if the value didn't exist it would return an empty string, but in ASP.NET you get Nothing (in VB.NET, which I believe is null in C#).

Wednesday, March 28, 2012

The Command event of dynamically loaded controls

Hi,

I noticed an interesting effect when working with controls that are
dynamically loaded. For instance, on a web form with a PlaceHolder control
named ImageHolder, I dynamically add an image button at runtime:

//-- Code snippet
protected System.Web.UI.WebControls.PlaceHolder ImageHolder;

private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
LoadDynamicImageButton();
}

private void ImageButton_Click(object sender,
System.Web.UI.ImageClickEventArgs e)
{
Response.Write("Image button clicked");
}

private void LoadDynamicImageButton()
{
ImageButton btn = new ImageButton();
btn.ImageUrl = "Images/Minus.png";
btn.Click += new ImageClickEventHandler(ImageButton_Click);
ImageHolder.Controls.Add(btn);
}
//-- End code snippet

The first time the page loads, the image button is created. When I click it,
it reloads the page but doesn't trigger its ImageClickEventHandler. If I
forcefully run LoadDynamicImageButton(), i.e., remove the IsPostBack check
in Page_Load() to recreate the image, its ImageClickEventHandler is
triggered. This happens with the Command event as well.

It seems that on post-back, if a dynamically loaded control is not loaded,
then its event handler is not wired. Its properties such as CommandName and
CommandArgument, OTOH, persists from the last load.

The problem is that if I dynamically load up the PlaceHolder control with
different controls according to the button clicked, this behavior forces all
those controls to be loaded twice - first to load all default controls just
to wire up their event handlers, then to reload them again according to the
event. There are also other factors, such as the assigning a differnet
ImageUrl, that seem to affect whether or not the event handler is triggered.
I'm still working on it to hopefully isolate the problem.

Is there a workaround?

Thanks,
Donald XieHi Donald,

Thanks for posting in the community!
From your description, you dynamically add some command controls such as
button or ImageButton into a webform within a placeholder.(in the page_load
event when the page is first loaded). Also, you registered a "Click" event
handler for the dynamicly added control. However, you found that when you
clicked the control , its event handler hadn't been called and if you did
the adding and registering event handler operation every time the page is
loaded in Page_load, it worked well, yes?

I've tested the code you provided and also tried using other controls such
as Button and did encoutnered the same problem. Currently, I am finding
proper resource to assist you and we will update as soon as posible. In the
meantime, if you have any new findings, please feel free to post here.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security(This posting is provided "AS IS",
with no warranties, and confers no rights.)
Hi Donald,

This is normal behavior and results from the way ASP.NET remembers the old
value for that text box in order to determine if the new value is different.

Each time the form is sent to the browser, ASP.NET stores the current text
box value (and other controls) in a hidden field which it sends to the
browser. When the browser posts the page back, the hidden field is sent to
the server along with the rest of the form. ASP.NET parses the list of old
values from the hidden field and attempts to associate each value with a
control. Then it compares the new value of the control with the old value
and triggers events.

The text box must be recreated to allow ASP.NET to associate it with the
old value from the hidden field. Only then can ASP.NET compare the new and
old values.

Here is a code sample which demonstrates one text box that correctly
triggers the changed event and three text boxes which fail for each of
three reasons.

**** HTML
<form id="Form1" method="post" runat="server">
<P>This sample contains a series of text boxes added to the page<BR>
programmatically with Controls.Add. The variations in these<BR>
text boxes demonstrate how to (and how not to) add a control<BR>
so that it can fire an event.<BR>
<BR>
</P>
<asp:panel id="Panel1" runat="server">
<P>
<asp:Label id="Label5" runat="server" Width="115px"> With
ViewState:</asp:Label>
<asp:PlaceHolder id="PlaceHolder1"
runat="server"></asp:PlaceHolder>
<asp:Label id="Label1" runat="server" Width="368px"
EnableViewState="False"></asp:Label></P>
<P>
<asp:Label id="Label6" runat="server" Width="115px" Height="19"> No
ViewState:</asp:Label>
<asp:PlaceHolder id="PlaceHolder2"
runat="server"></asp:PlaceHolder>
<asp:Label id="Label2" runat="server" Width="368px"
EnableViewState="False"></asp:Label></P>
<P>
<asp:Label id="Label7" runat="server" Width="115px"
Height="19px">Controls.AddAt:</asp:Label>
<asp:Label id="Label3" runat="server" Width="368px"
EnableViewState="False"></asp:Label></P>
<P>
<asp:Label id="Label8" runat="server" Width="115px"
Height="19px">!IsPostBack:</asp:Label>
<asp:PlaceHolder id="PlaceHolder4"
runat="server"></asp:PlaceHolder>
<asp:Label id="Label4" runat="server" Width="368px"
EnableViewState="False"></asp:Label></P>
</asp:panel>
<P><asp:button id="Button1" runat="server" Text="Submit" Width="100px"
Height="27px"></asp:button></P>
<P><hr></P>
<P>As you can see through experimenting with the above, the text<BR>
box labeled "With ViewState" is the only one that works properly.<BR>
<BR>
The "No ViewState" and the "Controls.AddAt" text boxes both<BR>
fire their changed events whenever they contain text, even if that<BR>
text has not changed.<BR>
<BR>
The "!IsPostBack" text box simply disappears upon postback.</P>
</form
**** CODE
private void Page_Load(object sender, System.EventArgs e)
{
System.Web.UI.WebControls.TextBox MyTextBox;

MyTextBox = new TextBox();
MyTextBox.ID = "TextBox1";
MyTextBox.EnableViewState=true;
PlaceHolder1.Controls.Add(MyTextBox);
MyTextBox.TextChanged += new
System.EventHandler(this.TextBox_TextChanged);

MyTextBox = new TextBox();
MyTextBox.ID = "TextBox2";
MyTextBox.EnableViewState=false;
PlaceHolder2.Controls.Add(MyTextBox);
MyTextBox.TextChanged += new
System.EventHandler(this.TextBox_TextChanged);

MyTextBox = new TextBox();
MyTextBox.ID = "TextBox3";
MyTextBox.EnableViewState=true;
Panel1.Controls.AddAt(15,MyTextBox);
MyTextBox.TextChanged += new
System.EventHandler(this.TextBox_TextChanged);

if(!IsPostBack)
{
MyTextBox = new TextBox();
MyTextBox.ID = "TextBox4";
MyTextBox.EnableViewState=true;
PlaceHolder4.Controls.Add(MyTextBox);
MyTextBox.TextChanged += new
System.EventHandler(this.TextBox_TextChanged);
}
}

private void TextBox_TextChanged(object sender, System.EventArgs e)
{
TextBox txtBoxSender = (TextBox)sender;
string strTextBoxID = txtBoxSender.ID;

switch(strTextBoxID)
{
case "TextBox1":
Label1.Text = "Changed";
break;
case "TextBox2":
Label2.Text = "Changed";
break;
case "TextBox3":
Label3.Text = "Changed";
break;
case "TextBox4":
Label4.Text = "Changed";
break;
}
}

--
Please see these articles for more information.

Adding Controls to a Web Forms Page Programmatically
http://msdn.microsoft.com/library/e...gcontrolstowebf
ormspageprogrammatically.asp

HOW TO: Dynamically Create Controls in ASP.NET by Using Visual C# .NET
http://support.microsoft.com/defaul...kb;EN-US;317794

Does this answer your question?

Thank you, Mike
Microsoft, ASP.NET Support Professional

Microsoft highly recommends to all of our customers that they visit the
http://www.microsoft.com/protect site and perform the three straightforward
steps listed to improve your computers security.

This posting is provided "AS IS", with no warranties, and confers no rights.

-------
> From: "Donald Xie" <donald_xie@dotnet.itags.org.msdn.nospam>
> Subject: The Command event of dynamically loaded controls
> Date: Fri, 30 Jan 2004 16:52:00 +0800
> Lines: 54
> X-Priority: 3
> X-MSMail-Priority: Normal
> X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
> X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
> Message-ID: <#C2U35w5DHA.2580@dotnet.itags.org.TK2MSFTNGP11.phx.gbl>
> Newsgroups: microsoft.public.dotnet.framework.aspnet
> NNTP-Posting-Host: 202.181.80.84
> Path:
cpmsftngxa07.phx.gbl!cpmsftngxa10.phx.gbl!TK2MSFTN GXA05.phx.gbl!TK2MSFTNGP08
.phx.gbl!TK2MSFTNGP11.phx.gbl
> Xref: cpmsftngxa07.phx.gbl microsoft.public.dotnet.framework.aspnet:206364
> X-Tomcat-NG: microsoft.public.dotnet.framework.aspnet
> Hi,
> I noticed an interesting effect when working with controls that are
> dynamically loaded. For instance, on a web form with a PlaceHolder control
> named ImageHolder, I dynamically add an image button at runtime:
> //-- Code snippet
> protected System.Web.UI.WebControls.PlaceHolder ImageHolder;
> private void Page_Load(object sender, System.EventArgs e)
> {
> if (!IsPostBack)
> LoadDynamicImageButton();
> }
> private void ImageButton_Click(object sender,
> System.Web.UI.ImageClickEventArgs e)
> {
> Response.Write("Image button clicked");
> }
> private void LoadDynamicImageButton()
> {
> ImageButton btn = new ImageButton();
> btn.ImageUrl = "Images/Minus.png";
> btn.Click += new ImageClickEventHandler(ImageButton_Click);
> ImageHolder.Controls.Add(btn);
> }
> //-- End code snippet
> The first time the page loads, the image button is created. When I click
it,
> it reloads the page but doesn't trigger its ImageClickEventHandler. If I
> forcefully run LoadDynamicImageButton(), i.e., remove the IsPostBack check
> in Page_Load() to recreate the image, its ImageClickEventHandler is
> triggered. This happens with the Command event as well.
> It seems that on post-back, if a dynamically loaded control is not loaded,
> then its event handler is not wired. Its properties such as CommandName
and
> CommandArgument, OTOH, persists from the last load.
> The problem is that if I dynamically load up the PlaceHolder control with
> different controls according to the button clicked, this behavior forces
all
> those controls to be loaded twice - first to load all default controls
just
> to wire up their event handlers, then to reload them again according to
the
> event. There are also other factors, such as the assigning a differnet
> ImageUrl, that seem to affect whether or not the event handler is
triggered.
> I'm still working on it to hopefully isolate the problem.
> Is there a workaround?
> Thanks,
> Donald Xie
Thanks for the excellent explanation, Mike. Yes that answers my question.

Now I'm trying to find a good solution for my problem. In a nutshell, I need
to load a hierarchical list of folders and files from a database and display
them on a tree - very much the same as the MSDN Library deeptree.asp. The
number of nodes is potentially large, so I'll only load all top level
folders plus folders in the branch selected by the user. Only one branch can
be expanded each time. My users can click a folder node to expand or
collapse it, based on the selected folder's state.

Since my client doesn't want to use a third party tree control, my first
thought i\was to programmatically create a list of ImageButton/LinkButton
pairs to display the folders. This dynamic control's behavior means that:

1. I'll need to load the folder list in the first pass to wire up the
controls and corresponding event handlers. After it's loaded, the event
handler will fire and give me the selected folder. Then,

2. I'll then load the folder list again with the selected folder
expanded/collapsed.

It doesn't seem like a very efficient solution now because it requires two
trips to the database to load the folder list. Caching doesn't sound very
attractive either because list can be quite big and changes frequently.

Any suggestions are very much appreciated.

Cheers,
Donald Xie

""Mike Moore [MSFT]"" <michmo@dotnet.itags.org.online.microsoft.com> wrote in message
news:AXcHok55DHA.3032@dotnet.itags.org.cpmsftngxa07.phx.gbl...
> Hi Donald,
> This is normal behavior and results from the way ASP.NET remembers the old
> value for that text box in order to determine if the new value is
different.
> Each time the form is sent to the browser, ASP.NET stores the current text
> box value (and other controls) in a hidden field which it sends to the
> browser. When the browser posts the page back, the hidden field is sent to
> the server along with the rest of the form. ASP.NET parses the list of old
> values from the hidden field and attempts to associate each value with a
> control. Then it compares the new value of the control with the old value
> and triggers events.
> The text box must be recreated to allow ASP.NET to associate it with the
> old value from the hidden field. Only then can ASP.NET compare the new and
> old values.
> Here is a code sample which demonstrates one text box that correctly
> triggers the changed event and three text boxes which fail for each of
> three reasons.
>
> **** HTML
> <form id="Form1" method="post" runat="server">
> <P>This sample contains a series of text boxes added to the page<BR>
> programmatically with Controls.Add. The variations in these<BR>
> text boxes demonstrate how to (and how not to) add a control<BR>
> so that it can fire an event.<BR>
> <BR>
> </P>
> <asp:panel id="Panel1" runat="server">
> <P>
> <asp:Label id="Label5" runat="server" Width="115px"> With
> ViewState:</asp:Label>
> <asp:PlaceHolder id="PlaceHolder1"
> runat="server"></asp:PlaceHolder>
> <asp:Label id="Label1" runat="server" Width="368px"
> EnableViewState="False"></asp:Label></P>
> <P>
> <asp:Label id="Label6" runat="server" Width="115px" Height="19"> No
> ViewState:</asp:Label>
> <asp:PlaceHolder id="PlaceHolder2"
> runat="server"></asp:PlaceHolder>
> <asp:Label id="Label2" runat="server" Width="368px"
> EnableViewState="False"></asp:Label></P>
> <P>
> <asp:Label id="Label7" runat="server" Width="115px"
> Height="19px">Controls.AddAt:</asp:Label>
> <asp:Label id="Label3" runat="server" Width="368px"
> EnableViewState="False"></asp:Label></P>
> <P>
> <asp:Label id="Label8" runat="server" Width="115px"
> Height="19px">!IsPostBack:</asp:Label>
> <asp:PlaceHolder id="PlaceHolder4"
> runat="server"></asp:PlaceHolder>
> <asp:Label id="Label4" runat="server" Width="368px"
> EnableViewState="False"></asp:Label></P>
> </asp:panel>
> <P><asp:button id="Button1" runat="server" Text="Submit" Width="100px"
> Height="27px"></asp:button></P>
> <P><hr></P>
> <P>As you can see through experimenting with the above, the text<BR>
> box labeled "With ViewState" is the only one that works
properly.<BR>
> <BR>
> The "No ViewState" and the "Controls.AddAt" text boxes both<BR>
> fire their changed events whenever they contain text, even if
that<BR>
> text has not changed.<BR>
> <BR>
> The "!IsPostBack" text box simply disappears upon postback.</P>
> </form>
>
> **** CODE
> private void Page_Load(object sender, System.EventArgs e)
> {
> System.Web.UI.WebControls.TextBox MyTextBox;
> MyTextBox = new TextBox();
> MyTextBox.ID = "TextBox1";
> MyTextBox.EnableViewState=true;
> PlaceHolder1.Controls.Add(MyTextBox);
> MyTextBox.TextChanged += new
> System.EventHandler(this.TextBox_TextChanged);
> MyTextBox = new TextBox();
> MyTextBox.ID = "TextBox2";
> MyTextBox.EnableViewState=false;
> PlaceHolder2.Controls.Add(MyTextBox);
> MyTextBox.TextChanged += new
> System.EventHandler(this.TextBox_TextChanged);
> MyTextBox = new TextBox();
> MyTextBox.ID = "TextBox3";
> MyTextBox.EnableViewState=true;
> Panel1.Controls.AddAt(15,MyTextBox);
> MyTextBox.TextChanged += new
> System.EventHandler(this.TextBox_TextChanged);
> if(!IsPostBack)
> {
> MyTextBox = new TextBox();
> MyTextBox.ID = "TextBox4";
> MyTextBox.EnableViewState=true;
> PlaceHolder4.Controls.Add(MyTextBox);
> MyTextBox.TextChanged += new
> System.EventHandler(this.TextBox_TextChanged);
> }
> }
> private void TextBox_TextChanged(object sender, System.EventArgs e)
> {
> TextBox txtBoxSender = (TextBox)sender;
> string strTextBoxID = txtBoxSender.ID;
> switch(strTextBoxID)
> {
> case "TextBox1":
> Label1.Text = "Changed";
> break;
> case "TextBox2":
> Label2.Text = "Changed";
> break;
> case "TextBox3":
> Label3.Text = "Changed";
> break;
> case "TextBox4":
> Label4.Text = "Changed";
> break;
> }
> }
>
> --
> Please see these articles for more information.
> Adding Controls to a Web Forms Page Programmatically
http://msdn.microsoft.com/library/e...gcontrolstowebf
> ormspageprogrammatically.asp
> HOW TO: Dynamically Create Controls in ASP.NET by Using Visual C# .NET
> http://support.microsoft.com/defaul...kb;EN-US;317794
> Does this answer your question?
> Thank you, Mike
> Microsoft, ASP.NET Support Professional
> Microsoft highly recommends to all of our customers that they visit the
> http://www.microsoft.com/protect site and perform the three
straightforward
> steps listed to improve your computers security.
> This posting is provided "AS IS", with no warranties, and confers no
rights.
>
> -------
> > From: "Donald Xie" <donald_xie@dotnet.itags.org.msdn.nospam>
> > Subject: The Command event of dynamically loaded controls
> > Date: Fri, 30 Jan 2004 16:52:00 +0800
> > Lines: 54
> > X-Priority: 3
> > X-MSMail-Priority: Normal
> > X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
> > X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
> > Message-ID: <#C2U35w5DHA.2580@dotnet.itags.org.TK2MSFTNGP11.phx.gbl>
> > Newsgroups: microsoft.public.dotnet.framework.aspnet
> > NNTP-Posting-Host: 202.181.80.84
> > Path:
cpmsftngxa07.phx.gbl!cpmsftngxa10.phx.gbl!TK2MSFTN GXA05.phx.gbl!TK2MSFTNGP08
> phx.gbl!TK2MSFTNGP11.phx.gbl
> > Xref: cpmsftngxa07.phx.gbl
microsoft.public.dotnet.framework.aspnet:206364
> > X-Tomcat-NG: microsoft.public.dotnet.framework.aspnet
> > Hi,
> > I noticed an interesting effect when working with controls that are
> > dynamically loaded. For instance, on a web form with a PlaceHolder
control
> > named ImageHolder, I dynamically add an image button at runtime:
> > //-- Code snippet
> > protected System.Web.UI.WebControls.PlaceHolder ImageHolder;
> > private void Page_Load(object sender, System.EventArgs e)
> > {
> > if (!IsPostBack)
> > LoadDynamicImageButton();
> > }
> > private void ImageButton_Click(object sender,
> > System.Web.UI.ImageClickEventArgs e)
> > {
> > Response.Write("Image button clicked");
> > }
> > private void LoadDynamicImageButton()
> > {
> > ImageButton btn = new ImageButton();
> > btn.ImageUrl = "Images/Minus.png";
> > btn.Click += new ImageClickEventHandler(ImageButton_Click);
> > ImageHolder.Controls.Add(btn);
> > }
> > //-- End code snippet
> > The first time the page loads, the image button is created. When I click
> it,
> > it reloads the page but doesn't trigger its ImageClickEventHandler. If I
> > forcefully run LoadDynamicImageButton(), i.e., remove the IsPostBack
check
> > in Page_Load() to recreate the image, its ImageClickEventHandler is
> > triggered. This happens with the Command event as well.
> > It seems that on post-back, if a dynamically loaded control is not
loaded,
> > then its event handler is not wired. Its properties such as CommandName
> and
> > CommandArgument, OTOH, persists from the last load.
> > The problem is that if I dynamically load up the PlaceHolder control
with
> > different controls according to the button clicked, this behavior forces
> all
> > those controls to be loaded twice - first to load all default controls
> just
> > to wire up their event handlers, then to reload them again according to
> the
> > event. There are also other factors, such as the assigning a differnet
> > ImageUrl, that seem to affect whether or not the event handler is
> triggered.
> > I'm still working on it to hopefully isolate the problem.
> > Is there a workaround?
> > Thanks,
> > Donald Xie
Hi Donald,

Thank you for the response. Regarding on the issue, we are
finding proper resource to assist you and we will update as soon as posible.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security(This posting is provided "AS IS",
with no warranties, and confers no rights.)
Hi Donald,

As for the situation you mentioned in the last reply, here is my
suggestions on it:
1. If we manually build a "tree" programatically via a list of ImageButtons
or LinkButtons, I'm afraid there will cause some performance issues since
every time page loaded , it need to create and add these dynamic controls
so as to associate their states from viewstate, also register the event
handler for them. This will be a large challenge to the serverside.

2. Would you like to have a try on the TreeView control in the Microsoft
Internet Explorer WebControls? This treeview control has been added to the
MS's web control collections and have detailed reference and tutorial in
MSDN. Also, the IE webcontrols' source code is opened to public , you're
feel to extend their existed functions. Here is some tech references and
articls on the TreeView web control:

#TreeView WebControl Reference
http://msdn.microsoft.com/library/e...ingtreeviewiewe
bcontrol.asp?frame=true

And here is a test page I used to test dynamically add nodes when a certain
node is expanded. The treeview has
4 hierarchies and each contains 20 nodes. When a node is first time
expanded or selected, it dynamically add its child nodes. Please have a
look to see whether it possible for you to use this TreeView control.

In addition, if you have the "Application Center Test" installed, you may
try having a test on different approachs such as using TreeView or manually
add button lists so as to see the realtime performance. And here are
another two tech articles, one is about the MSDN site's TreeView 's
implementation in C#. I think they may be helpful to you,too.

#Hierarchical Data Binding in ASP.NET
http://msdn.microsoft.com/library/e...databinding.asp
?frame=true

#The MSDN Table of Contents in C#
http://msdn.microsoft.com/library/e...001.asp?frame=t
rue

Please check out the above suggestions. If you have any questions or if my
suggestions not quite suitable for your situation, please feel free to post
here.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
Hi Donald,

Sorry for forgetting attach My test page's code in the last reply, here is
the Page code:
#If you haven't the IE web control's reference or code, you may get them at
http://www.asp.net/ControlGallery/C...l=75&tabindex=2

----------aspx page-----------
<%@dotnet.itags.org. Register TagPrefix="iewc" Namespace="Microsoft.Web.UI.WebControls"
Assembly="Microsoft.Web.UI.WebControls" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DynaTree</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table width="500" align="center">
<tr>
<td><FONT face="">
<iewc:TreeView id="trvMain"
runat="server"></iewc:TreeView></FONT></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</form>
</body>
</HTML
--------code behind class-----
public class DynaTree : System.Web.UI.Page
{
protected Microsoft.Web.UI.WebControls.TreeView trvMain;

private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
LoadData();
BindTreeNodes(trvMain.Nodes,GetChildNodes("0"));
trvMain.AutoPostBack = true;
}
}

protected void LoadData()
{
DataTable tb = new DataTable();
tb.Columns.Add("nid");
tb.Columns.Add("pid");
tb.Columns.Add("name");
tb.Columns.Add("url");
tb.Columns.Add("target");

int i=0;
int j=0;
int k=0;
int l=0;
int nodeindex = 1;

for(i=1;i<=20;i++)
{
DataRow row1 = tb.NewRow();
row1["nid"] = i.ToString();
row1["pid"] = "0";
row1["name"] = "FirstLevelNode_"+nodeindex.ToString();
row1["url"] = "";
row1["target"] = "";
tb.Rows.Add(row1);

for(j=1;j<=20;j++)
{

DataRow row2 = tb.NewRow();
row2["nid"] = i.ToString() + j.ToString();
row2["pid"] = i.ToString();
row2["name"] = "SecondLevelNode_"+j.ToString();
row2["url"] = "";
row2["target"] = "";
tb.Rows.Add(row2);

for(k=1;k<=20;k++)
{

DataRow row3 = tb.NewRow();
row3["nid"] = i.ToString() + j.ToString() + k.ToString();
row3["pid"] = i.ToString() + j.ToString();
row3["name"] = "ThirdLevelNode_"+k.ToString();
row3["url"] = "";
row3["target"] = "";
tb.Rows.Add(row3);

for(l=1;l<20;l++)
{
DataRow row4 = tb.NewRow();
row4["nid"] = i.ToString() + j.ToString() + k.ToString() +
l.ToString();
row4["pid"] = i.ToString() + j.ToString() + k.ToString();
row4["name"] = "ForthLevelNode_"+k.ToString();
row4["url"] = "";
row4["target"] = "";
tb.Rows.Add(row4);
}

}
}
}

Session["TEMP_DATA"] = tb;

}

protected DataRow[] GetChildNodes(string pid)
{
DataTable tb = (DataTable)Session["TEMP_DATA"];
DataRow[] rows = tb.Select("pid = '" + pid +"'");

return rows;
}

protected void BindTreeNodes(TreeNodeCollection nodes, DataRow[] rows)
{

for(int i=0;i<rows.Length;i++)
{
TreeNode node = new TreeNode();
node.ID = rows[i]["nid"].ToString();
node.Text = rows[i]["name"].ToString();
node.NavigateUrl = rows[i]["url"].ToString();
node.Target = rows[i]["target"].ToString();

TreeNode emptynode = new TreeNode();
emptynode.ID = node.ID + "#$#EMPTY";

node.Nodes.Add(emptynode);
nodes.Add(node);
}

}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{

InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.trvMain.Expand += new
Microsoft.Web.UI.WebControls.ClickEventHandler(thi s.trvMain_Expand);
this.trvMain.SelectedIndexChange += new
Microsoft.Web.UI.WebControls.SelectEventHandler(th is.trvMain_SelectedIndexCh
ange);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void trvMain_Expand(object sender,
Microsoft.Web.UI.WebControls.TreeViewClickEventArg s e)
{
TreeNode pnode = ((TreeView)sender).GetNodeFromIndex(e.Node);
TreeNode emptynode = pnode.Nodes[0];

if(emptynode.ID.IndexOf("#$#EMPTY") != -1)
{
pnode.Nodes.Clear();
BindTreeNodes(pnode.Nodes,GetChildNodes(pnode.ID)) ;
}

}

private void trvMain_SelectedIndexChange(object sender,
Microsoft.Web.UI.WebControls.TreeViewSelectEventAr gs e)
{
TreeNode oldnode = ((TreeView)sender).GetNodeFromIndex(e.OldNode);
TreeNode newnode = ((TreeView)sender).GetNodeFromIndex(e.NewNode);

if(newnode.Nodes.Count>0)
{
TreeNode emptynode = newnode.Nodes[0];

if(emptynode.ID.IndexOf("#$#EMPTY") != -1)
{
newnode.Nodes.Clear();
BindTreeNodes(newnode.Nodes,GetChildNodes(newnode. ID));
}
}

}

}
Hi Steven,

Thanks so much for your suggestions and the sample code - they are exactly
the information I need.

The TreeView control is the more conventional, and the MSDN TOC in C# is
very elegant and certainly well proven. I will go through both to see which
is the best for this application.

The hierarchical data binding approach is in essense what I'm doing
manually, as the depth of each node is variable. However I suspect that it
also suffers the same render-twice problem if we want to do more than just
displaying the nodes and get their state on post back.

Best,
Donald Xie

"Steven Cheng[MSFT]" <v-schang@dotnet.itags.org.online.microsoft.com> wrote in message
news:8JbKxSx6DHA.3524@dotnet.itags.org.cpmsftngxa07.phx.gbl...
> Hi Donald,
>
> As for the situation you mentioned in the last reply, here is my
> suggestions on it:
> 1. If we manually build a "tree" programatically via a list of
ImageButtons
> or LinkButtons, I'm afraid there will cause some performance issues since
> every time page loaded , it need to create and add these dynamic controls
> so as to associate their states from viewstate, also register the event
> handler for them. This will be a large challenge to the serverside.
> 2. Would you like to have a try on the TreeView control in the Microsoft
> Internet Explorer WebControls? This treeview control has been added to the
> MS's web control collections and have detailed reference and tutorial in
> MSDN. Also, the IE webcontrols' source code is opened to public , you're
> feel to extend their existed functions. Here is some tech references and
> articls on the TreeView web control:
> #TreeView WebControl Reference
http://msdn.microsoft.com/library/e...ingtreeviewiewe
> bcontrol.asp?frame=true
> And here is a test page I used to test dynamically add nodes when a
certain
> node is expanded. The treeview has
> 4 hierarchies and each contains 20 nodes. When a node is first time
> expanded or selected, it dynamically add its child nodes. Please have a
> look to see whether it possible for you to use this TreeView control.
> In addition, if you have the "Application Center Test" installed, you may
> try having a test on different approachs such as using TreeView or
manually
> add button lists so as to see the realtime performance. And here are
> another two tech articles, one is about the MSDN site's TreeView 's
> implementation in C#. I think they may be helpful to you,too.
> #Hierarchical Data Binding in ASP.NET
http://msdn.microsoft.com/library/e...databinding.asp
> ?frame=true
> #The MSDN Table of Contents in C#
http://msdn.microsoft.com/library/e...001.asp?frame=t
> rue
>
> Please check out the above suggestions. If you have any questions or if my
> suggestions not quite suitable for your situation, please feel free to
post
> here.
>
> Regards,
> Steven Cheng
> Microsoft Online Support
> Get Secure! www.microsoft.com/security
> (This posting is provided "AS IS", with no warranties, and confers no
> rights.)
Hi Donald,

Thanks for your response. I'm glad that my suggestions are helpful to you.
As for the things I mentioned in the last reply, here some of my further
suggestions:
As for the "MSDN TOC in C#", since it is not provided as a Web Server
Control and the DataSource is based on serveral xml files. If you'd like to
use this means, I think you may try dynamically generic the certain XML
files from your own datasource. That'll save your times.

Anyway, which approach to choose all depends on the real time performance.
Hope you'll soon figure out the most appropriate means.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Monday, March 26, 2012

The control values are not sent to the form code.

I am new to Web Forms and I ported my little app from Windows Forms to
ASP.NET and I am wondering why some things are not working as before.
Although I figured most of them, one of them is that on my form I have input
fields and a button causing to store all the input fields into the database.
However, when in the button OnClick event I gather all the form control
values by either getting txtBox.Text or lstChoice.SelectedItem, all the
values are not equal to the user choices, but to the values last set by the
form programatically on Form Load. It looks that I am missing some event tha
t
sends the user control values from the client to the server.
Am I missing something?
Thank you
Cezar MartCezar:
Take a look at http://openmymind.net/FAQ.aspx?documentId=2
short answer is you need to wrap the code which initially sets the values in
a if not page.IsPostback then
Karl
MY ASP.Net tutorials
http://www.openmymind.net/ - New and Improved (yes, the popup is annoying)
http://www.openmymind.net/faq.aspx - unofficial newsgroup FAQ (more to
come!)
"Cezar" <Cezar@dotnet.itags.org.discussions.microsoft.com> wrote in message
news:E8548106-843F-4252-A39F-4C40BC63774B@dotnet.itags.org.microsoft.com...
> I am new to Web Forms and I ported my little app from Windows Forms to
> ASP.NET and I am wondering why some things are not working as before.
> Although I figured most of them, one of them is that on my form I have
input
> fields and a button causing to store all the input fields into the
database.
> However, when in the button OnClick event I gather all the form control
> values by either getting txtBox.Text or lstChoice.SelectedItem, all the
> values are not equal to the user choices, but to the values last set by
the
> form programatically on Form Load. It looks that I am missing some event
that
> sends the user control values from the client to the server.
> Am I missing something?
> Thank you
> Cezar Mart
>

The control values are not sent to the form code.

I am new to Web Forms and I ported my little app from Windows Forms to
ASP.NET and I am wondering why some things are not working as before.
Although I figured most of them, one of them is that on my form I have input
fields and a button causing to store all the input fields into the database.
However, when in the button OnClick event I gather all the form control
values by either getting txtBox.Text or lstChoice.SelectedItem, all the
values are not equal to the user choices, but to the values last set by the
form programatically on Form Load. It looks that I am missing some event that
sends the user control values from the client to the server.
Am I missing something?
Thank you
Cezar MartCezar:
Take a look at http://openmymind.net/FAQ.aspx?documentId=2

short answer is you need to wrap the code which initially sets the values in
a if not page.IsPostback then

Karl

--
MY ASP.Net tutorials
http://www.openmymind.net/ - New and Improved (yes, the popup is annoying)
http://www.openmymind.net/faq.aspx - unofficial newsgroup FAQ (more to
come!)

"Cezar" <Cezar@dotnet.itags.org.discussions.microsoft.com> wrote in message
news:E8548106-843F-4252-A39F-4C40BC63774B@dotnet.itags.org.microsoft.com...
> I am new to Web Forms and I ported my little app from Windows Forms to
> ASP.NET and I am wondering why some things are not working as before.
> Although I figured most of them, one of them is that on my form I have
input
> fields and a button causing to store all the input fields into the
database.
> However, when in the button OnClick event I gather all the form control
> values by either getting txtBox.Text or lstChoice.SelectedItem, all the
> values are not equal to the user choices, but to the values last set by
the
> form programatically on Form Load. It looks that I am missing some event
that
> sends the user control values from the client to the server.
> Am I missing something?
> Thank you
> Cezar Mart

The conversion of a char data type to a datetime data type resulted....

Hi,

I'm trying to insert a date time value into a SQL Server Database field of type date time using a c# web form.
I get the following error...
"The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated"

My SQL looks like this:


INSERT INTO tblname (fldname) VALUES ('" + DateTime.Now.ToString() + "')"

What am I doing wrong?Remove the ToString() method as that is changing the DateTime type to a string (or Char type) ...at least thats what it looks like.
Nope sorry to say that didn't work.

My C# now looks like


SqlConnection myConn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["eTeam_ConnectionString"].ToString());
string mySQL = "INSERT INTO tblname (datestamp) VALUES ('" + DateTime.Now + "')";
SqlCommand myCMD = new SqlCommand(mySQL, myConn);
myConn.Open();
myCMD.ExecuteNonQuery();
myConn.Close();
myCMD.Dispose();
myConn.Dispose();

And the field 'datestamp' is a SQL Server Data Type datetime

Anyone else?
You can use getDate() method of SQL server to update date.

INSERT INTO tblname (datestamp) VALUES (getDate())";
Thanks for that - definately half way to solving my problem.
What if I need to take a value from an ASP:Calendar control?
Is there a ToDate() function that will convert it as required?
You can use

Calendar1.SelectedDate.ToShortDateString())

which will convert this date into short date format.

Saturday, March 24, 2012

The difference between Postback and CallBack ?

I know that Postback referring to the action users click a button to submit the form data.

In what situations do we say mention thecallbackaction?

(I found that there is a property Page.IsCallBack)

Regards,

Ricky

Hi there,

The difference between a callback and postback is that, as with a postback, a callback does not refresh the currently viewed page (i.e. does not redraw the page). You can think of it as a quick trip back to get some data etc. For example if there were two drop down boxes, the second dependant on the value of the first, when a user selects a value of a the first, rather then posting the whole page, doing some server side calculations and returning a new whole page to the client, a callback can enable you to only go fetch the required data. Obviously from this, View State is not updated with a callback (it's the same instance of the page just updated!!!).

Hope this helps.


Tom thats a good answer to the original posters question. So am I right in thinking callback are the core of the whole AJAX craze. I'm learning ajax at the moment, not ajax.net for just the regular ajax fundamentals and what you've sais about only fetching required date seems to ring a bell.

Also can callaback be implemented without the use of the .net ajax framework?


Hi,

Altough similar in end results to what can be achieved with AJAX (but limited compared to ajax) the callback functionality is not part of its framework and is a feature of just .NET 2.0 (other options avaialble with 1.1). Try the following article for more information it puts the difference between callback functionalty and AJAX into context.

http://www.geekpedia.com/tutorial155_ASP.NET-2.0-Script-CallBack-(Ajax-like).html

Thanks


i dont know it may help you or not... just check out this

This feature allows you to programmatically call server-side methods through client-side JavaScript code without the need for posting back the page.

http://dotnetjunkies.com/Article/E80EC96F-1C32-4855-85AE-9E30EECF13D7.dcik

with good sample


Thanks a lot, Tom.

Ricky.

The directory name is invalid

In VS2005 I drop a button and a dropdownlist on a web form.
When I try to change the name of these (i.e. from Button1 to btnEdit)
in the Properties panel, I get a message popping up saying "The
directory name is invalid." and it won't let me change the
name.
Any Ideas?Actually I had a problem like that once with the Beta program, I closed the
solution, open again and I was able to rename it, what version of the VS2005
are you running and did you try that?
Cheers
Al
"jhcorey@.yahoo.com" wrote:

> In VS2005 I drop a button and a dropdownlist on a web form.
> When I try to change the name of these (i.e. from Button1 to btnEdit)
> in the Properties panel, I get a message popping up saying "The
> directory name is invalid." and it won't let me change the
> name.
> Any Ideas?
>

The directory name is invalid

In VS2005 I drop a button and a dropdownlist on a web form.
When I try to change the name of these (i.e. from Button1 to btnEdit)
in the Properties panel, I get a message popping up saying "The
directory name is invalid." and it won't let me change the
name.
Any Ideas?Actually I had a problem like that once with the Beta program, I closed the
solution, open again and I was able to rename it, what version of the VS2005
are you running and did you try that?

Cheers
Al

"jhcorey@.yahoo.com" wrote:

> In VS2005 I drop a button and a dropdownlist on a web form.
> When I try to change the name of these (i.e. from Button1 to btnEdit)
> in the Properties panel, I get a message popping up saying "The
> directory name is invalid." and it won't let me change the
> name.
> Any Ideas?
>

The easiest way to save data into a text file on server side - Help me please

Embarrassed

Hi guys, I'm new at ASP and all I wanna know is, what is the simplest code for gathering info from my website visitors (using the FORM object) and saving it to a text file (*.TXT) on the web server? The whole procedure. I know it's lame, but is there anyone out there, that could help me with this one? Thanks guys.

Andrew

You could do something like the following. Here txtName and txtAddress are textboxes. Similarly you can add all the controls that you want to save.

The collected data is saved in the current directory on the webserver in a file called Test.txt. All subsequent saves will be appended to the same file (change the last parameter
to false to overwrite on every save)

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim s As String
s += txtName.Text + vbCrLf
s += txtAddress.Text + vbCrLf
My.Computer.FileSystem.WriteAllText(Server.MapPath("Test.txt"), s, True)

end sub

Thursday, March 22, 2012

The files are downloaded with the html code at the end of them

I have a code that download files form a folder to the client:

Try
Response.AddHeader("Content-Disposition", "attachment;filename=" & strFileName)
Dim fs As FileStream = New FileStream("C:\text.txt", FileMode.Open, FileAccess.Read)
Dim fileData As Byte()
ReDim fileData(fs.Length)
Dim bytesRead As Long = fs.Read(fileData, 0, CInt(fs.Length))
fs.Close()
Response.BinaryWrite(fileData)
Catch es as Exception
lblAlert.text = "It was a problem transferring the file."
end try

The problem is that if you open the files with 'notepad' you see that the html code of the page has been incorporated to the end of the file. Something like this:

***************Beginning of the file***************
0000114099 00000 n
0000114243 00000 n
0000114317 00000 n
trailer<</Size 62/ID<79e93880650e9d343ab0837ab878f5cd><79e93880650e9d343ab0837ab878f5cd>]>>
startxref 173 %%EOF
<html>
<head>
<title>HLC Intranet - HLC Eroom</title>
***************rest of the html code***************

Somebody knows what can be? How can I takeout the html code?

Thanks,

BriegaHi,

I presume this is some code-behind code. Check if there is still some html code in your page (this is created automatically when you create a new webform in vs.net). Delete the html code and only leave the Page-directive.

I struggled with this issue also last year and this is what worked for me:


Response.Clear()
Response.ContentType = scan.ContentType
Response.BinaryWrite(scan.Document)
Response.End()

Grz, Kris.
It works!!!

The only part of your code that I don't understand is the


Response.BinaryWrite(scan.Document)

Could you tell me what that does? I've copy the code without it and it works anyway.

Regards,

Briega
Sorry I typed wrong!

What I don't understand is:


Response.ContentType = scan.ContentType

Briega
I'm sorry, I took a little snippet out of my code. scan is an instantiation of a custom made class which retrieves the binary data and it's accompanying contenttype (pdft, excell, word, ...)

You can search for the content types on the internet.

Grz, Kris.

the form is valid, now what?

Ok, I've got my form working. The validation works, now how do I get to the next page when the form data is valid?Never mind. I do my processing in Page.IsPostBack and then do a redirect.