I'm trying to allow for editing of the items in a GridView (the DataSource is a database connection). Every example I find has complicated examples implemented within. I'd like to know what the simplest change(s) I need to do are in order to allow for editing of items in the GridView.
In other words, how can I modify the following to allow for editing?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceWS">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="NAME" HeaderText="NAME" SortExpression="NAME" />
<asp:BoundField DataField="ACCESS_TO" HeaderText="ACCESS_TO" SortExpression="ACCESS_TO" />
</Columns>
</asp:GridView>
Obviously I'd need to add code as well, but I'm just not sure how to start with this.
EDIT: I thought I'd specified, but I didn't - it's an SQLDataSource.
There are several thing you need to do to enable editing
Assuming that your data source is an SQLDataSource
1) Add a command field to your girdview columns
<asp:CommandField ButtonType="Button" EditText="Edit" ShowEditButton="true"/>
2) Add an update command to your data source
<asp:SqlDataSource ID="SqlDataSourceWS" runat="server"
ConnectionString="<%$ Connection String %>"
SelectCommand=" SELECT COMMAND HERE "
UpdateCommand=" UPDATE COMMAND HERE ">
<UpdateParameters>
<asp:Parameter Name="" />
<asp:Parameter Name="" />
</UpdateParameters>
</asp:SqlDataSource>
For more information on the command field and how to use it you can look at the Microsoft Developer Network Documentation
EDIT
Here is a very simple example of a SQLDatasource that shows how you may update an item
<asp:SqlDataSource ID="sqlMeetings" runat="server"
ConnectionString="<%$ connection %>"
SelectCommand="SELECT [meetingid]
,[groupname]
,[meetingtime]
,[meetingdate]
FROM [DCMS].[dbo].[tbl_meetings] "
UpdateCommand="UPDATE tbl_meetings
SET meetingdate = #meetingdate, meetingtime = #meetingtime
WHERE meetingid = #meetingid">
<UpdateParameters>
<asp:Parameter Name="meetingdate" />
<asp:Parameter Name="meetingtime" />
</UpdateParameters>
</asp:SqlDataSource>
From the example above you can see that I am selecting 3 fields from the data base but only allowing for two to be updated (meetingdate and meetingtime).
To edit the records, the GridView must enter EditMode. The grid changes modes according to the commands it receives, in this case "edit". See the remarks on the gridview page, 'Data Operations' section, for more info.
There are basically three ways to fire the command and enter edit mode on the grid:
Use the AutoGenerateEditButton property on the grid
Use a CommandField with ShowEditButton like the other answer stated
Use a custom TemplateField with a LinkButton inside like this:
<Columns>
...
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
...
</Columns>
After that, it will depend on which DataSource control you are using. With an EntityDataSource, for instance, all you need to do is set EnableUpdate="true"
Related
I have one stored procedure called VideoGalleryDelete . I am using FormView and Gridview to insert, update, show and delete data. VideoGallery is my primary table with PK VideoId and it has a foreign key as CategoryId .
When i click Delete linkButton, its says Procedure or function has too many arguments specified
This is my SP :
ALTER PROCEDURE [dbo].[VideoGalleryDelete]
#VideoId int
AS
BEGIN
DELETE FROM [dbo].[VideoGallery]
WHERE VideoId = #VideoId
END
GridView and its assigned SqlDataSource :
<asp:GridView ID="gvVideo" CssClass="table" runat="server" OnSelectedIndexChanged="gvVideo_SelectedIndexChanged" AutoGenerateColumns="False" DataKeyNames="VideoId,CategoryId" DataSourceID="sdVideoList">
<Columns>
<asp:BoundField DataField="VideoId" Visible="false" HeaderText="VideoId" InsertVisible="False" ReadOnly="True" SortExpression="VideoId" />
<asp:BoundField DataField="VideoLink" HeaderText="Video Link" SortExpression="VideoLink" />
<asp:BoundField DataField="CategoryId" HeaderText="Category Id" SortExpression="CategoryId" />
<asp:TemplateField ItemStyle-CssClass="Center" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ImageUrl="~/images/edit.png" ID="lnkedit" Style="margin-left: 15px" CommandName="Select" runat="server" Width="20px"></asp:ImageButton>
<asp:ImageButton ImageUrl="~/images/delete.png" ID="lnkDelete" CommandName="Delete" Style="margin-left: 15px" runat="server" Width="20px" OnClientClick="return ConfirmDelete();"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdVideoList" runat="server" ConnectionString="<%$ ConnectionStrings:WebAAERT_DBConnectionString %>" DeleteCommand="VideoGalleryDelete" DeleteCommandType="StoredProcedure" SelectCommand="VideoGallerySelect" SelectCommandType="StoredProcedure">
<DeleteParameters>
<asp:Parameter Name="VideoId" Type="Int32" />
</DeleteParameters>
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="CategoryId" Type="Int32" />
</SelectParameters>
I think you're misusing the DataKeyNames property of the grid view control.This property should ideally contain only the primary key field(s) to identify the current row.Also every single value set on this property will be passed through to the Delete command.
Your delete stored proc takes one parameter but two values are being passed through beacuase of DataKeyNames="VideoId,CategoryId".So you can do what #Chris Flynn suggested or change your grid view to DataKeyNames="VideoId"
I have just started to learn how to use the Gridview Control to display SQL data. I have been able to get almost everything to work except for displaying the more user friendly information for one of my data fields that I populate from a lookup table. The entire concept of the page I want to be able to Update, Insert and Delete new records too and for some reason I could not get these options to work when I was using the SqlDataSource so I use LinqDataSource and all is now working (except I haven’t figured out Insert yet…a separate question)
I am also using the controls tabs in Visual Studio to choose and edit the attributes of the controls so kind of using the wizards and not hand coding the example.
What I cannot figure out is how to make my column with employeetypeid that contains the foreign key from the employeetypelookup table to show the employeetype text value for the user so this makes more sense. I found a “Walkthrough: Displaying a Drop-Down List While Editing in the GridView Web Server Control“ and this works perfectly. When I go into edit mode the dropdownlist shows the employeetype text and when I choose a different type, the appropriate employeetype id gets stored in the database.
So how can I modify something (the Datasource???) to display the employeetype text in the DataGrid.
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="SNRmain.SNRmainDataContext" EntityTypeName="" OrderBy="lastname, preferredfirstname" Select="new (personnelid, lastfirstname)" TableName="masterpersonnellastpreferreds"></asp:LinqDataSource>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="LinqDataSource1" DataTextField="lastfirstname" DataValueField="personnelid">
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="SNRmain.SNRmainDataContext" EnableDelete="True" EnableInsert="True" EnableUpdate="True" EntityTypeName="" TableName="tblappointmentdates" Where="personnelid == #personnelid" OrderBy="startdate desc">
<WhereParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="personnelid" PropertyName="SelectedValue" Type="Int32" />
</WhereParameters>
</asp:LinqDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="snrappointmentid" DataSourceID="LinqDataSource2">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="startdate" HeaderText="startdate" SortExpression="startdate" />
<asp:BoundField DataField="endingdate" HeaderText="endingdate" SortExpression="endingdate" />
<asp:TemplateField HeaderText="employeetypeid" SortExpression="employeetypeid">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="LinqDataSource3" DataTextField="employeetypetext" DataValueField="employeetypeid" SelectedValue='<%# Bind("employeetypeid", "{0}") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("employeetypeid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="apptcomment" HeaderText="apptcomment" SortExpression="apptcomment" />
<asp:BoundField DataField="dateentered" HeaderText="dateentered" SortExpression="dateentered" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource3" runat="server" ContextTypeName="SNRmain.SNRmainDataContext" EntityTypeName="" OrderBy="employeetypetext" Select="new (employeetypeid, employeetypetext)" TableName="tblemployeetypelookups">
</asp:LinqDataSource>
I have tried to modify the LinqDataSource2 to include a statement like the one below but that does not work and I get an error that does not make sense to me. "System.Web.Query.Dynameic.ParseException: Syntax error.
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="SNRmain.SNRmainDataContext" EntityTypeName="" Select="snrappointmentid,
personnelid, startdate,
endingdate, employeetypeid,
tblemployeetypelookup.employeetypetext
from tblappointmentdates
join tblemployeetypelookups on tblappointmentdates.employeetypeid = tblemployeetypelookups.employeetypeid" TableName="tblappointmentdates" Where="personnelid == #personnelid">
<WhereParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="personnelid" PropertyName="SelectedValue" Type="Int32" />
</WhereParameters>
</asp:LinqDataSource>
thanks in advance.
Ok if I understood correctly what you should do is to pass the employeetypeid in a function and retrieve the text and bind that to control like this.
from
<asp:Label ID="Label1" runat="server" Text='<%# Bind("employeetypeid") %>'></asp:Label>
to
<asp:Label ID="Label1" runat="server" Text='<% #GetEmployeeName(Eval("employeetypeid"))%>' runat="server" />
so now GetEmployeeName is a server function you would write to fetch name from id.
protected string GetEmployeeName(int employeetypeid)
{
//What ever is the way to query and return from here
}
Also as side note I noticed you do naming like Label1 which is very poor practice.
I have created a GridView in Visual Studio 2010.
The information displayed in the GridView is controlled by a dropdown list.
Can I add a "Show all" option to the dropdown list so that the GridView shows all the data?
This is what I have so far...
Dropdown list
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="dorpDownList2" DataTextField="Type" DataValueField="Type" AppendDataBoundItems="true"
AutoPostBack="True">
<asp:ListItem Value="0" Text="Select a type"></asp:ListItem>
</asp:DropDownList>
GridView code
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1" ShowHeaderWhenEmpty="True" emptydatatext="No data was found.">
<Columns>
<asp:BoundField DataField="OrgName" HeaderText="Organisation"
SortExpression="OrgName" />
<asp:BoundField DataField="ProjectTitle" HeaderText="Project title"
SortExpression="ProjectTitle" />
<asp:BoundField DataField="Type" HeaderText="Type"
SortExpression="Type" />
<asp:BoundField DataField="Amount"
HeaderText="Amount" SortExpression="Amount"
DataFormatString="{0:c}" />
<asp:HyperLinkField DataNavigateUrlFields="OrgName"
DataNavigateUrlFormatString="orgDetails.aspx?OrgName={0}"
HeaderText="Details" Text="Organisation details" />
</Columns>
</asp:GridView>
SqlDataSource1
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT [OrgName], [ProjectTitle], [Type], [Amount] FROM [tabRequest] WHERE [Type] = #Type">
</asp:SqlDataSource>
I can obviously add "Show all" to the drop down list using asp:ListItem but how do I add the functionality to make that actually show all the results?
Any help would be greatly appreciated.
Thanks,
James
The easiest way is via the Configure Data Source context menu. You already have a parameter, as you move through the configuration process you come to a dialog called Define Parameters. You should see "Type" listed in the Parameters list. Select it and change the Parameter source to "Control" and when prompted specify the DDL.
The trick is that you need to effectively remove the condition on your select where clause when Type is 0. This is easily done with an IF statement.
I have this code that present a gridview that retrieved the data from 2 datasources.
each line present an order details and the last column present the order status.
the order status should be updateable in a dropdownlist .
<asp:GridView runat="server" AutoGenerateColumns="False" DataSourceID="OrderDataSource"
CssClass="DataTables">
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:BoundField DataField="oID" HeaderText="oId" SortExpression="oId" ReadOnly="true" />
<asp:BoundField DataField="DateOpened" HeaderText="DateOpened" SortExpression="DateOpened"
ReadOnly="true" />
<asp:BoundField DataField="rName" HeaderText="rName" SortExpression="rName" ReadOnly="true" />
<asp:BoundField DataField="DateOfArrival" HeaderText="DateOfArrival" SortExpression="DateOfArrival"
ReadOnly="true" />
<asp:BoundField DataField="Quantity" HeaderText="Quantity" SortExpression="Quantity"
ReadOnly="true" />
<asp:BoundField DataField="sName" HeaderText="sName" SortExpression="sName" ReadOnly="true" />
<asp:TemplateField HeaderText="osName" SortExpression="osName">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="StatusDataSource"
DataTextField="osName" DataValueField="osID" SelectedValue='<%# Bind("osName") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("osName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="OrderDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:igroup9_prodConnectionString %>"
SelectCommand="spGetOrdersListForProject" SelectCommandType="StoredProcedure"
UpdateCommand="Update[Orders] set [osID] =#osID where [oID]=#oID">
<SelectParameters>
<asp:ControlParameter ControlID="ProjectIDHolder" DefaultValue="" Name="ProjectID"
PropertyName="Value" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="osID" Type="Int32" />
<asp:Parameter Name="oID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="StatusDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:igroup9_prodConnectionString %>"
SelectCommand="spGetOrderStatus" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
The problem is that when i'm trying to edit a column in the gridview i get this error: (after i click the edit button)
Server Error in '/Maestro' Application.
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Error seems clear to me. The values in the DropDownList don't contain the value that you're trying to set as the selected value. This is probably because the values are from the osID column and the selected value is from the osName column. Whatever the selected value ends up being, it should come from the data source which means you should probably use the same column (or a foreign key relationship).
You should probably change it to...
SelectedValue='<%# Bind("osID") %>'
and make sure that spGetOrdersListForProject returns the osID.
I am having some problems passing parameters to a DELETE command, and cant seem to get a good understanding on how it works.
<asp:SqlDataSource ID="sdsPropertyList"
runat="server"
ProviderName="<%$ appSettings:ProviderName %>"
ConnectionString="<%$ appSettings:ConnectionString %>"
SelectCommand="selPropertyByAcntID"
SelectCommandType="StoredProcedure"
OnSelecting="sdsPropertyList_Selecting"
OnSelected="sdsPropertyList_Selected"
DeleteCommand="delPropertyByPropID"
DeleteCommandType="StoredProcedure"
OnDeleting="sdsPropertyList_Deleting"
OnDeleted="sdsPropertyList_Deleted">
<SelectParameters>
<asp:Parameter Name="in_acntID" Type="Int32" DefaultValue="0" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="in_acntID" Type="Int32" DefaultValue="0" />
<asp:Parameter Name="in_propID" Type="Int32" DefaultValue="0" />
</DeleteParameters>
</asp:SqlDataSource>
<asp:GridView ID="gvProperty" runat="server" DataSourceID="sdsPropertyList"
AutoGenerateColumns="false" CssClass="gvPropList">
<Columns>
<asp:BoundField HeaderText="ID" InsertVisible="true" DataField="prop_id" ReadOnly="true" Visible="False" />
<asp:BoundField HeaderText="Property" DataField="prop_title"
ItemStyle-CssClass="gvPropTitle" >
<ItemStyle CssClass="gvPropTitle" />
</asp:BoundField>
<asp:BoundField HeaderText="Units" DataField="unitCount"
ItemStyle-CssClass="gvUnitCount" >
<ItemStyle CssClass="gvUnitCount" />
</asp:BoundField>
<asp:BoundField DataField="prop_lastmodified" HeaderText="Last Modified"
ItemStyle-CssClass="gvDate" DataFormatString="{0:M/dd/yyyy hh:mm tt}" >
<ItemStyle CssClass="gvDate" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnEdit" runat="server" CommandName="EditRecord" Text="Edit" CommandArgument='<%# Eval("prop_id") %>'></asp:LinkButton>
<asp:LinkButton ID="lbtnDelete" runat="server" CommandName="Delete" Text="Delete" CommandArgument='<%# Eval("prop_id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnAdd" runat="server" CommandName="AddRecord" Text="Add" CommandArgument='<%# Eval("prop_id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="headerPropList"/>
<RowStyle CssClass="gvPropRow" />
</asp:GridView>
protected void sdsPropertyList_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
int userID = Convert.ToInt32(Page.User.Identity.Name);
if (userID != 0)
e.Command.Parameters["in_acntID"].Value = userID;
}
protected void sdsPropertyList_Deleting(object sender, SqlDataSourceCommandEventArgs e)
{
int userID = Convert.ToInt32(Page.User.Identity.Name);
if (userID != 0)
{
e.Command.Parameters["in_acntID"].Value = userID;
}
}
The SELECT statement is straightforward which requires one input parameter of userID.
However, the DELETE statement, requires 2 parameter inputs.
in_acntID = userID
in_propID = the boundfield datafield prop_id
What am I doing wrong? and should the CommandName and CommandArgument be passed at the ItemTemplate level if I have it defined at the SqlDataSource level?
I want the delete button to achieve the following:
delete records from table(s) in DB
remove the row from the gridview
UPDATE
After some additional research, I've found that, the NAME for parameters and HeaderText for Boundfield must be the same so that the values within your gridview can be used by the SQL commands of the datasource.
With the exception of the initial select commant, i have removed all the code behind references.
All is working corrently now.
According to the MSDN documentation, you need to specify the DataKeyNames on the gridView:
"Use the DataKeyNames property to specify the field or fields that represent the primary key of the data source. You must set the DataKeyNames property in order for the automatic update and delete features of the GridView control to work. The values of these key fields are passed to the data source control in order to specify the row to update or delete."
e.g. if the id was in a listbox or dropdown
<DeleteParameters>
<asp:ControlParameter ControlID="controlname" Name="id" PropertyName="SelectedValue" Type="Int32" />
</DeleteParameters>
i have used the above successfully for deleting . this could work for textboxes or labels. If you are handling the event , why not just take the entire delete process to the even handler ? Specify the entire sql setup including connection , command execution there . This method has also worked for me .
After some additional research, I've found that, the NAME for parameters and HeaderText for Boundfield must be the same so that the values within your gridview can be used by the SQL commands of the datasource.
With the exception of the initial select commant, i have removed all the code behind references.
All is working corrently now.
<asp:SqlDataSource ID="sdsPropertyList"
runat="server"
ProviderName="<%$ appSettings:ProviderName %>"
ConnectionString="<%$ appSettings:ConnectionString %>"
SelectCommand="selPropertyByAcntID"
SelectCommandType="StoredProcedure"
OnSelecting="sdsPropertyList_Selecting"
DeleteCommand="delPropertyByPropID"
DeleteCommandType="StoredProcedure"
OnDeleted="sdsPropertyList_Deleted" >
<SelectParameters>
<asp:Parameter Name="acnt_id" Type="Int32" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="acnt_id" Type="Int32" />
<asp:Parameter Name="prop_id" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
<asp:GridView ID="gvProperty" runat="server" DataSourceID="sdsPropertyList"
AutoGenerateColumns="false" CssClass="gvPropList" DataKeyNames="acnt_id, prop_id">
<Columns>
<asp:BoundField HeaderText="acnt_id" InsertVisible="true" DataField="acnt_id" ReadOnly="true" Visible="False" />
<asp:BoundField HeaderText="prop_id" InsertVisible="true" DataField="prop_id" ReadOnly="true" Visible="False" />
<asp:BoundField HeaderText="Property" DataField="prop_title">
<ItemStyle CssClass="gvPropTitle" />
</asp:BoundField>
<asp:BoundField HeaderText="Units" DataField="unitCount" >
<ItemStyle CssClass="gvUnitCount" />
</asp:BoundField>
<asp:BoundField DataField="prop_lastmodified" HeaderText="Last Modified"
ItemStyle-CssClass="gvDate" DataFormatString="{0:M/dd/yyyy hh:mm tt}" >
<ItemStyle CssClass="gvDate" />
</asp:BoundField>
<asp:BoundField HeaderText="Active" DataField="prop_active">
<ItemStyle CssClass="gvPropActive" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnEdit" runat="server" CommandName="EditRecord" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="lbtnDelete" runat="server" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnAdd" runat="server" CommandName="AddRecord" Text="Add"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="headerPropList"/>
<RowStyle CssClass="gvPropRow" />
</asp:GridView>