473,405 Members | 2,287 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

How can I pass more than one arguement to a function via <asp:linkbutton> ?

Hello

Could anyone please explain how I can pass more than one
arguement/parameter value to a function using <asp:linkbutton> or is
this a major shortfall of the language ?

Consider the following code fragments in which I want to list through
all files on a directory with a link to download each file by passing
a filename and whether or not to force the download dialog box to
appear.

Codebehind

public void DownloadFile(string fname,bool forceDownload)
{
.....
.....
}

<script language="C#" runat="server">

void CommandBtn_Click(Object sender, CommandEventArgs e)
{
DownloadFile(e.CommandArgument,???);
}
</script>
<asp:linkbutton id="LinkButton2"
style="Z-INDEX: 101; LEFT: 136px; POSITION: absolute; TOP: 200px"
OnCommand="CommandBtn_Click" runat="server"
CommandArgument="test.doc" Width="240px" Height="48px"
CommandName="FileName">LinkButton</asp:linkbutton>
Nov 15 '05 #1
5 3731
Fresh Air Rider wrote:
DownloadFile(e.CommandArgument,???);


The DownloadFile method itself must accept more than one parameter. If it
does not, there is no way to pass more than one.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
Nov 15 '05 #2
Fr*************@Hotmail.com (Fresh Air Rider) wrote:
Hello

Could anyone please explain how I can pass more than one
arguement/parameter value to a function using <asp:linkbutton> or is
this a major shortfall of the language ?

Consider the following code fragments in which I want to list through
all files on a directory with a link to download each file by passing
a filename and whether or not to force the download dialog box to
appear.

Codebehind

public void DownloadFile(string fname,bool forceDownload)
{
.....
.....
}

<script language="C#" runat="server">

void CommandBtn_Click(Object sender, CommandEventArgs e)
{
DownloadFile(e.CommandArgument,???);
}
</script>
<asp:linkbutton id="LinkButton2"
style="Z-INDEX: 101; LEFT: 136px; POSITION: absolute; TOP: 200px"
OnCommand="CommandBtn_Click" runat="server"
CommandArgument="test.doc" Width="240px" Height="48px"
CommandName="FileName">LinkButton</asp:linkbutton>
"major shortfall" is probably a bit strong; an “inconvenience” maybe.

You have several options at your disposal:
OPTION1: use different CommandNames, e.g.:

<asp:linkbutton id="LinkButton1" OnCommand="CommandBtn_Click" CommandName="DownloadFile" CommandArgument="test1.doc" …LinkButton1</asp:linkbutton>
<asp:linkbutton id="LinkButton2" OnCommand="CommandBtn_Click" CommandName="DownloadForce" CommandArgument="test2.doc" …LinkButton2</asp:linkbutton>
public void DownloadFile(string fname,bool forceDownload) {
.....
}

void CommandBtn_Click(object sender, CommandEventArgs e) {
bool forceDownload =
(e.CommandName == “DownloadForce”) ? true : false;
DownloadFile((string)e.CommandArgument, forceDownload );
}
OPTION2: use different CommandEventHandlers, e.g.:

<asp:linkbutton id="LinkButton1" OnCommand="CommandBtn_Click" CommandName="FileName" CommandArgument="test1.doc" …LinkButton1</asp:linkbutton>
<asp:linkbutton id="LinkButton2" OnCommand="CommandForceBtn_Click" CommandName="FileName" CommandArgument="test2.doc" …LinkButton2</asp:linkbutton>


public void DownloadFile(string fname,bool forceDownload) {
.....
}

void CommandBtn_Click(object sender, CommandEventArgs e) {
DownloadFile((string)e.CommandArgument, false );
}

void CommandForceBtn_Click(object sender, CommandEventArgs e) {
DownloadFile((string)e.CommandArgument, true );
}

OPTION3: You can stuff your arguments into that single CommandArgument. It can be as simple as a delimited string or as complex as
an XML document. This is most suitable if you create the LinkButtons dynamically. Example:

