Edit / Delete table options - c#

I have a table that has Edit and Delete links in each row. I am supposed to be able to click either Edit or Delete and it would do it. The edit link works but the delete has this error:
Deleting is not supported by data source 'SqlDataSource1' unless DeleteCommand is specified.
My tables data source is sqlDataSource1.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:PayrollSystem_DBConnectionString %>"
ProviderName="<%$ ConnectionStrings:PayrollSystem_DBConnectionString.ProviderName %>"
SelectCommand="SELECT [UserID], [UserName], [UserPassword], [SecurityLevel] FROM [tblUserLogin]">
</asp:SqlDataSource>
</div>
<div align="center">
<asp:Label ID="Label1" runat="server" Text="Manage Users"></asp:Label>
<p>
<asp:Label ID="Label2" runat="server" Text="User Name:"></asp:Label>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</p>
<p>
<asp:Label ID="Label3" runat="server" Text="Password:"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</p>
<p>
<asp:Label ID="Label4" runat="server" Text="Security Level:"></asp:Label>
<asp:DropDownList ID="drpdwnlstSecurityLevel" runat="server"
onselectedindexchanged="drpdwnlstSecurityLevel_SelectedIndexChanged">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>U</asp:ListItem>
</asp:DropDownList>
</p>
<p>
<asp:Button ID="btnAddUser" runat="server" onclick="btnAddUser_Click1"
Text="Add User" />
</p>
<p>
<asp:Label ID="lblError" runat="server"></asp:Label>
</p>
</div>
<p>
</p>
<div align="center">
<asp:GridView ID="tblUserLogin" runat="server" AutoGenerateColumns="False"
DataSourceID="AccessDataSource1">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" InsertVisible="False"
SortExpression="UserID"></asp:BoundField>
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName"></asp:BoundField>
<asp:BoundField DataField="UserPassword" HeaderText="UserPassword"
SortExpression="UserPassword"></asp:BoundField>
<asp:BoundField DataField="SecurityLevel" HeaderText="SecurityLevel"
SortExpression="SecurityLevel"></asp:BoundField>
<asp:CommandField ShowEditButton="True"></asp:CommandField>
<asp:CommandField ShowDeleteButton="True"></asp:CommandField>
</Columns>
</asp:GridView>
</form>
</body>

The table doesn't have a primary key, that's why you could not autogenerate the update and delete statments.
It's probably something like this:
<asp:SqlDataSource
id="AccessDataSource1"
runat="server"
DataSourceMode="DataSet"
ConnectionString="<%$ ConnectionStrings:PayrollSystem_DBConnectionString %>"
SelectCommand="SELECT [UserID], [UserName], [UserPassword], [SecurityLevel] FROM tblUserLogin"
DeleteCommand="DELETE FROM [tblUserLogin] WHERE UserID=#UserID">
<DeleteParameters>
<asp:Parameter Name="UserID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
You have to add a DeleteCommand to your SqlDataSource. Of course you have to change the ConnectionString and the tableNames. In your DataGridView you have a CommandField to show the DeleteButton. That's why your SqlDataSource requires a DeleteCommand.
If you want to do it by the wizard, you can configure the SqlDataSource by clicking on the little arrow on top right. Under advanced options you can generate insert, update and delete commands, because you probably need them as well.
There is a nice tutorial about SqlDataSource

Related

Asp.Net C# DropDownList Selected Index Change Taking about 50 to 60 Sec

