Question

I'm new to asp.net development. I would like to ask if it is possible for one link button to have two or more commands?

What I want to happen is that my link button should be able to handle the edit and update commands. Once i click the link in my grid view, it will show the data on its respective controls (i.e textbox for name will have the data of what I clicked) then once I edit any data on the textbox and click the same link it will update and save in the database.

 <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkEdit" runat="server" CommandArgument='<%#Eval("ID")%>'  CommandName="Update" 
                             HeaderText="ID" SortExpression="ID" Text='<%#Eval("ID")%>'> 
                        </asp:LinkButton>
                    </ItemTemplate> 
                </asp:TemplateField>

Thanks in advance. Please help!. :)

Was it helpful?

Solution

Its not possible to have multiple commandname for one linkbutton,but when you click linkbutton for editing you can change commandname to "Update".I think this will solve your problem.For changing the commandname for linkbutton refer to this link.

OTHER TIPS

You don't need to create two commands.

First set command name to Edit. Hence on clicking it. It will show data in controls. Also in click event set command name to Update. And after updating again set command name to Edit.

Write click event code like this.

 if(CommandName=="Edit")
 {
    //Fill Value in controls
    // Set CommandName to Update
 }
else if(CommandName=="Update")
 {
    // Update value in database
    // Set command name to Edit
 }

Alternatively you can use two linkbuttons with one visible at a time.

Hope this help.

Hi Jenny use code like this:-

 <asp:TemplateField HeaderText="ID">
                <ItemTemplate>
                    <asp:LinkButton ID="lnkEdit" runat="server" CommandArgument='<%#Eval("ID")%>'  CommandName="Update" Onclick="lnkEdit_Click"
                         HeaderText="ID" SortExpression="ID" Text='<%#Eval("ID")%>'> 
                    </asp:LinkButton>
                </ItemTemplate> 
            </asp:TemplateField>

In aspx.cs Page write code like below:-

protected void lnkEdit_Click(object sender, EventArgs e)
{
   LinkButton btn = (LinkButton )sender;
   int Id = Convert.ToInt32(btn.CommandArgument.ToString());

   if(btn.CommandName=="Edit")
     {
         // Write here code for edit
          btn.CommandName="Update";
     }
   else if(btn.CommandName=="Update")
     {
         // Write here code for Update
          btn.CommandName="Edit";
     }
}

Hope this help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top