<!-- DynamicButtons.aspx -->
<%@ Page language="c#" Codebehind="DynamicButtons.aspx.cs" AutoEventWireup="false" Inherits="LbtnArg.DynamicButtons" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DynamicButtons</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:panel id="pnlLinks" runat="server" Height="312px" Width="528px"></asp:panel></form>
</body>
</HTML>

// DynamicButtons.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace LbtnArg {
public class DynamicButtons : System.Web.UI.Page {

protected System.Web.UI.WebControls.Panel pnlLinks;

// Page_Load dynamically adds LinkButtons to the panel
// for each xml, txt, html, zip file in the specified directory
// and prepares the command arguments
private void Page_Load(object sender, System.EventArgs e){

// Attributes of directories or filed we do not want
const FileAttributes excludeMask =
FileAttributes.Directory
| FileAttributes.Hidden
| FileAttributes.Temporary
| FileAttributes.System
| FileAttributes.Encrypted;

// Types of file we want to show
Regex includeTypes = new Regex(
@"^\.(xml)|(html)|(txt)|(zip)$",
RegexOptions.IgnoreCase
);

// Get all the items in the directory
DirectoryInfo di = new DirectoryInfo(".");
FileSystemInfo[] fsi = di.GetFileSystemInfos();

foreach( FileSystemInfo info in fsi ){

// Don't list directories or files with
// undesirable attributes
if( (info.Attributes & excludeMask) != 0)
continue;

// Only list specific types
if( ! includeTypes.IsMatch(info.Extension) )
continue;

// Add the link button for the file
LinkButton linkButton = new LinkButton();
linkButton.Text = info.Name;
if( info.Extension.ToLower() == ".zip" ){
linkButton.Command += new CommandEventHandler( DownloadDialog );
linkButton.CommandName = "DOWNLOADDIALOG";
} else {
linkButton.Command += new CommandEventHandler( DownloadSimple );
linkButton.CommandName = "DOWNLOADSIMPLE";
}
linkButton.CommandArgument = ArgToString( info );
pnlLinks.Controls.Add( linkButton );

// add a <br>
HtmlControl lcBreak = new HtmlGenericControl("br");
pnlLinks.Controls.Add( lcBreak );

} // end foreach item in the directory

} // end EventHandler DynamicButtons.Page_Load

// Both CommandEventHandlers delegate the actual
// work the DownloadFile method.

// CommandEventHandler which hardcodes the bool
// parameter to "true"
protected void DownloadSimple(
object sender,
CommandEventArgs e
){
// Call DownloadFile
// hardcoding the bool parameter to "true"
DownloadFile(
e.CommandName,
(string)e.CommandArgument,
true
);
} // End CommandEventHandler DynamicButtons.DownloadSimple

// CommandEventHandler which hardcodes the bool
// parameter to "false"
protected void DownloadDialog(
object sender,
CommandEventArgs e
){
// Call DownloadFile
// hardcoding the bool parameter to "false"
DownloadFile(
e.CommandName,
(string)e.CommandArgument,
false
);
} // End CommandEventHandler DynamicButtons.DownloadDialog

// Names for elements in the argument string
private const string groupElemNm_ = "data";
private const string nameElemNm_ = "name";
private const string fullNameElemNm_ = "fullName";
private const string extensionElemNm_ = "extension";

// Stuff the arguments into an XML fragment
private string ArgToString( FileSystemInfo info ){
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter( sw );

xw.WriteStartElement( groupElemNm_ );
xw.WriteElementString( nameElemNm_, info.Name );
xw.WriteElementString( fullNameElemNm_, info.FullName );
xw.WriteElementString( extensionElemNm_,info.Extension );
xw.WriteEndElement();
xw.Flush();
string argString = sw.ToString();
xw.Close();

return argString;
} // End DynamicButtons.ArgToString

// Helper method for StringToArg
private string GetElementValue( XmlTextReader reader ){
reader.Read();
return reader.NodeType == XmlNodeType.Text ? reader.Value : string.Empty;
} // End DynamicButtons.GetElementValue

// Extract the arguments from the XML fragment
private void StringToArg(
string argStr,
ref string name,
ref string fullName,
ref string extension
){
bool readElements = false;

StringReader sr = new StringReader( argStr );
XmlTextReader xr = new XmlTextReader( sr );
xr.WhitespaceHandling = WhitespaceHandling.None;

// Get past the enclosing element
while( xr.Read() ) {
if( xr.NodeType == XmlNodeType.Element ) {
readElements = (xr.Name == groupElemNm_ );
break;
}
}

// Now process the contained elements
if( readElements ){
while( xr.Read() ){
if( xr.NodeType != XmlNodeType.Element )
continue;

if ( xr.Name == nameElemNm_ )
name = GetElementValue( xr );
else if ( xr.Name == fullNameElemNm_ )
fullName = GetElementValue( xr );
else if ( xr.Name == extensionElemNm_ )
extension = GetElementValue( xr );

} // end while more elements
} // end if enclosing "data" element

xr.Close();
} // End DynamicButtons.StringToArg

// Helper method for "DownloadFile"
private void AddTableRow( Table tbl, string desc, string valueStr ){
TableRow row = new TableRow();
TableCell tcDesc = new TableCell();
TableCell tcValue = new TableCell();

tcDesc.Text= desc;
tcValue.Text = valueStr;
row.Cells.Add( tcDesc );
row.Cells.Add( tcValue );
tbl.Rows.Add( row );
} // End DynamicButtons.AddTableRow

// Simply demonstrate handling of the arguments and display
private void DownloadFile(
string cmdName,
string cmdArg,
bool forceDownload
){
string fileName = string.Empty;
string fileFullName = string.Empty;
string fileExtension = string.Empty;
StringToArg( cmdArg, ref fileName, ref fileFullName, ref fileExtension );

// Display the Results
Table tbl = new Table();
tbl.GridLines = GridLines.Both;
tbl.BorderStyle = BorderStyle.Solid;

AddTableRow( tbl, "forceDownload", forceDownload.ToString() );
AddTableRow( tbl, "Command Name", cmdName );
AddTableRow( tbl, nameElemNm_, fileName );
AddTableRow( tbl, fullNameElemNm_, fileFullName );
AddTableRow( tbl, extensionElemNm_, fileExtension );

pnlLinks.Controls.Add( tbl );
} // End DynamicButtons.Downloadfile
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
}
Nov 15 '05 #3
Hi Folks