While working on asp.Net webforms. I realize and got many complains. dropdown selected Index is taking huge amount of time to bind another Dropdown on Selected Index Change did very simple thing to check but no luck.
<div class="col-sm-4">
<div>
<asp:Label Text="Category *" ID="LabelCompanyCategory" runat="server"></asp:Label>
</div>
<div>
<telerik:RadComboBox ID="DropDownListCompanyCategory" runat="server"
AutoPostBack="true" AppendDataBoundItems="true"
Width="100%" CssClass="form-control" CausesValidation="False"
DataSourceID="SqlDataSourceCategory" DataTextField="catDescription" DataValueField="CatId"
OnSelectedIndexChanged="DropDownListCompanyCategory_SelectedIndexChanged"
EmptyMessage="Select Category">
</telerik:RadComboBox>
<asp:RequiredFieldValidator runat="server" ErrorMessage="please select a category" Display="Dynamic"
ControlToValidate="DropDownListCompanyCategory" ForeColor="Red" ID="rfv2"></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="SqlDataSourceCategory" ConnectionString='<%$ ConnectionStrings:MainConnection %>' runat="server"
SelectCommand=" select CatId, Catdescription from dbo.category"></asp:SqlDataSource>
</div>
</div>
<div class="col-sm-4" runat="server" id="DivActivity" visible="false">
<div>
<asp:Label Text="Activity *" ID="LabelCompanyActivity" runat="server"></asp:Label>
</div>
<div>
<telerik:RadComboBox ID="DropDownListActivity" runat="server" CssClass="form-control" Width="100%"
AppendDataBoundItems="false" DataSourceID="SqlDataSourceActivity" EmptyMessage="Select Activity" CausesValidation="False"
DataTextField="activity" DataValueField="id">
</telerik:RadComboBox>
<asp:RequiredFieldValidator runat="server" ErrorMessage="please select a Activity"
ControlToValidate="DropDownListActivity" ForeColor="Red" Display="Dynamic" ID="RequiredFieldValidator1"></asp:RequiredFieldValidator>
</div>
<asp:SqlDataSource ID="SqlDataSourceActivity" ConnectionString='<%$ ConnectionStrings:MainConnection %>' runat="server"
SelectCommand="select activity, id from activity where catid=#CategoryId">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownListCompanyCategory" PropertyName="SelectedValue"
DefaultValue="0" Name="CategoryId" />
</SelectParameters>
</asp:SqlDataSource>
</div>
Back end Code:
protected void DropDownListCompanyCategory_SelectedIndexChanged(object sender, EventArgs e)
{
DivActivity.Visible = true;
DropDownListActivity.DataBind();
}
Telerik Components are amazingly fast, but you must configure them appropriately and use the RadAjaxManager.
Follow the example here:
http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/multiplecomboboxes/defaultcs.aspx
if the dataset is very large and the performance is still not good enough you must configure the loadOnDemand or revert to client side data binding.

SQL search error ASP.NET C#

keep getting this error when trying to use #itemname in a SQL search query. The code should search the values in the SQL table and display them here. Thanks.
Must declare the scalar variable "#itemname".
Code for search.aspx
<body>
<asp:SqlDataSource ID="searchresults" runat="server"
ConnectionString='<%$ ConnectionStrings:ConnectionString %>'
SelectCommand="SELECT [ID], [itemname] FROM [reports] WHERE ([itemname] LIKE '%' + #itemname + '%')">
</asp:SqlDataSource>
<asp:ListView ID="displayitems" runat="server" DataSourceID="searchresults" DataKeyNames="ID">
<EmptyDataTemplate>
<span>
No items for <asp:Label Text='' runat="server" ID="itemname" />
</span>
</EmptyDataTemplate>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateURL='<%# "Sale.aspx?saleid=" + Eval("ID") %>'>
<asp:Label Text='<%# Eval("itemname") %>' runat="server" ID="ItemNameLabel" /> <br />
</asp:HyperLink>
</ItemTemplate>
</asp:ListView>
</body>
You have to provide the parameter to the #itemname
<asp:SqlDataSource ID="searchresults" runat="server"
ConnectionString='<%$ ConnectionStrings:ConnectionString %>'
SelectCommand="SELECT [ID], [itemname] FROM [reports] WHERE ([itemname] LIKE '%' + #itemname + '%')">
<SelectParameters>
<asp:Parameter Name="itemname" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
and in code behind you can set the value of the parameter
searchresults.SelectParameters("itemname").DefaultValue = "some value";

Update command issue

