Conditional Delete Button in Gridview - asp.net

I have a delete button in my gridview, but I want this button not to work depending on the result of an sql query.
An example
I have a gridview with "ship containers", and I want to remove one of the container from this list, but I want to display a message "to be able to delete this container, please remove it from the products", so that if a ship container is in use, I need to prevent it from being deleted.

Here is the way you can do this:
<asp:GridView ID="EntityGridView" runat="server" DataKeyNames="DocumentId" AutoGenerateColumns="False"
AllowPaging="True" AllowSorting="False" SkinID="GridViewSmall" OnRowCommand="EntityGridView_RowCommand"
OnPageIndexChanged="EntityGridView_PageIndexChanged">
<Columns>
<asp:TemplateField ItemStyle-CssClass="TemplateFieldThreeColumns">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" ImageAlign="Top" runat="server" ImageUrl='<% #ResolveImageUrl(Eval("Extension").ToString()) %>'
ToolTip='<%# Eval("Extension").ToString() %>' CommandName="Select" CommandArgument='<%# Eval("DocumentId") %>' />
<asp:ImageButton ID="btnDelete" runat="server" ToolTip="<% $resources:AppResource,Delete %>"
SkinID="DeletePage" OnClientClick="<%# GetDeleteConfirmation(Resources.AppResource.ConfirmDocumentDelete) %>"
CommandName="CustomDelete" CommandArgument='<%# Eval("DocumentId") %>' Visible='<% #AllowDocDelete(Container.DataItem) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Title" HeaderText="<% $resources:AppResource,Title %>" />
<asp:BoundField DataField="Author" HeaderText="<% $resources:AppResource,Author %>" />
<asp:BoundField DataField="FileName" HeaderText="<% $resources:AppResource,FileName %>" />
<asp:BoundField DataField="Created" HeaderText="<% $resources:AppResource,Created %>" />
</Columns>
<EmptyDataTemplate>
<asp:Label ID="EmptyLabel" runat="server" Text='<%# Resources.AppResource.NoContentToDisplay %>' CssClass="NoDataLabel"></asp:Label>
</EmptyDataTemplate>
</asp:GridView>
Take notice on AllowDocDelete function that disables delete button. This function should be declared inslide your page class, something like this:
public bool AllowDocDelete(object item)
{
bool result = false;
//TODO: check your condition
return result;
}
Item object represents binded entity.

Related

Sorting asp.net GridView with SPDataSource

