I have some texts in my database. Each text has its own id.
My job is to print all texts to a website and add a button to each text. Button will delete appropriate text from the database.

So, I created a for loop so I can print all texts from the db, I also put <asp:Button id="button" runat="server" Text="delete" onclick="some_method" </asp> in the loop.

My problem is that all buttons have the same id and the program cannot know what text to delete. I tried to put in the id attribute a variable created before but I got the message that I cannot put <% %> inside button tag.

I also tried this:
buttonX.Attributes.Add("id", "123");
But onclick event didn't get this id.

Any suggestions. Thank you.

Recommended Answers

All 11 Replies

You can use CommandName and CommandArgument for this requirement.

A Simple example

HTML source

<form id="form1" runat="server">

      <h3>Button CommandName Example</h3>

      Click on one of the command buttons.

      <br /><br />

      <asp:Button id="Button1"
           Text="Sort Ascending"
           CommandName="Sort"
           CommandArgument="Ascending"
           OnCommand="CommandBtn_Click" 
           runat="server"/>

      &nbsp;

      <asp:Button id="Button2"
           Text="Sort Descending"
           CommandName="Sort"
           CommandArgument="Descending"
           OnCommand="CommandBtn_Click" 
           runat="server"/>

      <br /><br />

      <asp:Button id="Button3"
           Text="Submit"
           CommandName="Submit"
           OnCommand="CommandBtn_Click" 
           runat="server"/>

      &nbsp;

      <asp:Button id="Button4"
           Text="Unknown Command Name"
           CommandName="UnknownName"
           CommandArgument="UnknownArgument"
           OnCommand="CommandBtn_Click" 
           runat="server"/>

      &nbsp;

      <asp:Button id="Button5"
           Text="Submit Unknown Command Argument"
           CommandName="Submit"
           CommandArgument="UnknownArgument"
           OnCommand="CommandBtn_Click" 
           runat="server"/>

      <br /><br />

      <asp:Label id="Message" runat="server"/>

   </form>

Class file source

void Page_Load(Object sender, EventArgs e)
      {

         // Manually register the event-handling method for the Command  
         // event of the Button controls.
         Button1.Command += new CommandEventHandler(this.CommandBtn_Click);
         Button2.Command += new CommandEventHandler(this.CommandBtn_Click);
         Button3.Command += new CommandEventHandler(this.CommandBtn_Click);
         Button4.Command += new CommandEventHandler(this.CommandBtn_Click);
         Button5.Command += new CommandEventHandler(this.CommandBtn_Click);

      }


void CommandBtn_Click(Object sender, CommandEventArgs e) 
      {

         switch(e.CommandName)
         {

            case "Sort":

               // Call the method to sort the list.
               Sort_List((String)e.CommandArgument);
               break;

            case "Submit":

               // Display a message for the Submit button being clicked.
               Message.Text = "You clicked the <b>Submit</b> button";

               // Test whether the Command Argument is an empty string ("").
               if((String)e.CommandArgument == "")
               {
                  // End the message.
                  Message.Text += ".";
               }
               else
               {
                  // Display an error message for the command argument. 
                  Message.Text += ", but the command argument is not recogized.";
               }                
               break;

            default:

               // The command name is not recognized. Display an error message.
               Message.Text = "Command name not recogized.";
               break; 

         }

      }

bind that text to gridview and ondeletingevent....

fire the delete query & killem all...

or you can try something like ramesh suggested...

hope it helps...

Oh i see.

Now I only have a problem how to specify each button's CommandName.

Is it possible to insert a string variable inside a tag (to specify attribute). Example:
String attributeName = "attr";
<asp:button id="button1" CommandName=attributeName...</asp>

The tag above does not work. Anyone know the solution?

I also tried this after writing <asp:button...</asp>:
buttonX.Attributes.Add("CommandName", attributeName);
No effect.

Anyone?

Try this. buttonX.CommandName = attributeName;

Try this. buttonX.CommandName = attributeName;

I did. Same issue (CommandName in event handler is not updated).

Post your code. It will help us to give you a correct solution.

I prepared a simple example. Let's pressume text is coming from a database. Actually whole thing is how to get variable i in button_Click.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
            
        <% for (int i = 0; i < 10; i++)
           { %>
                          
            <p> <% Response.Write("Text number: " + i); %> <br /></p>
            <asp:Button ID="buttonX" runat="server" Text="Delete" CommandName=????? OnCommand="button_Click" />
            
        <% } %>
        
        
    </div>
    </form>
</body>
</html>

It seems that you have mixed both classic asp and asp.net to achieve your requirement.

I have given some sample code for this. Hope this will help you.

HTML Source

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DemoPage5.aspx.cs" Inherits="DemoPage5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>

Code behind class source

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;


public partial class DemoPage5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        LoadControls();
    }

    private void LoadControls()
    {
        for (int i = 0; i < 10; i++)
        {
            Button btn = new Button();
            btn.ID = "buttonX" + i.ToString();
            btn.CommandArgument = "arg" + i;
            btn.CommandName = "YourCommandName";
            btn.Text = "Delete";
            btn.Command += new CommandEventHandler(ButtonX_Command);
            PlaceHolder1.Controls.Add(btn);

            LiteralControl litCtrl = new LiteralControl("<br/>");
            PlaceHolder1.Controls.Add(litCtrl);

        }
    }
    protected void ButtonX_Command(object sender, CommandEventArgs e)
    {
        string cmdArgument = e.CommandArgument.ToString();
        switch (cmdArgument)
        {
            case "arg0":
                //your code
                break;

            case "arg1":
                //your code
                break;

            case "arg2":
                //your code
                break;

        }
    }
}

dude your problem is load txt data from database and process it on button click..

i'm trying to show you an easy way...why are taking a long cut....

try things to workout in short...

load the data in Gridview and add a command button in Itemtemplate...

specify commandName & command Argument..

on on gridview's rowdatabound event....handle the delete event...

or i can send you the code...

Thanks to both of you. I solved it as Ramesh suggested. I am not so used to asp.net yet so every help is appreciated.
dnanetwork i am sure your solution is good to but right now I am busy and I do not have time to work it out. Thanks anyway.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.