Using asp:Button with OnRowDeleting event - asp.net

I'm trying to connect an asp:Button with my OnRowDeleting event in a gridview, but I don't don't know how to do that :X. I'm currently using CommandField but for my own purposes I need it with a Button instead. Can anyone help me please?
EDIT:
Let me re-explain, I have a row with Delete and Edit buttons in the same CommandField. What I'm trying to do is to hide the 'Delete' button in some specific cases for specific rows only and not necessarily for every row. That's why I'm struggling with a CommandField because there's no ID coming with it so I can't refer to it in my codebehind. But - asp:Button has an ID but I can't manage to link it with the UserAccounts_RowDeleting function. And that's my question - how to link it? :)
EDIT2:
These are part of my codes:
<asp:GridView ID="UserAccounts" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="#3AC0F2"
HeaderStyle-ForeColor="White" AutoGenerateDeleteButton="false"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AutoGenerateEditButton="false"
onrowcancelingedit="UserAccounts_RowCancelingEdit" RowStyle-ForeColor="#3A3A3A" OnRowEditing="UserAccounts_RowEditing"
PageSize="10" AllowPaging="false" onrowdeleting="UserAccounts_RowDeleting"
OnRowUpdating="UserAccounts_RowUpdating" OnRowDataBound="UserAccounts_RowDataBound" onrowcreated="UserAccounts_RowCreated">
<Columns>
<asp:CommandField ShowDeleteButton="true" ShowEditButton='true' ButtonType="Link" />
<asp:BoundField DataField="UserName" HeaderText="Username" ReadOnly="true"/>
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:CheckBoxField DataField="IsApproved" HeaderText="Approved?" ReadOnly="false"/>
<asp:CheckBoxField DataField="IsLockedOut" HeaderText="Locked Out?" ReadOnly="true"/>
<asp:CheckBoxField DataField="IsOnline" HeaderText="Online?" ReadOnly="true"/>
<asp:BoundField DataField="Comment" HeaderText="Comment" NullDisplayText="N/A"/>
<asp:TemplateField HeaderText="Select" >
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
//Codebehind c#
protected void UserAccounts_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (Funcs.GetAdminLevel() >= 999)
{
username = UserAccounts.Rows[e.RowIndex].Cells[1].Text;
if (username.ToLower().Equals(HttpContext.Current.User.Identity.Name.ToLower()))
ActionStatus.Text = string.Format("ERROR: You can't delete your own account ('<font color=#000000><b>{0}</b></font>')!", username);
else if (Funcs.GetAdminLevel(username) >= 1)
ActionStatus.Text = string.Format("ERROR: You can't delete administrators' accounts ('<font color=#000000><b>{0}</b></font>')!", username);
else
{
Roles.RemoveUserFromRoles(username, Roles.GetRolesForUser(username));
Membership.DeleteUser(username);
ActionStatus.Text = string.Format("User '<font color=#000000><b>{0}</b></font>' has been successfully deleted!", username);
BindUserAccounts();
}
}
else
ActionStatus.Text = "You are not authorized to delete user accounts!";
}
I want to change the CommandField to ItemTemplate so I can enable/disable it through the codebehind for specific rows only. Also, I want the ItemTemplate, which would be asp:Button, to use the UserAccounts_RowDeleting event and that's where my problem is, I just don't know how to link the button to the event..

It sounds like you pretty much have the solution already. Use a TemplateField for your button. The key part is to set the CommandName of your button to "Delete". This tells the GridView that it is a delete button and the RowDeleting event should handle it.
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>

Related

Model binding to formview when Gridview Edit button is clicked

I have searched here and on google as well.Things are not working so I'm posting this.
I have two controls GridView and FormView.I am using Model binding in my project.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
AutoGenerateColumns="false" SelectMethod="Select_GridView">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Designation" HeaderText="Designation" />
<asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="Edit_Profile" OnClick="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
DefaultMode="Insert" InsertMethod="Insert_Profile" >
I want to open FormView in Edit mode , where in gridview i am sending id of that record.On button click i want to change formview mode by calling BLL method which takes that Id from button click and retrieved record displayed in form view in edit mode.
Please help me , how can i implement this or any other similar way using model binding only,
Thank you.
As no one seems to answer this.I have found work around and also proper method for doing,I will add the answer as i get time from work.
before
asp:Button ID="Edit_Profile" OnClick="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>"
asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
DefaultMode="Insert" InsertMethod="Insert_Profile"
after
asp:Button ID="Edit_Profile" OnCommand="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>"
asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView" SelectMethod="Get"
DefaultMode="Insert" InsertMethod="Insert_Profile"
protected void btnEdit_OnClick(object sender, CommandEventArgs e)
{
gId = Convert.ToInt32(e.CommandArgument.ToString());
fvProfile.ChangeMode(FormViewMode.Edit);
fvProfile.Visible = true;
GridView1.Visible = false;
fvProfile.DataBind();
}
public DAL2.Models.OfficialDocument Get()
{
if(gId == 0)
{
ChangeViewMode();
return null;
}
BLL.ManageOfficialDocument mod = new BLL.ManageOfficialDocument();
var od = mod.GetById(gFILES_ID);
return od;
}
private int gId;