I would like to sort my GridView by clicking on the column's header. So far I declared a SPDataSource
<SharePoint:SPDataSource
runat="server"
ID="SPdsInventarGrid"
DataSourceMode="List"
UseInternalName="true"
Scope="Recursive"
SelectCommand="<View><Query><Where><Or><Neq><FieldRef Name='EBS_x002e_CN_x002e_Inventar_x00210' /><Value Type='Text'>Open</Value></Neq><IsNull><FieldRef Name='EBS_x002e_CN_x002e_Inventar_x0028' /></IsNull></Or></Where></Query><ViewFields><FieldRef Name='Title'/><FieldRef Name='ID'/><FieldRef Name='EBS_x002e_CN_x002e_Inventar_x0028'/><FieldRef Name='EBS_x002e_CN_x002e_Inventar_x00210'/><FieldRef </ViewFields></View>">
<SelectParameters>
<asp:Parameter Name="ListName" DefaultValue="Inventar" />
</SelectParameters>
</SharePoint:SPDataSource>
Then I created my grid, based on the datasource
<asp:GridView Visible="true" Width="100%"
ID="gvInventar"
AutoGenerateColumns="false" runat="server" CellPadding="2" AllowPaging="false" AllowSorting="true" OnSorted="gvInventar_Sorted" OnSorting="gvInventar_Sorting" GridLines="None" DataSourceID="SPdsInventarGrid" OnRowCommand="gvInventar_RowCommand">
<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="true" EditImageUrl="/_layouts/images/edit.gif" UpdateImageUrl="/_layouts/images/save.gif" CancelImageUrl="/_layouts/images/delete.gif" />
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label Text='<%# Bind("ID") %>' runat="server" ID="lblIdProduct"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" >
<ItemTemplate>
<asp:Label Text='<%# Bind("Title") %>' runat="server" ID="lblTitleProduct" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product" SortExpression="Product">
<ItemTemplate>
<asp:Label Text='<%# Bind("EBS_x002e_CN_x002e_Inventar_x0028") %>' runat="server" ID="lblProduct" "></asp:Label>
</ItemTemplate>
</Columns>
</asp:GridView>
Now, I have this function where I wanted to get the current Query as a string and add <OrderBy>(my field) before <Query> but i get an error saying that the DataSource has been already declared (which is true because i want to be declared in asp)
protected void gvInventar_Sorting(object sender, GridViewSortEventArgs e)
{
SPQuery q = new SPQuery();
q.Query = SPdsInventarGrid.SelectCommand;
switch (e.SortExpression)
{
case "Product":
if (e.SortDirection == SortDirection.Ascending)
{
gvInventar.DataSource = q.Query;
gvInventar.DataBind();
}
else
{
}
break;
}
}
Even though it's not working this way, I don't think modifying the Query is the solution.
Could anyone help me with this matter?
You don't need to write any custom code to sort the gridview by clicking the column headers, all you have to do is set the SortExpression property of the TemplateField to the required column name, e.g:
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<asp:Label Text='<%# Bind("ID") %>' runat="server" ID="lblIdProduct" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="Title">
<ItemTemplate>
<asp:Label Text='<%# Bind("Title") %>' runat="server" ID="lblTitleProduct" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product" SortExpression="EBS_x002e_CN_x002e_Inventar_x0028">
<ItemTemplate>
<asp:Label Text='<%# Bind("EBS_x002e_CN_x002e_Inventar_x0028") %>' runat="server"
ID="lblProduct" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Now you can sort on all 3 columns:

can't access asp controls from gridview

I have user control with a gridview, but for some reason I can't use the asp controls from within the backend code.
In the other user controls I can use them normally but at this particular user control it gives me error when I am trying to use a control which is used in the gridview.
Here is the code for my gridview, please let me know if you notice something unusual:
<asp:GridView ID="gvGDG" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1" Width="100%" CssClass="mGrid" GridLines="None" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
AllowPaging="True" >
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True"
ItemStyle-HorizontalAlign="Center" CausesValidation="False">
</asp:CommandField>
<asp:BoundField DataField="ID" HeaderText="ID"
SortExpression="ID" InsertVisible="False" ReadOnly="True"
ItemStyle-HorizontalAlign="Center" >
</asp:BoundField>
<asp:TemplateField HeaderText="Country" SortExpression="Country">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:UpdatePanel ID="countrypanel" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlCountry" runat="server" DataTextField="name" DataValueField="ID" onselectedindexchanged="ddlcountry_SelectedIndexChanged" AppendDataBoundItems="true" AutoPostBack="true" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlCountry" />
</Triggers>
</asp:UpdatePanel>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="State Province" SortExpression="State_Province">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("State_Province") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlState" runat="server" DataSourceID="SqlDataSource3" SelectedValue='<%# Bind("State_Province") %>'
DataTextField="StateName" DataValueField="StateName">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [StateName] FROM [States]"></asp:SqlDataSource>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="GDG Type" SortExpression="State_Province">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("GDG_Type") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlGdg" runat="server" DataSourceID="SqlDataSource4" SelectedValue='<%# Bind("GDG_Type") %>'
DataTextField="GDG" DataValueField="GDG">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [GDG] FROM [GDG]"></asp:SqlDataSource>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Energy Type UOM" SortExpression="Energy_Type_UOM">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Energy_Type_UOM") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlUomEnergy" runat="server" DataSourceID="SqlDataSource5" SelectedValue='<%# Bind("Energy_Type_UOM") %>'
DataTextField="UOM" DataValueField="UOM">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT UOM FROM UOM WHERE (Type = 'E')"></asp:SqlDataSource>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="GDG UOM" SortExpression="GDG_UOM">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("GDG_UOM") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlUom" runat="server" DataSourceID="SqlDataSource6" SelectedValue='<%# Bind("GDG_UOM") %>'
DataTextField="UOM" DataValueField="UOM">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource6" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT UOM FROM UOM WHERE (Type = 'O')"></asp:SqlDataSource>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="GDG_Coeficient_Value"
HeaderText="GDG Coeficient Value" SortExpression="GDG Coeficient Value"
ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundField>
</Columns>
<PagerStyle CssClass="pgr"></PagerStyle>
</asp:GridView>
Thanks in advance, Laziale
If I m right then. You have a User Control. Say wucMyControl.ascx, where you have a gridview control gvGDG. And u are unable to access it from wucMyControl.ascx.cs. If its the problem then use the solution below:
In your user controls designer file check the access level of the Gridview control. Might be it will get changed to private, accidently , instead of protected. If its private , make it protected or public and check whether you are able to access it now or not.
Update
FYI, you can't access directly the child controls. For this you need to access in the controls DataBound event.
Here in your case :
protected void GridView_RowDataBound(sender, e)
{
if(e.Row.RowType == DataControlRowtype.DataRow)
{
var ddl = (DropdownList)e.Row.FindControl("ddlCountry");
// do whatever you want with ddl. Similarly you can find all html and server control inside a gridview.
}
}
This will help you...
Adding event to gridview child controls
In your GridView1_RowDataBound method, add the handler when you create the drop down by calling ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
Then, declare the void ddl_SelectedIndexChanged(object sender, EventArgs e) method to handle your logic. The sender argument will be a reference to the drop down's that was selected. Also set AutoPostback property of the drodownlist to true.
I think maybe you have some wrong with code on top line of page ASP.net designer:
Please check on CodeFile="??????" and Inherits="????????"

