472,374 Members | 1,239 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,374 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 3656
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: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.
0
DizelArs
by: DizelArs | last post by:
Hi all) Faced with a problem, element.click() event doesn't work in Safari browser. Tried various tricks like emulating touch event through a function: let clickEvent = new Event('click', {...

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.