I'm having a problem with an update function I'm trying to create for a group website I'm building. I have code in place that uses a SQL datasource and a list view with edit functionality. Basically I'm having a problem updating the table. I only want to update certain fields within the table in the DB but I only know how to update them all using the ID as a datakey name. Can someone help me/direct me as to what I need to add for the code to just update the fields I want? Basically I just want to be able to edit the name, description and units fields.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:UniString %>"
SelectCommand="SELECT [module_name], [module_desc], [module_units]
FROM [modules] ORDER BY [module_name], [module_desc], [module_units]"
UpdateCommand="UPDATE [modules] SET [module_name]= #Module_Name, [module_desc]=#Module_Description,
[module_units]=#Module_Units"
>
<UpdateParameters>
<asp:Parameter Name="Module_Name" Type="String" />
<asp:Parameter Name="Module_Description" Type="String" />
<asp:Parameter Name="Module_Units" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</p>
<asp:ListView ID="ListView1" runat="server"
DataSourceID="SqlDataSource1"
**DataKeyNames= ""** >
<AlternatingItemTemplate>
<span style="">module_name:
<asp:Label ID="module_nameLabel" runat="server" Text='<%# Eval("module_name") %>' />
<br />
module_desc:
<asp:Label ID="module_descLabel" runat="server" Text='<%# Eval("module_desc") %>' />
<br />
module_units:
<asp:Label ID="module_unitsLabel" runat="server" Text='<%# Eval("module_units") %>' />
<br />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
<br />
<br />
</span>
</AlternatingItemTemplate>
<EditItemTemplate>
<span style="">module_name:
<asp:TextBox ID="module_nameTextBox" runat="server" Text='<%# Bind("module_name") %>' />
<br />
module_desc:
<asp:TextBox ID="module_descTextBox" runat="server" Text='<%# Bind("module_desc") %>'
TextMode="MultiLine" Columns="30" Rows="10" />
<br />
module_units:
<asp:TextBox ID="module_unitsTextBox" runat="server" Text='<%# Bind("module_units") %>' />
<br />
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
<br /><br /></span>
</EditItemTemplate>
I have no back-end code on the CS file as I don't think its needed also I haven't added the whole list view as its long and probably isn't needed to be displayed. I have put ** beside the key names as I think that's where the error is coming from. When I had something such as module name in there, I think it works, but it updates everything to the same name, desciption etc. I want to individually change each of the list edits to be a different module name, description etc.
Briefly you should
Change select and select ID column from DB SelectCommand="SELECT [module_id]
Change update "UPDATE
[modules] SET [module_name]= #Module_Name,
[module_desc]=#Module_Description,
[module_units]=#Module_Units where [module_id]=#Module_ID"
Set the datakey column to "module_id" us you mention.
Add a hidden colummn into the listview

Adding Blank Rows to GridView bound to SqlDataSource

I am creating a GridView that will initially have a blank row (consisting of 2 DropDownLists and one TextBox). There is a button in the footer that will allow a user to add another row after they have filled in the first. I am binding this to a SqlDataSource so I am able to use the InsertCommand to call a stored procedure to Insert the user's data into a database table. However, I am not sure how to go about adding an empty row. Right now, the headers will not show up until a postback call is executed. I have seen tutorials that use a DataTable to add an empty row, but I could not get this to work with the bound DropDownLists. Is there a way to add a row to the SqlDataSource from code behind? The following is the relevant part of my ASP page:
<table>
<tr>
<td colspan="2" style="width:100%">
<div>
<asp:UpdatePanel ID="upUpdateChecklist" runat="server">
<ContentTemplate>
<asp:GridView ID="gvUpdate" runat="server" AutoGenerateColumns="False"
CssClass="mGrid" PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt"
ShowHeaderWhenEmpty="true"
Visible="true" CellSpacing="2"
CellPadding="2" ShowFooter="true"
DataSourceID="dsUpdate">
<Columns>
<asp:TemplateField HeaderText="Division/Context">
<ItemTemplate>
<asp:DropDownList ID="ddDivision" runat="server" DataTextField="Division" DataValueField="ID" DataSourceID="dsDivision"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Application">
<ItemTemplate>
<asp:DropDownList ID="ddApplication" runat="server" DataTextField="Application" DataValueField="ID" DataSourceID="dsApplication" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Task">
<ItemTemplate>
<asp:TextBox ID="tbTask" runat="server" ReadOnly="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="btnAdd" Text="Add New Row" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</td>
</tr>
</table>
<asp:SqlDataSource ID="dsApplication" SelectCommand="SELECT ID, ApplicationName FROM Automation.dbo.Applications"
runat="server"
ConnectionString="<%$ ConnectionStrings:AutomationDBConnectionString %>"></asp:SqlDataSource>
<asp:SqlDataSource ID="dsDivision" SelectCommand="SELECT ID, Division FROM Automation.dbo.Division ORDER BY Application, Division"
runat="server"
ConnectionString="<%$ ConnectionStrings:AutomationDBConnectionString %>"></asp:SqlDataSource>
<asp:SqlDataSource ID="dsUpdate" runat="server"
ConnectionString="<%$ ConnectionStrings:AutomationDBConnectionString %>"
SelectCommand="">
<InsertParameters>
<asp:Parameter Name="Division" DbType="Int32" />
<asp:Parameter Name="Application" DbType="Int32" />
<asp:Parameter Name="Task" DbType="String" />
</InsertParameters>
</asp:SqlDataSource>
I am not completely sure I understand how do you intend to achieve what you want but if you want to generate an empty row, change the select command of the SQL data source to do a union with an empty dummy row.
<asp:SqlDataSource ID="dsApplication" SelectCommand="SELECT ID, ApplicationName FROM Automation.dbo.Applications UNION select -1 as ID, '' as ApplicationName "