Hiding a cell with a Hidden Field

In my GridView, I am using a Hidden Field to store some data that is not supposed to be seen by the user:
<Columns>
<asp:BoundField DataField="Название" HeaderText="Название" ItemStyle-Width="250px" HeaderStyle-Width="250px" />
<asp:BoundField DataField="RDName" HeaderText="РД" ItemStyle-Width="250px" HeaderStyle-Width="250px" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="RD_ID" runat="server" Value='<%# Eval("RD_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
I have a problem with this. Though the data is not seen in the GridView, the additional empty cell is still there. Could you please tell me how I can hide it completely?
Thanks,
David
Can't you do it like this?
<Columns>
<asp:BoundField DataField="Название" HeaderText="Название" ItemStyle-Width="250px" HeaderStyle-Width="250px" />
<asp:TemplateField HeaderText="РД" ItemStyle-Width="250px" HeaderStyle-Width="250px">
<ItemTemplate>
<asp:Label ID="RD_Name" runat="server" Text='<%# Eval("RDName") %>' />
<asp:HiddenField ID="RD_ID" runat="server" Value='<%# Eval("RD_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
You can always put the hidden element alongside with any TemplateField ItemTemplate object. You don't have to create a cell to contain the hidden element.

How to get cell contents in ASP.NET GridView while handling OnRowEditing?

