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
Related
I use griview propertied while editing or deleting records without coding
When I click on edit button my image is also converted into a TextBox control,
I want to take
Fileupload control instead of textBox control.
For it which property shoule i set?
my code is as follow
<asp:GridView ID="GridView1" runat="server" Width="197px"
AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="SqlDataSource2" AllowPaging="True">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID"
InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
<asp:ImageField DataImageUrlField="Image" HeaderText="PHOTO">
<ControlStyle Height="100px" Width="100px" />
</asp:ImageField>
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="status" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
And here is the code of SqlDataSource2:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionStringnewdb %>"
DeleteCommand="delete from Product where ProductID=#ProductID"
SelectCommand="SELECT * FROM [Product]"
UpdateCommand="update Product set ProductName=#ProductName,Status=#Status where ProductID=#ProductID ">
<DeleteParameters>
<asp:ControlParameter ControlID="GridView1" Name="ProductID"
PropertyName="SelectedValue" />
</DeleteParameters>
<UpdateParameters>
<asp:ControlParameter ControlID="GridView1" Name="ProductName"
PropertyName="SelectedValue" />
<asp:Parameter Name="ProductID" />
</UpdateParameters>
</asp:SqlDataSource>
Use the EditItemTemplate and add the FileUpload control:
... other columns ...
</EditItemTemplate>
<ItemTemplate>
<asp:FileUpload id="FileUpload1" runat="server">
</asp:FileUpload>
</ItemTemplate>
</asp:TemplateField>
... other columns ...
Here's a tutorial: http://msdn.microsoft.com/en-us/library/ms972948.aspx
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"
Sorry for the convoluted title, but that is the best way I could think to phrase it.
Basically, I have a column of data that is a URL (lets call it URL-A), and another that is hidden which is also a URL(URL-B). I have a function called ConvertURL(string URLin) in the codebehind that will take URL-A and turn it into URL-B.
So in this gridview, if someone were to edit an entry using the native gridview/datasource functionality and change URL-A, how do I get it to run this new URL-A through ConvertURL() and update the URL-B field?
Here is a simple representation of the code (not the actual code):
Code-behind function:
public string ConvertURL(string URLin)
{
Int32 iLocation = URLin.IndexOf("WWW.XYZ.COM");
if (iLocation >= 0)
{
string checkurl = URLin.Replace("WWW.XYZ.COM", "STAGING.XYZ.COM");
return checkurl;
}
else
{
return URLin;
}
}
Data-Source:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:My_AppConnectionString %>"
SelectCommand="SELECT [URL_A], [URL_B], [URLName] FROM [My_App] WHERE ([IsActive] = #IsActive)"
OldValuesParameterFormatString="original_{0}"
UpdateCommand="UPDATE [My_App] SET [URL_A] = #URL_A, [URL_B] = #URL_B, [URLName] = #URLName, [IsActive] = #IsActive WHERE [ID] = #original_ID">
<SelectParameters>
<asp:Parameter DefaultValue="True" Name="IsActive" Type="Boolean" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="URL_A" Type="String" />
<asp:Parameter Name="URL_B" Type="String" />
<asp:Parameter Name="URLName" Type="String" />
<asp:Parameter Name="IsActive" Type="boolean" />
<asp:Parameter Name="original_ID" Type="Int32" />
<asp:Parameter Name="original_URL_A" Type="String" />
<asp:Parameter Name="original_URL_B" Type="String" />
<asp:Parameter Name="original_URLName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
And Lastly the GridView:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
onrowediting="GridView1_RowEditing"
AutoGenerateColumns="False" CellPadding="3" DataKeyNames="ID"
DataSourceID="SqlDataSource1" EnableModelValidation="False" ForeColor="Black"
GridLines="Vertical" AllowSorting="True" BackColor="White"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
AutoGenerateEditButton="True" CausesValidation="false">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" Visible="False" />
<asp:BoundField DataField="URL_A" HeaderText="URL A"
SortExpression="URL_A" />
<asp:BoundField DataField="URL_B" HeaderText="URL B"
SortExpression="URL_B" **Visible="False"** />
<asp:BoundField DataField="URLName" HeaderText="URL Name"
SortExpression="URLName" />
<asp:CheckBoxField DataField="IsActive" HeaderText="Active"
SortExpression="IsActive" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
</asp:GridView>
So to summarize: A user will see a gridview with 3 fields to edit, one of which is URL_A (URL_B is hidden). When they hit edit and update the URL_A field I want to run URL_A through the ConvertURL() function and use that output as the data for URL_B when the update is performed.
I appreciate the help in advance!
Use the RowUpdating event of the grid view and change the new value for URL_B. In that event you will have access to the old values of the row as well as the new values. You can change the new values before they are sent to the data source for the actual update.
Add the event handler to the grid view in the ASPX:
<asp:GridView ID="GridView1" runat="server"
...
OnRowUpdating="GridView1_RowUpdating">
And in the code file handle the event:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Find the current value for URL_A
string urlA = (string)e.NewValues["URL_A"];
// Get the corresponding value for URL_B from the method
string urlB = ConvertURL(urlA);
// Set the new value for the URL_B column before it's sent to the SqlDataSource
e.NewValues["URL_B"] = urlB;
}
I'm having a wired problem with Radgrid.. Im using a Radgrid to display some results where the user can edit/update/delete them. I'm using a single SQL Server 2000 table to fetch the results... Not sure why the events are not firing in radgrid. But I am able to do it successfully using the Gridview control...
Im using .NET framework 4
Radgrid code
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteColumn="True"
AutoGenerateEditColumn="True" DataSourceID="SSDS" GridLines="None" Width="844px"
DataMember="DefaultView">
<MasterTableView DataSourceID="SSDS" DataKeyNames="id">
<Columns>
<telerik:GridBoundColumn DataField="id" HeaderText="id" ReadOnly="True" SortExpression="id"
UniqueName="id" Visible="false">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="name" HeaderText="name" SortExpression="name"
UniqueName="name">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="address" HeaderText="address" SortExpression="address"
UniqueName="address">
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<br />
<br />
<asp:SqlDataSource ID="SSDS" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringSQL %>"
ProviderName="<%$ ConnectionStrings:ConnectionStringSQL.ProviderName %>" SelectCommand="SELECT [id], [name], [address] FROM [sitelinks]"
UpdateCommand="UPDATE [sitelinks] set [name] = ? , [address] = ? where [id] = ?"
DeleteCommand="delete from sitelinks where id = ?">
<DeleteParameters>
<asp:Parameter Name="id" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="name" />
<asp:Parameter Name="address" />
<asp:Parameter Name="id" />
</UpdateParameters>
</asp:SqlDataSource>
Gridview control code (the one that works)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SSDS"
DataKeyNames="id">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
SortExpression="id" Visible="false" />
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="address" HeaderText="address" SortExpression="address" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SSDS" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringSQL %>"
DeleteCommand="delete from sitelinks where id = ?" ProviderName="<%$ ConnectionStrings:ConnectionStringSQL.ProviderName %>"
SelectCommand="select id,name,address from sitelinks" UpdateCommand="update sitelinks set name=?, address=? where id = ? ">
<UpdateParameters>
<asp:ControlParameter ControlID="GridView1" Name="name" />
<asp:ControlParameter ControlID="GridView1" Name="address" />
<asp:ControlParameter ControlID="GridView1" Name="id" />
</UpdateParameters>
<DeleteParameters>
<asp:ControlParameter ControlID="GridView1" Name="id" />
</DeleteParameters>
</asp:SqlDataSource>
Thanks
Set the AllowAutomaticUpdates/AllowAutomaticDeletes properties of the telerik grid to true and see this sample.
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