Getting database ID of objects in ListView and updating ListView from user control ListView

I am creating a website and am facing the following problem. I have 2 ListViews.
The first ListView is inside a user control called Sidebar.ascx:
<asp:ListView ID="sidebarListView" runat="server" DataKeyNames="Id" DataSourceID="SqlDataSourceSidebar">
<ItemTemplate>
<div class="sidebarItem" runat="server">
<div>
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
</div>
</div>
</ItemTemplate>
<LayoutTemplate>
<div class="sidebarMain">
<asp:PlaceHolder runat="server" ID="itemPlaceHolder" />
</div>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSourceSidebar" runat="server" ConnectionString="<%$ ConnectionStrings:TudengiDBConnectionString %>" SelectCommand="SELECT [Id], [Name] FROM [Faculties] ORDER BY [Name]"></asp:SqlDataSource>
It has to display only the name.
The second listview is inside my Default.aspx
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:ListView ID="RecentItemsListView" runat="server" DataSourceID="SqlDataSource1"
GroupItemCount="3">
<LayoutTemplate>
<div class="recentItemsMain">
<asp:PlaceHolder runat="server" ID="groupPlaceHolder" />
</div>
<asp:DataPager ClientIDMode="Static" ID="DataPager1" runat="server" PageSize="9">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<GroupTemplate>
<div class="recentItems">
<asp:PlaceHolder runat="server" ID="itemPlaceHolder" />
</div>
</GroupTemplate>
<ItemTemplate>
<div class="recentItem" runat="server">
<div>
<asp:Image ID="PictureThumb" runat="server" ImageUrl='<%#CreateThumbnail((string)Eval("Picture"),130,130) %>' />
</div>
<asp:Label ID="AuthorLabel" runat="server" Text='<%# Eval("Author") %>' />
<div>
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
</div>
</div>
</ItemTemplate>
<GroupSeparatorTemplate>
<div class="groupSeparator">
</div>
</GroupSeparatorTemplate>
</asp:ListView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TudengiDBConnectionString %>" SelectCommand="SELECT [Id], [Name], [Faculty_Id], [User_Id], [Author], [Picture], [Location] FROM [Books] ORDER BY [DateAdded] DESC">
What I need is for the ListView in Default.aspx to display the data without a WHERE clause, but when an item is clicked in the Sidebar user control I need to update the Default.aspx ListView to display only the data where the [Faculty_Id] = the ID of the ListView item in the user control.
How can I get the database ID of the ListView object when I can only display the NAME field? Do I have to display the ID as well and then hide the column from users?
What is the correct way to solve a situation like this?
Thanks for helping
<asp:ListView ID="sidebarListView" runat="server" DataKeyNames="Id" DataSourceID="SqlDataSourceSidebar" OnItemCommand="sidebarListView_ItemCommand">
<ItemTemplate>
<div class="sidebarItem" runat="server">
<div>
<asp:LinkButton ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' CommandName="Select" CommandArgument='<%# Eval("Id") %>' />
</div>
</div>
</ItemTemplate>
This is what I ended up with.
Add a hidden-field to your item-template to hold the database ID.
<ItemTemplate>
<asp:HiddenField ID="hdnFacultyID" runat="server" Value='<%# Eval("FacultyID") %>' />
<div class="recentItem" runat="server">
...
</div>
</ItemTemplate>
In the appropriate ListView handlers, you can access the database ID something like this.
((HiddenField)e.item.FindControl("hdnFacultyID")).Value
What you can do is to add an attribute to the NameLabel control.
Call it for example myID:
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' myID='<%# Eval("ID") %>'/>
then access that attribute from your code to get your ID:
string ID = NameLabel.Attributes["myID"];

Categories

Resources