C# How do I create a Hyperlink OnClick event on GridView?

I'm having trouble creating the GridView I want.
I would like the user to get inside the website and see the GridView which is attached to a DB.
Columns are: ID, InsertionTime, Filepath, ProccessedByUser
Now I want the user to click the filepath he/she would like to process. When he/she clicks the filepath, I want their username (logged in with built-in asp website authentication) to be updated (added) into DB.
My markup is standard and I haven't got to manage with code behind.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="AccessDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="starttime" HeaderText="starttime"
SortExpression="starttime" />
<asp:HyperLinkField DataNavigateUrlFields="path" DataTextField="path"
HeaderText="path" />
<asp:BoundField DataField="user" HeaderText="user" SortExpression="user" />
</Columns>
</asp:GridView>
I tried using HyperlinkField but it doesn't seem to support onlick events.
Any suggestions?
Thanks.
I assume you are looking for the LinkButton control which has an OnClick event.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="AccessDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="starttime" HeaderText="starttime"
SortExpression="starttime" />
<asp:TemplateField HeaderText="Path" SortExpression="Filepath">
<ItemTemplate>
<asp:LinkButton ID="LbPath" runat="server"
Text='<%# Eval("Filepath") %>'
CommandName="PathUpdate"
CommandArgument='<%#Bind("path") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="user" HeaderText="user" SortExpression="user" />
</Columns>
</asp:GridView>
Now you can handle the LinkButton's click event or the GridView's RowCommand event.
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "PathUpdate")
{
string path= e.CommandArgument.ToString();
// do you what you need to do
}
}
Note that i've used a TemplateField which is the most dynamic column type in a GridView since you can add anything you want, even nested GridViews or UserControls.
You could use a ButtonField, and then handle OnRowCommand of the gridview. Example here:
http://msdn.microsoft.com/SV-SE/library/system.web.ui.webcontrols.buttonfieldbase.buttontype.aspx
You can set the ButtonType attribute of ButtonField to display the button as a Link.

Query regarding binding the label in gridview ItemTemplate to String

I have a nested gridview lets call parent gridview as gridview1 and child gridview as gridview2.
For each parent gridview's (gridview1) row i'm adding child gridview (gridview2) depending upon the invoice number that is present on that particular row in the gridview1. Here is a screen shot of that output here.
Inside the child gridview (i.e., gridview2) i have a download linkbutton which i add through item template and software title which i databind to gridview2 after filtering the output that i get through List<>. But as you can see the download linkbutton is being rendered first and then software titles next. But i want the software titles to be rendered first and download link button as last column in child gridview (i.e., gridview2).
Here is the code in .aspx page for nested gridviews. I got a suggestion from a fellow member of this forum that I can add label before the download link button and associate it with data source. I just could n't understand it. How can one do that ?
<asp:GridView ID="UserTransactionGridView" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" OnRowDataBound="UserTransactionGridView_RowDataBound"
HorizontalAlign="Center" AllowPaging="true">
<Columns>
<asp:BoundField DataField="Date Of Transaction" HeaderText="Date Of Transaction"
SortExpression="Date Of Transaction" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Invoice Number" HeaderText="Invoice Number" SortExpression="Invoice Number"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="totalAmount" HeaderText="Total Amount" ReadOnly="True"
SortExpression="totalAmount" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField>
<HeaderTemplate>
<asp:Label Text="Software Title" ID="softwareLbl" runat="server"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" GridLines="None"
ShowHeader="false">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:LinkButton ID="DownloadLbtn" Text="Download" runat="server" OnClick="DownloadLbtn_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:componentConnString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="xyz" Name="userName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
By the way here is the code where i'm binding child gridview with datasource (which is arraylist that i filter based on the invoice number present on the parent gridview (i.e., gridview1)).
protected void UserTransactionGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gridView2 = (GridView)e.Row.FindControl("gridView2");
System.Data.DataRowView dr = (System.Data.DataRowView)e.Row.DataItem;
gridView2.AutoGenerateColumns = true;
String x = dr[1].ToString();
softwareTitlesList = SoftwareListRetrieve();
ArrayList titles = new ArrayList();
foreach (SoftwareTitles softwareTitle in softwareTitlesList)
{
if (softwareTitle.InvoiceNumber.Contains(x))
titles.Add(softwareTitle.SoftwareTitle);
}
gridView2.DataSource = titles;
gridView2.DataBind();
softwareTitlesList.Clear();
}
}
BTW I'm using Visual studio 2008, asp.net/c# and no LINQ in my web application project.
Please help me.
Thank you in anticipation
PS: If some one doesn't like this question u may delete it after getting answered rather than down voting or flagging it.
1: Add AutoGenerateColumns="false" to your gv2
2: <%#Container.DataItem %> just before linkbutton
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" GridLines="None" ShowHeader="false" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<%#Container.DataItem %>
<asp:LinkButton ID="DownloadLbtn" Text="Download" runat="server" OnClick="DownloadLbtn_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can add a separate TemplateField instead of adding in same before the existing one but the you get the idea why it is showing next to linkbutton.

