Multiple command in one linkbutton control - asp.net

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!. :)

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.

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.

Related

Asp.net gridview edit without editbutton

I have regular asp.net gridview,and i want to enable editmode in each row,and also without editbutton (like excel grid).
Edited data i want to save to my database by clicking "Post" button outside the grid(one button for whole grid).
How can i reach it?
To achieve this, you are going to have to use ItemTemplates for each column with textboxes in them as the control..
ASP
<asp:TemplateField HeaderText="Heading Title" SortExpression="Heading Title">
<ItemTemplate>
<asp:TextBox ID="tbTextbox" runat="server" Width="65px" Text='<%# Bind("ColumnNameYouWantToView") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
After this is set up properly, you will want the post button. You can either put it in the grid or outside the grid. I use both, but here is the one inside the grid as a footer.
ASP
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnView" runat="server" Text="View" OnClick="btnView_Click" Width="40px" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ValidationGroup="UPDATE" ID="btnUpdate" OnClick="btnUpdate_Click" runat="server" Text="Update" Width="50px"></asp:Button>
</FooterTemplate>
<FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
So far, what I have found that works best is using a foreach statement in your button click. The biggest flaw with this idea is that it will update every single row. It works, but if you only change a single row at a time, it will update all of them. I have my pager set to 10, so 10 rows are always updated (unless you are just searching for a single record and update it, the only that single record is updated).
Code Behind C#
protected void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["databaseConnection"].ConnectionString);
conn.Open();
//finds the controls within the gridview and updates them
foreach (GridViewRow gvr in gvGridViewName.Rows)
{
string ID = (gvr.FindControl("lblId") as Label).Text.Trim();//finds the control in the gridview
string anotherControl = ((TextBox)gvr.FindControl("tbTextBox")).Text.Trim();//finds the textbox in the gridview
//Your update or insert statements
}
This is how I do it. You can also look into Real World Grids but I haven't had much luck with this as I would always get an error if a textbox was empty. This however, is suppose to be "smart" enough to just update the rows that have been changed, but again, I didn't have much luck of doing it this way. Hope this helps!

Using hyperlink with querystring for gridview row

Is there someway to turn the row of a gridview into a hyperlink so that when a user opens it in a new tab for example, it goes to that link? Right now I am using a LinkButton and when the user opens it in a new tab, it doesn't know where to go.
I figured the .aspx code would look something like:
<asp:TemplateField>
<ItemTemplate>
<Hyperlink ID="hyperlink" runat="server" ForeColor="red" HtmlEncode="false" navigationURL="testUrl.aspx"
</ItemTemplate>
</asp:TemplateField>
The only thing is, our URLs are set up in the C# code behind as a query string, so I'm not sure how to pass that into the navigationURL section.
I'm guessing there's something I can do on the page_load with the query string to redirect to the page I need, but this is my first time working with query strings so I'm a little confused.
Thanks!
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#String.Format("~/controller.aspx?routeID1={0}&routeID2={1}", Eval("routeid1"), Eval("routeid2"))%>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
routeid1 and routeid2 are passed as query strings to the controller of that page.
What I did recently is modified my class to have a readonly property that constructs the A tag for me. This way I have control over what gets displayed; just text or a link.
<ItemTemplate>
<asp:Label ID="ColumnItem_Title" runat="server" Text='<%# Bind("DownloadATag") %>'> </asp:Label>
</ItemTemplate>
The code behind just binds an instance of the class to the gridview. You can bind the gridview whenever, on load on postback event, etc.
Dim docs As DocViewList = GetViewList()
GridViewDocuments.DataSource = docs
GridViewDocuments.DataBind()
In the above code, the DocViewList, instantiated as docs, is a list of a class that has all the properties that are needed to fill my GridView, which is named GridViewDocuments here. Once you set the DataSource of your GridView, you can bind any of the source's properties to an item.
Something like:
<asp:LinkButton ID="LinkButton_Title" runat="server" target="_blank"
PostBackUrl='<%# Eval(Request.QueryString["title"]) %>'
or binding them from the RowCreated event:
protected void GridView_OnRowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
(e.Row.FindControl("LinkButton_Title") as LinkButton).PostBackUrl = Request.QueryString["title"]))
}
}

ASP.NET Gridview Templatefield with multiple items