Firstly, many thanks to all of you who put forward potential solutions
to this problem which is most helpful.

Frank, you will notice from my code fragments that the DownloadFile
function does indeed accept two parameters. My question really was how
do you call a function with more than one parameter from a hyperlink
or LinkButton.

It looks to me like a major shortfall of the .Net system.

Many thanks again to you all
John
Nov 15 '05 #4
Fresh Air Rider <Fr*************@Hotmail.com> wrote:
Firstly, many thanks to all of you who put forward potential solutions
to this problem which is most helpful.

Frank, you will notice from my code fragments that the DownloadFile
function does indeed accept two parameters. My question really was how
do you call a function with more than one parameter from a hyperlink
or LinkButton.

It looks to me like a major shortfall of the .Net system.


It's still not.

Your code for CommandBtn_Click is:

void CommandBtn_Click(Object sender, CommandEventArgs e)
{
DownloadFile(e.CommandArgument,???);
}

You just need to change it to fill in the second parameter
appropriately. Only you know what the appropriate value is in this
case.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5
Hi Frank

Yes, the question marks were simply there to show that I want to pass
other parameters into my function.

Thanks very much for your help
John
Nov 15 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Fresh Air Rider | last post by:
Hello Could anyone please explain how I can pass more than one arguement/parameter value to a function using <asp:linkbutton> or is this a major shortfall of the language ? Consider the...
0
by: Fresh Air Rider | last post by:
Can anyone please tell me why I get a javascript error (expected ';') when I simply add an <asp:LinkButton> to a User Control and the reference that user control in a webpage ? The...
5
by: George Durzi | last post by:
I currently have an href inside of an asp:repeater <a href='<%# String.Concat("PDFReader.aspx?id=", DataBinder.Eval(Container.DataItem, "ProductUniqueId")) %>' target="_blank">View</a> ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.