I have a GridView with a BoundField column and quite a few item templates like the following:
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" OnRowCommand="gvUsers_RowCommand"
OnRowDataBound="gvUsers_RowDataBound" DataKeyNames="UserId" OnRowEditing="gvUsers_OnRowEditing"
OnRowUpdating="gvUsers_OnRowUpdating" OnRowUpdated="gvUsers_OnRowUpdated"
DataSourceID="DataSource1" Width="807px" Height="105px"
AllowPaging="True" >
<Columns>
<asp:BoundField DataField="UserName" HeaderText="User Name"
SortExpression="UserName" />
<asp:TemplateField HeaderText="Approver">
<ItemTemplate>
<asp:CheckBox ID="cbApprover" runat="server" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Auditor">
<ItemTemplate>
<asp:CheckBox ID="cbAuditor" runat="server" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server"
CommandArgument='<%# Eval("UserName") %>' CommandName="Edit" Text="Edit" />
<asp:Label ID="lblPipe1" runat="server" Text=" | " />
<asp:LinkButton ID="btnUpdate" runat="server"
CommandArgument='<%# Eval("UserName") %>' CommandName="Update" Text="Update" />
<asp:Label ID="lblPipe" runat="server" Text=" | " />
<asp:LinkButton ID="btnDelete" runat="server"
CommandArgument='<%# Eval("UserName") %>' CommandName="Remove"
OnClientClick="return confirm('Are you sure you want to delete this user?');"
Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
While handling the Edit link button I need to use the value in the BoundField, UserName. Unfortunately during the OnRowEditing handler, all strings are empty "". This is also true in the ensuing OnRowDataBound handler for the row in question where e.Row.RowState == DataControlRowState.Edit. Is there a way to obtain this value after the user clicks on the Edit link, and commences the OnRowEditing event?
I arrived at a solution that was a bit more complicated than I was hoping for. I'll show code later but I did the following:
Created a HiddenField to hold the
value of the cell I wanted to edit in
its view state.
In the OnRowDataBound handler, I assigned the value to the
HiddenField.
The ItemTemplate, as seen above, sends the UserName as an
argument. I store this value in
the HiddenField.
The OnRowEditing is fired after the Command handler. That is where I
read the HiddenField.
If anyone has a simpler solution I would love hear about it.
Could it be that you're using late binding in TemplatedItems without EditItemTemplates?

Simple databinding to gridview columns

I have a GridView that I use to show my users the result of a search. I want to allow them to choose which columns are shown on the GridView when performing their search. Simple enough, yes? I wanted to try doing this using just databinding, no events. Unfortunately, my code fails to update the GridView using checkboxes bound to the column's Visible property. The state of the chechboxes changes, but the Visible property of the columns does not.
Snippet of Search.aspx:
<myControl:FacultyGridView ID="FacultyGridView1" runat="server" />
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Text='<%# Eval("HeaderText") %>' Checked='<%# Bind("Visible") %>' AutoPostBack=true/></ItemTemplate>
</asp:Repeater>
Code-behind snippet in Search.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = FacultyGridView1.GridView.Columns;
Repeater1.DataBind();
}
To be clear, the GridView is exposed as a public property of a user control named FacultyGridView. Relevant snippet of FacultyGridView.ascx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowPaging="True" AllowSorting="True" PageSize="25">
<PagerSettings Mode="NumericFirstLast" Position="TopAndBottom" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" />
<asp:TemplateField HeaderText="University" SortExpression="UniversityID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("University.Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Division">
<ItemTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSource='<%# Eval("DivisionMemberships") %>'>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Division.Name") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True" SortExpression="Title" />
<asp:TemplateField HeaderText="Research Type">
<ItemTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSource='<%# Eval("ResearchTypeMappings") %>'>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ResearchType.Name") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Expertise" HeaderText="Expertise" ReadOnly="True" SortExpression="Expertise" />
<asp:HyperLinkField DataNavigateUrlFields="Website" DataTextField="Website" HeaderText="Website"
SortExpression="Website" />
<asp:BoundField DataField="Phone" HeaderText="Phone" ReadOnly="True" SortExpression="Phone" />
<asp:TemplateField HeaderText="Email Address" SortExpression="EmailAddress">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("EmailAddress", "mailto:{0}") %>'
Text='<%# Eval("EmailAddress") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Finally, I should mention that the GridView is bound by a Button on the page, but I am not getting updates to the Visible property whether I play with the checkboxes before or after databinding. Furthermore, I have not seen my desired behavior when binding the repeater only on the first Page_Load() using if(!IsPostBack), nor by not using Checkbox.AutoPostback true or false. Any clue as to what I'm doing wrong? I expect it to be something simple, but I'm a bit green here.
As a note: I know how to do this easily with events, but I want to do it with databinding as a learning exercise.
Probably because every time the grid is bound to the data, the column & settings are recreated (with-out your changes).

Resources