I am creating a web application in ASP.net/VB.NET and I have an issue with the GridView control.
Currently, I have the GridView populated with data from the DB and I've also coded the update button to allow the user to edit any necessary information through a form that pops up.
What I'd like to do, if possible, is add a button to the two right columns(I already put one in the Dock Out Time column) which will be invisible if the column is set or will set the current time to the column. Setting the time for those two columns is already handled through the update form, but my supervisor asked me to try and see if this was possible.
Those two Time columns are TemplateFields(since I format the display time from what is actually in the DB) and I added an asp button in the ItemTemplate for that Set Button in the picture.
Is this even possible to do and if so, how would I access this button in the code behind so I can add functionality(setting the time and hiding it if the column is not null)If it's not really possible to have two items like this in a TemplateField I can just make 2 extra columns for these buttons but I think this would look much cleaner.
Any input would be greatly appreciated. thank you for your time.
Yes this is possible, check this answer:
https://stackoverflow.com/a/11077709/1268570
Basically you need to handle the RowCommand event from the grid and identify each button with a command, optionally you can add arguments to each button when you bind, for example:
<asp:GridView runat="server" OnRowCommand="grdProducts_RowCommand"
ID="grdProducts">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false"
CommandName="myLink" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' Text="Button"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
In code behind:
protected void grdProducts_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "myLink":
this.lblMessage.Text = e.CommandName + " " + e.CommandArgument + " " + DateTime.Now.ToString();
// referenece to the current row
var row = this.grdProducts.Rows[int.Parse(e.CommandArgument.ToString())];
break;
default:
break;
}
}
After you update your grid in the RowCommand event, you should repopulate the grid data to render the changes

ASP.NET : Access controls declared in TemplateColumn of DataGrid

ASCX File:
<asp:datagrid runat="server" id="gridFormFields" datakeyfield="FieldID"
autogeneratecolumns="False"
onitemcommand="gridFormFields_ItemCommand" onitemdatabound="gridFormFields_ItemDataBound">
<columns>
<asp:templatecolumn>
<itemtemplate>
<asp:imagebutton runat="server" id="buttonMoveUpFormField" resourcekey="buttonMoveUpFormField"
commandname="Item" commandargument="MoveUp" imageurl="~/images/up.gif" />
</itemtemplate>
</asp:templatecolumn>
<asp:templatecolumn>
<itemtemplate>
<asp:imagebutton runat="server" id="buttonMoveDownFormField" resourcekey="buttonMoveDownFormField"
commandname="Item" commandargument="MoveDown" imageurl="~/images/dn.gif" />
</itemtemplate>
</asp:templatecolumn>
</columns>
Code behind:
protected void gridFormFields_ItemDataBound(object sender, DataGridItemEventArgs e)
{
(e.Item.FindControl("buttonMoveUpFormField") as ImageButton)
.Visible = gridFormFields.Items.Count > 1 && e.Item.ItemIndex > 0;
(e.Item.FindControl("buttonMoveDownFormField") as ImageButton)
.Visible = gridFormFields.Items.Count > 1 && e.Item.ItemIndex < gridFormFields.Items.Count - 1;
}
In the code behind, the Control returned by FindControl is null. Why?
How can I access the buttonMoveUpFormField and buttonMoveDownFormField controls?
From the code behind, is it possible to access controls which are declared in the ItemTemplate section of the TemplateColumn section of a DataGrid?
Because you need to add code to include "Item" and "AlternatingItem" and exclude all other types, before you try to find that control.
if (e.Item.Type == ...
You can certainly access the controls that are within the ItemTemplate section. I'm dealing with a similar issue. One thing that I've found is, depending what is calling your "gridFormFields_ItemDataBound", you may not have access to those controls yet.
I know that in my instance, I've got an "ItemTemplate" and an "EditItemTemplate", when I click edit, it fires an event "RowEditing" before it is actually switched to "Edit Mode", so the control will not be there yet. I do though have access to the controls in "RowUpdating" which is fired when I click save in the edit mode.
Maybe this helps? For example, your "OnDataBound" might be the event that is trying to access your controls, but you may not have access to them on databound?
Just a thought. I'll edit this if I get any further on mine.

ASP.NET GridView CommandField Update/Cancel does not wrap

My question is on the ASP.NET GridView control. I am using a CommandField in the Columns tag as seen below.
<asp:CommandField ShowEditButton="True" HeaderStyle-Width="40px" UpdateText="Save" ButtonType="Link" HeaderStyle-Wrap="true" ItemStyle-Wrap="true" ItemStyle-Width="40px"/>
What renders is the shown in the following image (after I click on the Edit button).
As you can see I am trying to have the Cancel link show up a new line and my question is how do you do what? If I change the ButtonType="Link" to ButtonType="Button", I get it rendering correctly as shown below.
alt text http://i38.tinypic.com/2pqopxi.jpg
I've tried Google already and maybe I'm not searching on the right tags but I couldn't see this one addressed before.
If you use a template field it will give you complete control over the look of your page, but it requires that you use the CommandName and possible CommandArgument properties, and also using the GridView's OnRowCommand.
The aspx page:
<asp:GridView id="gvGrid" runat="server" OnRowCommand="gvGrid_Command">
<Columns>
<asp:TemplateField>
<ItemTemplate>
Some Stuff random content
<br />
<asp:LinkButton id="lbDoIt" runat="server" CommandName="Cancel" CommandArgument="SomeIdentifierIfNecessary" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind:
protected void gvGrid_Command(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Cancel")
{
// Do your cancel stuff here.
}
}
Don't use a command field, use a TemplateField and put your command button in that with a line break (br) before it like you want.

Resources