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

  • Thread starter Thread starter Fresh Air Rider
  • Start date Start date
F

Fresh Air Rider

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>
 
Fresh said:
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)
 
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
}
}
 
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
 
Fresh Air Rider said:
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.
 
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
 
Back
Top