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 "
Related
I have the below but the update from gridview doesn't seem to work and throws this error:
Incorrect syntax near 'nvarchar'.
Must declare the scalar variable "#id".
I have added the datakeynames to the gridview and the update parameters to the SqlDataSource but still can't see what's wrong...
Doing a delete works fine.
I have tried reduced the update parameters one by one but still not found the cause
<asp:SqlDataSource ID="sqldsEvents" runat="server"
ConnectionString='<%$ ConnectionStrings:dbIPRadioConnectionString %>'
SelectCommand="SELECT id, eventid, [start time], duration, active, [event desc] FROM tblEvents"
UpdateCommand="UPDATE tblEvents SET [start time] = #starttime WHERE (id = #id)"
InsertCommand="INSERT INTO tblEvents(eventid, [start time], duration, active, [event desc]) VALUES (#eventid, #starttime, #duration, #active, #eventdesc)"
DeleteCommand="DELETE FROM tblEvents WHERE (id = #id)">
<DeleteParameters>
<asp:Parameter Name="id"></asp:Parameter>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="eventid"></asp:Parameter>
<asp:Parameter Name="starttime"></asp:Parameter>
<asp:Parameter Name="duration"></asp:Parameter>
<asp:Parameter Name="active"></asp:Parameter>
<asp:Parameter Name="eventdesc"></asp:Parameter>
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="starttime"></asp:Parameter>
<asp:Parameter Name="id"></asp:Parameter>
</UpdateParameters>
</asp:SqlDataSource>
<div class="col-sm-12 text-center">
<asp:GridView ID="gvEvents" runat="server" DataKeyNames="id"
CssClass="table table-bordered" DataSourceID="sqldsEvents"
BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
CellPadding="4" AutoGenerateColumns="False"
EmptyDataText="No Events Configured">
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton runat="server" Text="Update" CommandName="Update" CausesValidation="True" ID="LinkButton1"></asp:LinkButton> <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="False" ID="LinkButton2"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Edit" CommandName="Edit" CausesValidation="False" ID="LinkButton1"></asp:LinkButton> <asp:LinkButton runat="server" Text="Select" CommandName="Select" CausesValidation="False" ID="LinkButton2"></asp:LinkButton> <asp:LinkButton runat="server" Text="Delete" CommandName="Delete" CausesValidation="False" ID="LinkButton3"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" SortExpression="id"></asp:BoundField>
<asp:BoundField DataField="eventid" HeaderText="eventid" SortExpression="eventid"></asp:BoundField>
<asp:BoundField DataField="start time" HeaderText="start time" SortExpression="start time"></asp:BoundField>
<asp:BoundField DataField="duration" HeaderText="duration" SortExpression="duration"></asp:BoundField>
<asp:BoundField DataField="event desc" HeaderText="event desc" SortExpression="event desc"></asp:BoundField>
<asp:TemplateField HeaderText="active" SortExpression="active">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="0" Value="0"></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("active") %>' ID="Label1"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The problem occurs because DataField attribute inside GridView's BoundField does not accept column names that using whitespaces.
Better to use underscores for DataField and SortExpression field/column names, also using underscore-based alias names for every columns containing whitespaces in SqlDataSource:
GridView control
<asp:GridView ID="gvEvents" ... >
<%-- other fields --%>
<asp:BoundField DataField="start_time" HeaderText="start time" SortExpression="start_time"></asp:BoundField>
<asp:BoundField DataField="event_desc" HeaderText="event desc" SortExpression="event_desc"></asp:BoundField>
<%-- other fields --%>
</asp:GridView>
SqlDataSource control
<asp:SqlDataSource ID="sqldsEvents" runat="server" ConnectionString='<%$
ConnectionStrings:dbIPRadioConnectionString %>'
SelectCommand="SELECT id, eventid, [start time] AS start_time, duration, active, [event desc] AS event_desc FROM tblEvents"
<%-- other items --%>
</asp:SqlDataSource>
Furthermore, if you have access to modify column names in SSMS, changing all column names with whitespaces to underscores like this update command should work without hassle:
UpdateCommand="UPDATE tblEvents SET start_time = #starttime WHERE (id = #id)"
Note:
Column/field names in every table should follow database identifier convention to ensure CRUD commands are executed successfully.
Similar issue: incorrect syntax near nvarchar in gridview
i want to select a column like cl1 from different tables for each row on gridview and show it on my repeater. how can i do this?
here is my code:
<asp:gridview cssclass="text-center table table-bordered table-condensed" id="GridView1" runat="server" autogeneratecolumns="False" datakeynames="PID" datasourceid="SqlDataSource2" emptydatatext="There are no data records to display.">
<Columns>
<asp:TemplateField HeaderText="مشخصات اختصاصی">
<ItemTemplate>
<asp:Label ID="CatPageLabel" runat="server" Text='<%#Eval("catpage").ToString().Replace(".aspx","") %>'></asp:Label>
<asp:Repeater ID="SecondPageRepeater" runat="server" DataSourceID="SecondPageSqlDataSource">
<ItemTemplate>
<%#Eval("cl1") %>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource runat="server" ID="SecondPageSqlDataSource" ConnectionString='<%$ ConnectionStrings:DrB_DBConnectionString %>' SelectCommand='select cl1 from #dest where cl1=3'>
<SelectParameters>
<asp:ControlParameter Name="dest" ControlID="CatPageLabel"/>
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
and this is the error:
Invalid object name '#dest'.
thank you
I have a nested gridview of images that are associated with the parent grid's row on a one to many relationship. This structure is contained in a user control. The images are uploaded with a fileupload control and are stored in a folder on the server. When the image grid's row is deleted, I delete the image from the server in the OnRowDeleting event. What's weird is that when you delete a row, a postback occurs and the OnRowDeleting event fires, the record is deleted from the database, but the row does not go away from the UI until you then delete it a second time. What's even weirder is that when I comment out the code in the OnRowDeleting event, the row deletes immediately. What's going on here?
<%# Control Language="C#" AutoEventWireup="true" CodeFile="OrderItemView.ascx.cs" Inherits="Controls_OrderItemView" EnableTheming="true" EnableViewState="true"%>
<asp:GridView ID="OrderItemList" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id,ConcurrencyId" DataSourceID="OrderItemDataSource"
SkinID="Blue" OnRowDataBound="OrderItemList_RowDataBound"
EnableModelValidation="True" Width="100%"
OnRowUpdating="OrderItemList_RowUpdating"
OnRowUpdated="OrderItemList_RowUpdated" AllowSorting="True" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonConfirmDelete" runat="server"
CausesValidation="False" CommandName="Delete" ImageUrl="../Images/Grid_ActionDelete.gif"
OnClientClick='return confirm("Are you sure you want to delete this Order Item? This cannot be undone.");'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Name" SortExpression="OrderItemName">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("OrderItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Images">
<ItemTemplate>
<a href="" data-id='<%# Eval("id","imageHeader_{0}") %>' class="expandImages">
<asp:Label ID="Label3" runat="server"
Text='<%# string.Format("{0} Image{1}", Helpers.GetImageCount(new Guid(Eval("Id").ToString())), Helpers.GetImageCount(new Guid(Eval("Id").ToString())) != 1 ? "s" : "") %>'>
</asp:Label>
</a>
<div id='<%# Eval("id","images_{0}") %>' class="imageDisplay">
<asp:GridView ID="gvImages" runat="server" SkinID="Blue"
DataKeyNames="Id" EnableModelValidation="True"
DataSourceID="ImageDataSource" AutoGenerateColumns="False"
ShowHeader="False" onrowdeleting="gvImages_RowDeleting">
<Columns>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonConfirmDeleteImage" runat="server"
CausesValidation="False" CommandName="Delete" ImageUrl="../Images/Grid_ActionDelete.gif"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("FileName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<a href="" data-id='<%# Eval("id","image_{0}") %>' onclick='showImage("<%# Eval("ImageUrl") %>"); return false;'>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("FileName") %>' ToolTip="Click to Preview Image"></asp:Label>
</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<div style="color: Blue; font-style: italic;">No Images</div>
</EmptyDataTemplate>
</asp:GridView>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="btnUploadImage" runat="server" Text="Upload" CommandArgument='<%# Eval("Id") %>'
CommandName="orderItemId" oncommand="btnUploadImage_Command"/>
<asp:ObjectDataSource ID="ImageDataSource" runat="server"
DataObjectTypeName="OrderSite.Entities.OrderItemImage"
DeleteMethod="Delete" InsertMethod="Save"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetList"
TypeName="OrderSite.Bll.OrderItemImageManager" UpdateMethod="Save"
SelectCountMethod="SelectCountForGetList">
<SelectParameters>
<asp:Parameter DbType="Guid" Name="orderItemId"/>
</SelectParameters>
</asp:ObjectDataSource>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<div style="padding: 3px 0 3px 3px 3px;">No Order Items Exist</div>
</EmptyDataTemplate>
</asp:GridView>
<asp:ObjectDataSource ID="OrderItemDataSource" runat="server"
DataObjectTypeName="OrderSite.Entities.OrderItem"
DeleteMethod="Delete" InsertMethod="Save"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetList"
TypeName="OrderSite.Bll.OrderItemManager" UpdateMethod="Save"
OnInserting="OrderItemDataSource_OnInserting"
SortParameterName="sortExpression" SelectCountMethod="SelectCountForGetList">
<SelectParameters>
<asp:Parameter DbType="Guid" Name="orderFormId" />
<asp:Parameter Name="sortExpression" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
I commented out any containing updatepanels in the parent page as they can always be the culprit, but there was no effect.
Here is the OnRowDeleting event:
protected void gvImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// Also delete the file from the images folder
OrderItemImage myImage = OrderItemImageManager.GetItem((Guid)e.Keys["Id"]);
if (myImage != null)
{
string path = string.Format("../Images/OrderItemImages/{0}", myImage.OrderItemId.ToString());
if (File.Exists(Server.MapPath(string.Format("{0}/{1}", path, myImage.FileName))))
{
File.Delete(Server.MapPath(string.Format("{0}/{1}", path, myImage.FileName)));
// if there are no images left in folder, then delete it (only deletes empty directory)
if (Directory.GetFiles(Server.MapPath(path), "*.*", SearchOption.TopDirectoryOnly).Length == 0)
Directory.Delete(Server.MapPath(path));
}
OrderItemList.DataBind();
}
}
I've done this before and have had no issues, so any help would be greatly appreciated!
I ended up wrapping the nested GridView ("gvImages"), the FileUpload, and Button in a user control, and now it works great. I didn't change any of the code, just wrapped it all in the user control, so go figure.
I am currently experiencing a really weird problem with deleting a row from a GridView. I have the following code, and it throws the following exception:
ORA-01008: not all variables bound
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="DeleteBTN" runat="server" OnClientClick="return confirm('Are you sure you want to delete this move request?')" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UNIQUEKEY" HeaderText="Unique Key"
SortExpression="UNIQUEKEY" />
<asp:SqlDataSource ID="GridViewDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:Oracle1ConnectionString %>"
ProviderName="<%$ ConnectionStrings:Oracle1ConnectionString.ProviderName %>"
SelectCommand="SELECT ORIGINATOR, TO_CHAR(REQUESTDATE, 'MM/DD/YYYY') as REQUESTDATE, PARTNUMBER, REQUESTQTY, MOVEFROM, MOVETO, COMPLETEDBY, TO_CHAR(COMPLETION_DATE, 'MM/DD/YYYY') as COMPLETION_DATE, COMMENTS, RESPONSETIME, PROCESS_FLAG, UNIQUEKEY FROM MATERIALMOVEREQUEST WHERE RTRIM(PROCESS_FLAG) = :ProcessFlag ORDER BY REQUESTDATE DESC"
DeleteCommand="DELETE FROM MATERIALMOVEREQUEST WHERE UNIQUEKEY = :UNIQUEKEY">
<SelectParameters>
<asp:ControlParameter ControlID="RequestTypeLabel" DefaultValue="" Name="ProcessFlag" PropertyName="Text" Type="String" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="UNIQUEKEY" Type="Decimal" />
</DeleteParameters>
UNIQUEKEY is a 'Number' field in my Oracle table and I have tried all kinds of data types where it is currently a 'decimal' type.
Use Deleting event of SqlDataSource and try writing following code:
e.InputParameters["UNIQUEKEY"] = value;
value is what you want to send to database
Fixed it myself, had to add the primary keys to the GridView parameters (DATAKEYNAMES). Here is my code snippet:
<asp:GridView ID="MMRGrid" runat="server" AutoGenerateColumns="False" DataKeyNames="UNIQUEKEY"
DataSourceID="GridViewDataSource" Width="980px" OnRowDataBound="GridViewRowEventHandler"
EmptyDataText="No Data Found" AllowSorting="True">
<Columns>
<asp:TemplateField HeaderText="Delete" Visible = "true">
<ItemTemplate>
<asp:LinkButton ID="DeleteBTN" runat="server" OnClientClick="return confirm('Are you sure you want to delete this move request?')" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
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