My update sql procedure is
ALTER PROCEDURE [dbo].[usp_update]
#ID uniqueidentifier,
#Period nvarchar(6),
#News nvarchar(max),
#Editor nvarchar(30)
as
begin
update table1
set News= #News, Editor=#Editor, LastRevNT=getdate()
where ID=#ID and Period=#Period
end
my asp.net grid view is
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
<Columns>
asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="Period" HeaderText="Period" SortExpression="Period" ReadOnly="True"/>
<asp:BoundField DataField="News" HeaderText="News" SortExpression="News" />
<asp:BoundField DataField="Editor" HeaderText="Editor" SortExpression="Editor" ReadOnly="True" />
</Columns>
datasource is
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="usp_select" SelectCommandType="StoredProcedure" UpdateCommand="usp_update" UpdateCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter DefaultValue="" Name="ID" SessionField="SelectedID" dbType="guid" />
</SelectParameters>
<UpdateParameters>
<asp:SessionParameter DefaultValue="" Name="ID" SessionField="SelectedID" dbType="guid" />
<asp:SessionParameter DefaultValue="" Name="Editor" SessionField="SelectedEditor" dbType="string"/>
<asp:Parameter Name="Period" Type="String" />
<asp:Parameter Name="News" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
Problem is that when I update the table, I need both ID and [Period] to get the unique record.
And in gridview, I don't want to [period] to be modified. When I set the bound for period to be read-only, then I fail to access the value of period, thus fail to update the right record.
I wonder how I can handle the problem?
Thanks for advice!
I added DataKeyNames = "ID,Period" in my aspgridview, and it works ok now. Thanks for advice!
Related
I need to make a delete statement for results that are displayed in my GridView. This delete statement must use some of the columns themselves as parameters in the delete statement
My gridview is this:
<asp:GridView
ID="GridView1"
runat="server"
AllowPaging="True"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
style="z-index: 1; left: 222px; top: 139px; position: absolute; height: 299px; width: 458px" DataKeyNames="Id">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="Column1" HeaderText="Column1" SortExpression="Column1" ReadOnly="True" Visible="False" />
<asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" ReadOnly="True" Visible="False" />
<asp:BoundField DataField="department" HeaderText="department" SortExpression="department" />
<asp:BoundField DataField="courseCode" HeaderText="courseCode" SortExpression="courseCode" />
<asp:BoundField DataField="courseName" HeaderText="courseName" SortExpression="courseName" />
</Columns>
</asp:GridView>
I need to use "Column1" and "Id" from my SELECT query (That is stored within a stored procedure) for the DELETE query that is ran when the "Delete" button is hit on my Gridview. A problem that may be happening is my select statement uses one primary key, but my delete statement needs two primary keys (which are "Column1" and "Id"), so I do not know what to set DataKeyNames to.
Here is the SQLDataSource:
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="GetPreviouslyTakenCourses"
SelectCommandType="StoredProcedure"
DeleteCommand="DELETE FROM UserHasCourse WHERE UserHasCourse.userId=#Column1 AND UserHasCourse.courseId=#Id"
DeleteCommandType="Text">
<SelectParameters>
<asp:SessionParameter DefaultValue="1" Name="userId" SessionField="userId" Size="10" Type="Int32" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="Column1" Type="Int32" />
<asp:Parameter Name="Id" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
As of now nothing happens when I hit "Delete" on the GridView, so I can imagine the problem I am having is almost fixed. I can imagine there is a problem with <asp:Parameter but I don't know what.
DataKeyNames should be set to
DataKeyNames="Column1,Id"
And this problem is fixed
I am trying to update values in my access database, however it does not work in some cases.
The code :
<form id="form1" runat="server">
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/Database1.mdb"
DeleteCommand="UPDATE DT_Person SET Deleted = NOW() WHERE (Person_Ref = ?)"
InsertCommand="INSERT INTO [DT_Person] ([Person_Ref], [Created], [Updated], [Deleted], [Person_Name], [Person_No]) VALUES (?, ?, ?, ?, ?, ?)"
OldValuesParameterFormatString="original_{0}"
SelectCommand="SELECT * FROM [DT_Person]"
UpdateCommand="UPDATE DT_Person SET Updated = NOW(), Person_Name = ?, Person_No = ? WHERE (Person_Ref = ?)">
<DeleteParameters>
<asp:Parameter Name="original_Person_Ref" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Created" Type="DateTime" />
<asp:Parameter Name="Updated" Type="DateTime" />
<asp:Parameter Name="Deleted" Type="DateTime" />
<asp:Parameter Name="Person_Name" Type="String" />
<asp:Parameter Name="Person_No" Type="String" />
<asp:Parameter Name="original_Person_Ref" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="Person_Ref" Type="Int32" />
<asp:Parameter Name="Created" Type="DateTime" />
<asp:Parameter Name="Updated" Type="DateTime" />
<asp:Parameter Name="Deleted" Type="DateTime" />
<asp:Parameter Name="Person_Name" Type="String" />
<asp:Parameter Name="Person_No" Type="String" />
</InsertParameters>
</asp:AccessDataSource>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3"
DataKeyNames="Person_Ref" DataSourceID="AccessDataSource1">
<RowStyle ForeColor="#000066" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True"
ShowSelectButton="True" />
<asp:BoundField DataField="Person_Ref" HeaderText="Person_Ref"
InsertVisible="False" ReadOnly="True" SortExpression="Person_Ref" />
<asp:BoundField DataField="Created" HeaderText="Created"
SortExpression="Created" />
<asp:BoundField DataField="Updated" HeaderText="Updated"
SortExpression="Updated" />
<asp:BoundField DataField="Deleted" HeaderText="Deleted"
SortExpression="Deleted" />
<asp:BoundField DataField="Person_Name" HeaderText="Person_Name"
SortExpression="Person_Name" />
<asp:BoundField DataField="Person_No" HeaderText="Person_No"
SortExpression="Person_No" />
</Columns>
As you can see, the delete command
(DeleteCommand="UPDATE DT_Person SET Deleted = NOW() WHERE (Person_Ref = ?)" )
is really an update statement and this works fine . However the actual update statement does not work on the web page. The weird thing is, if you test the query in the 'query builder' it works fine.
Really need some help here.
TIA
P.S. Im using Visual Studio 2008 and using the data source builder each time
Windows 7 (if that's what you're using) has been known to make a copy of Access databases down in the Debug files and use the copy for all data changes. You might want to check that the database you are actually accessing is the copy you think it is.
Do a search for files with the same name across your whole development machine. You might be surprised what turns up.
Solution at the bottom.
I receive the following error when trying to update records:
Must declare Scalar Variable #PaymentTermID
Problem is, #PaymentTermID should be defined already in the Update parameters. The 2 functions for onrowdatabound and onrowupdate are tweaked versions of the ones found here for the DropDownList: GridViewRow.DataItem Property. Delete works fine.
No new lines are added, just names changed around. Any help would be appreciated, I am not exactly used to working with asp objects.
<asp:GridView ID="GridView1" onrowdatabound="GridView1_RowDataBound" onrowupdating="GridView1_RowUpdating" runat="server" AutoGenerateColumns="False" DataKeyNames="PaymentTermID" DataSourceID="SqlDataSource1" CellPadding="1" CellSpacing="2">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="Key Contract Date" SortExpression="Key Contract Date">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="Key_Contract_Date" DataValueField="Key_Contract_Date" />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Production_DatabaseConnectionString %>"
SelectCommand="SELECT DISTINCT [Key Contract Date] AS Key_Contract_Date FROM [tblPRJ_PaymentTerms]" />
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("[Key Contract Date]") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Due Date" HeaderText="Due Date" SortExpression="Due Date" />
<asp:BoundField DataField="Percent Due" HeaderText="Percent Due" SortExpression="Percent Due" />
<asp:BoundField DataField="Custom Description" HeaderText="Custom Description" SortExpression="Custom Description" />
</Columns>
<HeaderStyle Font-Bold="True" ForeColor="#666666" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Production_DatabaseConnectionString %>"
SelectCommand="SELECT * FROM [tblPRJ_PaymentTerms] WHERE ([Job Number] = #Job_Number)"
DeleteCommand="DELETE FROM [tblPRJ_PaymentTerms] WHERE [PaymentTermID] = #PaymentTermID"
InsertCommand="INSERT INTO [tblPRJ_PaymentTerms] ([Job Number], [Key Contract Date], [Due Date], [Percent Due], [Custom Description]) VALUES (#Job_Number, #Key_Contract_Date, #Due_Date, #Percent_Due, #Custom_Description)"
UpdateCommand="UPDATE [tblPRJ_PaymentTerms] SET [Job Number] = #Job_Number, [Key Contract Date] = #Key_Contract_Date, [Due Date] = #Due_Date, [Percent Due] = #Percent_Due, [Custom Description] = #Custom_Description WHERE [PaymentTermID] = #PaymentTermID">
<DeleteParameters>
<asp:Parameter Name="PaymentTermID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Job_Number" Type="String" />
<asp:Parameter Name="Key_Contract_Date" Type="String" />
<asp:Parameter Name="Due_Date" Type="DateTime" />
<asp:Parameter Name="Percent_Due" Type="Decimal" />
<asp:Parameter Name="Custom_Description" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:ControlParameter ControlID="txtCurrentJobNumber" Name="Job_Number" PropertyName="Text" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Job_Number" Type="String" />
<asp:Parameter Name="Key_Contract_Date" Type="String" />
<asp:Parameter Name="Due_Date" Type="DateTime" />
<asp:Parameter Name="Percent_Due" Type="Decimal" />
<asp:Parameter Name="Custom_Description" Type="String" />
<asp:Parameter Name="PaymentTermID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
SOLUTION: There were multiple problems happening here. First and foremost, GuthMD was correct in his assessment of parameters needing a reference in terms of either a boundfield, templatefield, or other source (such as a control in the case of a control parameter). Simply creating an asp:boundfield for the PaymentTermID and setting the Visible property to false fixed the problem I posted about.
The other problem was that the database was setup poorly, and had spaces in column names. The OLEDB driver doesn't like that, and causes errors when you try to write back to the database and you have spaces in column names (even if it's encased in brackets []). After fixing the names in SQL, then revisiting our code and rewriting most of the SQL code for it, things started behaving as expected.
Thanks again for your help.
I've been looking through the MSDN documentation for Using Parameters, and it seems that for the binding to be created between the GridView and your SqlDataSource that your GridView is going to need to have BoundField elements corresponding to the Parameter elements.
Add the following to the <Columns> of your GridView:
<asp:BoundField DataField="Job_Number" Visible="false" />
<asp:BoundField DataField="Key_Contract_Date" Visible="false" />
<asp:BoundField DataField="Due_Date" Visible="false" />
<asp:BoundField DataField="Percent_Due" Visible="false" />
<asp:BoundField DataField="Custom_Description" Visible="false" />
<asp:BoundField DataField="PaymentTermID" Visible="false" />
1-The problem occurs when datasource is OleDb not SQLclient.
Change the DataSource1 to :
providerName="System.Data.SqlClient"
2-Make sure valid binding field in grid definition DataKeyNames="id_field"
I'm getting the dreaded 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value error when trying to filter a drop down list in a templatefield using one of the other boundfield values (I'm trying to get a list of employees based on their department - i.e. the user can change the employee but only to another member of the same department).
Here's the code:
<asp:GridView ID="Rotas" runat="server" AllowSorting="True"
DataSourceID="SqlDataSource3" AutoGenerateEditButton="True" DataKeyNames="DateFrom,DateTo,DepartmentId"
AutoGenerateColumns="False" OnRowUpdating="Rotas_RowUpdating">
<Columns>
<asp:BoundField DataField="DateFrom" HeaderText="DateFrom" ReadOnly="True"
SortExpression="DateFrom" />
<asp:BoundField DataField="DateTo" HeaderText="DateTo" ReadOnly="True"
SortExpression="DateTo" />
<asp:TemplateField HeaderText="Employee Name" SortExpression="EmployeeName">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource4" DataTextField="EmployeeName"
DataValueField="EmployeeName" SelectedValue='<%# Bind("EmployeeName") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("EmployeeName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DepartmentId" HeaderText="DepartmentId"
ReadOnly="True" SortExpression="DepartmentId" />
<asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" ReadOnly="False"
SortExpression="EmployeeId" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:OnCallRotaConnectionString %>"
SelectCommand="SELECT r.DateFrom, r.DateTo, e.EmployeeName, e.EmployeeId, r.departmentid
FROM
dbo.[Rota] r INNER JOIN
dbo.[Employee] AS e ON r.EmployeeId = e.EmployeeId
WHERE (r.DateTo >= GETDATE()) "
UpdateCommand="UPDATE [Rota] SET [EmployeeId] = (select employeeid from employee where employeename = #EmployeeName),
[departmentid] = (select departmentid from employee where employeename = #EmployeeName)
WHERE [DateFrom] = #DateFrom AND [DateTo] = #DateTo AND [DepartmentId] = #DepartmentId">
<UpdateParameters>
<asp:Parameter Name="DateTo" Type="DateTime" />
<asp:Parameter Name="DateFrom" Type="DateTime" />
<asp:Parameter Name="DepartmentId" Type="Int16" />
<asp:Parameter Name="EmployeeId" Type="Int16" />
<asp:Parameter Name="EmployeeName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
</p>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:OnCallRotaConnectionString %>"
onselecting="SqlDataSource4_Selecting"
SelectCommand="SELECT [EmployeeName] FROM [Employee] where DepartmentId=#DepartmentId"
>
<SelectParameters>
<asp:ControlParameter ControlID="Rotas" Name="DepartmentId"
PropertyName="SelectedValue" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>
Really can't see what I'm doing wrong. If I don't use the Select Parameter and just a 'select employeename from employee' then the whole list of employees is displayed fine. As soon as I try and use a controlparameter it falls over. Help! :)
Thanks in advance for any assistance offered.
I think the problem is that your SqlDataSource that returns the list of employees for a department isn't returning any rows, and I think this is because the ControlParameter isn't right. Although you've done the right thing by pointing it at the Rotas GridView and the SelectedValue property, there are three fields used in the DataKeyNames property (DateFrom, DateTo, DepartmentId), and I believe you're currently passing the DateFrom value into your query - hence, no results.
What I think you need to use in the PropertyName of the ControlParameter instead of the SelectedValue property of Rotas is the SelectedDataKey - there's details on MSDN here although the demo code there isn't particularly useful. However the important line is:
If you are creating a ControlParameter
object and want to access a key field
other than the first field, use the
indexed SelectedDataKey property in
the PropertyName property of the
ControlParameter object
So from that I think what you need is:
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:OnCallRotaConnectionString %>"
onselecting="SqlDataSource4_Selecting"
SelectCommand="SELECT [EmployeeName] FROM [Employee] where DepartmentId=#DepartmentId"
>
<SelectParameters>
<asp:ControlParameter ControlID="Rotas" Name="DepartmentId"
PropertyName="SelectedDataKey[2]" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>
Without a copy of your data I can't test it, but give it a go and see what you get...
In a Telerik RadGrid, the user has the ability to add a row and edit an existing one. It appears that the grids actually force a postback to occur before the UI controls are rendered on the screen. I'm noticing a second to two seconds delay from the time the button is clicked to the time the controls appear. This seems about a second to two seconds too long. Here is my code, I'm not exactly sure what the bug is.
I apologize in advance for the "whatz wrongz with me codez post", but this seems like the easiest way to go about this one. Again, I have a performance issue and would like to figure out how to solve it in terms of what code needs to be tweaked.....
<asp:UpdatePanel ID="upPhone" runat="server">
<contenttemplate>
<telerik:RadGrid runat="server" ID="gridPhone" DataSourceID="dsPhone" AutoGenerateColumns="False"
Width="100%" AllowAutomaticDeletes="True" AllowAutomaticInserts="True"
GridLines="None" Skin="Vista" AllowAutomaticUpdates="True"
ondatabound="gridPhone_DataBound" onitemdeleted="gridPhone_ItemDeleted"
oniteminserted="gridPhone_ItemInserted"
onitemupdated="gridPhone_ItemUpdated"
onneeddatasource="gridPhone_NeedDataSource">
<MasterTableView DataKeyNames="phone_id" CommandItemDisplay="Top"
EditMode="InPlace" AllowFilteringByColumn="False">
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
<ItemStyle CssClass="MyImageButton" />
</telerik:GridEditCommandColumn>
<telerik:GridBoundColumn DataField="phone_id" ReadOnly="true" UniqueName="phone_id"
Visible="false">
</telerik:GridBoundColumn>
<telerik:GridDropDownColumn DataField="d_phone_type_id" DataSourceID="dsPhoneType"
UniqueName="d_phone_type_id" DataType="System.Int32" ListValueField="d_phone_type_id"
ListTextField="name" HeaderText="Type">
</telerik:GridDropDownColumn>
<telerik:GridTemplateColumn HeaderText="Number" SortExpression="number" UniqueName="number">
<ItemTemplate>
<asp:Label runat="server" ID="lblPhoneNumber" Text='<%# Eval("number", "{0:(###) ###-####}") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNumber" MaxLength="10" runat="server" Text='<%# Bind("number") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="description" UniqueName="description" HeaderText="Description">
</telerik:GridBoundColumn>
<telerik:GridCheckBoxColumn DataField="isprimary" UniqueName="isprimary" HeaderText="Primary"
DataType="System.Int16">
</telerik:GridCheckBoxColumn>
<telerik:GridButtonColumn ConfirmText="Delete this number?" ConfirmDialogType="RadWindow"
ConfirmTitle="Delete" ButtonType="ImageButton" CommandName="Delete" Text="Delete"
UniqueName="DeleteColumn">
<ItemStyle HorizontalAlign="Center" CssClass="MyImageButton" />
</telerik:GridButtonColumn>
</Columns>
<EditFormSettings>
<EditColumn UniqueName="EditCommandColumn1">
</EditColumn>
</EditFormSettings>
</MasterTableView>
<ClientSettings>
<Selecting AllowRowSelect="True" />
</ClientSettings>
</telerik:RadGrid>
<asp:ObjectDataSource ID="dsPhoneType" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetPhoneTypes"
TypeName="DataAccess"></asp:ObjectDataSource>
<asp:SqlDataSource ID="dsPhone" runat="server" ConnectionString="<%$ ConnectionStrings:TBD %>"
DeleteCommand="DELETE FROM [phone] WHERE [phone_id] = #phone_id" InsertCommand="INSERT INTO [phone] ([person_id],[d_phone_type_id], [number], [description], [isprimary]) VALUES (#person_id,#d_phone_type_id, #number, #description, #isprimary)"
SelectCommand="get_PhoneById" UpdateCommand="UPDATE [phone] SET [d_phone_type_id] = #d_phone_type_id, [number] = #number, [description] = #description, [isprimary] = #isprimary WHERE [phone_id] = #phone_id"
SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="lblID" Name="person_id" PropertyName="Text" Type="Int32" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="phone_id" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="d_phone_type_id" Type="Int32" />
<asp:Parameter Name="number" Type="Int64" />
<asp:Parameter Name="description" Type="String" />
<asp:Parameter Name="isprimary" Type="Boolean" />
<asp:Parameter Name="phone_id" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:ControlParameter ControlID="lblID" Name="person_id" PropertyName="Text" />
<asp:Parameter Name="d_phone_type_id" Type="Int32" />
<asp:Parameter Name="number" Type="Int64" />
<asp:Parameter Name="description" Type="String" />
<asp:Parameter Name="isprimary" Type="Boolean" />
</InsertParameters>
</asp:SqlDataSource>
</contenttemplate>
</asp:UpdatePanel>
Just a couple of things to check:
Are you duplicating the bind behaviour in the gridPhone_NeedDataSource event, your ItemUpdated, Deleted and Inserted events, and the native Rad Grid binding behviour (by using a asp:SqlDataSource control)? It would be useful to see your code-behind to see if you are or not.
How many records do you have in the grid? I find if I have a large number of items in the Grid and have some of the advanced features turned on (I've noticed you've got row selecting enabled) the grid grinds to a halt.
If none of these work/apply to your situation then it maybe worth checking the performance section of their site.
I am seeing that you are using DataSourceID="dsPhone" and onneeddatasource="gridPhone_NeedDataSource"
not sure if you need both. Also make sure you dont do a DataBind() else where in your code (page_Load or any other place) since you already have OnNeedDataSource event attached to the grid