Dynamic LinkButton and Click event

G

Guest

I am creating an aspx page using C# and would like to be able to dynamically
create linkbuttons that all run the same fuction on the click event. However,
I would like the function to accept a single argument (in this case the file
name) to identify which button was clicked. I am using the Command event
handler.

The link buttons load correctly, but when i click on a link, the event
handler code does not execute.

Any ideas?
cheers.

DirectoryInfo dir = new DirectoryInfo(C://temp);
FileInfo[] files = dir.GetFiles();

HtmlTable table = new HtmlTable();
HtmlTableRow tableRow;
LinkButton lbtn;

foreach(FileInfo file in files)
{
table.Rows.Add((tableRow = new HtmlTableRow()));

//Create delete cell
tableRow.Cells.Add(tableCell = new HtmlTableCell());
lbtn= new LinkButton();
lbtn.ID = file.Name;
lbtn.Text = "Delete";
lbtn.Command += new CommandEventHandler(OnDelete);
lbtn.CommandName = file.Name;
lbtn.CommandArgument = file.Name;
tableCell.Controls.Add(lbtn);
}

//The event handler
private void OnDelete(object sender, CommandEventArgs e)
{
string fileToDelete = e.CommandArgument.ToString();
Response.Write(fileToDelete);
}
 
G

Guest

It's ok, i figured it out.
the code works , but only if you create the linkbuttons from the page_load
event.
i was trying to call it from within another event. ... for somereason, it
didnt like it.
 
I

Ignacio Machin \( .NET/ C# MVP \)

hi

remember that teh controls that you create from code are not recreated in
the postback, you have to create them always.

if you want to pass an argument you can use Command instead of OnClick and
then use CommandArgument to store the value you want.


cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top