EditTemplate property of asp:GridView control

I have a asp:GridView and in there i have two columns , in one column i want to show label
but when i click an sdit button i want to show a drop down list in that particular column,
i have created the grid view like following:
<bw:GridView ID="grdProducts" AllowPaging="True" PageSize="5" AllowSorting="True"
CssClass="DGTable" runat="server" AutoGenerateColumns="False" DataKeyNames="LinkedProductCode"
RowSelectingEnabled="True" RowStyle-CssClass="DGItem" SelectedRowStyle-CssClass="DGSelectedItem"
FooterStyle-CssClass="DGFooterTR" EditRowStyle-CssClass="DGEditItemValidator" >
<Columns>
<asp:BoundField DataField="LinkedProductCode" HeaderText="Product Code" ReadOnly="true" meta:resourcekey="BoundFieldResource4" />
<asp:TemplateField HeaderText="Product Type" ItemStyle-VerticalAlign="Top">
<ItemTemplate>
<asp:Label ID="lbl1" runat="server" Text='<%# Bind("LinkedProductType")%>' />
</ItemTemplate>
<EditItemTemplate >
<asp:DropDownList ID="linkedproductList" runat="server" DataSourceID="list">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle CssClass="DGSelectedItem" />
<PagerStyle CssClass="DGPagerTR" />
<HeaderStyle CssClass="DGHeaderTR" />
</bw:GridView>
what should i do to do it? What should i write in edit button's click event?
Please help..
It depends on how you are setting up the Edit button. If you have
<asp:Button ID="btnEdit" CommandName="Edit" runat="server" Text="Edit" />
within an <ItemTemplate> in the GridView, then the Gridview will automatically go into Edit mode when the Edit button is clicked. The CommandName Edit is a special CommandName to put a GridView into edit mode.
If you wanted to implement some specific behaviour in edit mode, then this can be achieved by setting up an OnRowEditing event handler and implement your logic here. This would look something like this
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
// Set editing on the row that raised the event
GridView1.EditIndex = e.NewEditIndex;
/* Insert specific editing logic here */
GridView1.DataBind();
}
You only need to create a ButtonField with Commandname set to "Edit" (alternatively, set the AutoGenerateEditButton property of the GridView to True).
The GridView supports preconfigured commands for fields that specify a specific set of CommandNames (such as "Edit", "Delete", "Cancel").
When this button is clicked, your GridView will go into "Edit" mode and the EditItemTemplate will automatically be displayed.

Confirm delete before deleting dataview's row

I have a GridView which supports deleting. I'd like to add a pop up window with a question like 'Are you sure you want to delete this row?'.
My code:
<asp:GridView id="GridAccounts" runat="server" AutoGenerateColumns="False"
ShowFooter="True" DataKeyNames="ID"
DataSourceID="AccountDataSource" onrowcommand="GridAccounts_RowCommand">
<SelectedRowStyle BackColor="Lime" />
<Columns>
<asp:CommandField ButtonType="Image" ShowDeleteButton="True" DeleteImageUrl="~/Pictures/delete.jpg" />
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="LabelAccountIDUpdate" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="ButtonAccountIDInsert" runat="server" CommandName="Insert" Text="Insert" />
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="LabelAccountID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void GridPaymentMethod_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton deleteButton = (ImageButton)e.Row.Cells[0].Controls[0];
MyMoney.PaymentMethodRow row = (MyMoney.PaymentMethodRow)((System.Data.DataRowView)e.Row.DataItem).Row;
deleteButton.OnClientClick = string.Format("return confirm('Are you sure you want to delete payment method {0}?');", row.Name.Replace("'", #"\'"));
}
}
This renders as:
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="return confirm('Are you sure you want to delete payment method Gotovina?');javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
If I click OK on confirmation window, postback occurs, but nothing happens. If I comment out RowDataBound code, than delete works OK. Code whithout confirmation pop up:
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
What am I doing wrong?
I believe this is an example of what you are trying to do. It's cleaner and you don't have to go nutz with the code behind.
In your code you must change ButtonType="Image" to ButtonType="Link" - then onclick="..." will be rendered without javascript:___doPostBack(...) part. And in the GridPaymentMethod_RowDataBound event set something like deleteButton.Text = "<img src=\"path_to_image\" ... />" (use html entities instead of <>).
Or you can use ImageButton with ComamndName="delete" and ConfirmButtonExtender from ASP.NET AjaxToolkit suite.
deleteButton.OnClientClick = string.Format("((!confirm('Are you sure you want to delete payment method {0}?'))?return false);", row.Name.Replace("'", #"\'"));

Resources