parameterise table name in nested repeaters datasource - c#

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

Related

GridView update with SqlDataSource

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

checkbox itemtemplate not updating into an ASP GridView

working on an ASP Gridview querying a SQL server base.
<asp:Content ID="i_cttContenu" runat="server" ContentPlaceHolderID="i_cphContenu">
<asp:SqlDataSource ID="i_sdsGvOption" runat="server" ConnectionString="<%$ ConnectionStrings:... %>"
SelectCommand=" SELECT * FROM MyTable " SelectCommandType="Text"
UpdateCommand="UPDATE MyTable SET [name] = #name, prenom = #prenom, isAlive = #isAlive WHERE idWsgProgramOption = #idWsgProgramOption" UpdateCommandType="Text"
</asp:SqlDataSource>
<asp:UpdatePanel ID="i_up" runat="server">
<ContentTemplate>
<asp:GridView ID="i_gvOption" runat="server" AutoGenerateColumns="False" DataKeyNames="idWsgProgramOption"
DataSourceID="i_sdsGvOption" EnableModelValidation="True">
<Columns>
<asp:CommandField ButtonType="Image" CancelImageUrl="~/....gif"
CancelText="Annuler" EditImageUrl="~/....gif"
EditText="Update" HeaderText="M" UpdateImageUrl="~/....gif"
UpdateText="Save">
</asp:CommandField>
<asp:TemplateField HeaderText="Nom" SortExpression="name">
<ItemTemplate>
<asp:HyperLink ID="i_hlOption" runat="server" NavigateUrl='<%# Eval("idWsgProgramOption", "~/myURL") %>'
Text='<%# Eval("name") %>' />
</ItemTemplate>
<EditItemTemplate>
<table >
<tr>
<td >
<asp:TextBox ID="i_tbNom" runat="server" Text='<%# Bind("name") %>' />
</td>
</tr>
</table>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="prenom" SortExpression="prenom">
<ItemTemplate>
<asp:HyperLink ID="i_hlprenom" runat="server" NavigateUrl='<%# Eval("prenom", "~/myURL") %>'
Text='<%# Eval("prenom") %>' />
</ItemTemplate>
<EditItemTemplate>
<table >
<tr>
<td >
<asp:TextBox ID="i_tbprenom" runat="server" Text='<%# Bind("prenom") %>' />
</td>
</tr>
</table>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Obligatoire" >
<ItemTemplate>
<asp:CheckBox ID="CB_id1" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CB_id2" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The update() method is not invoked when I click the update button (first column). If I add an onUpdating event into the datasource, the corresponding method is never invoked.
The code causing the issue is definitely the checkbox.
If I remove from the datasource update query:
, isAlive = #isAlive
and only set:
UPDATE MyTable SET [name] = #name, prenom = #prenom, isAlive = #isAlive WHERE idWsgProgramOption = #idWsgProgramOption;
Then it updates fine (except the isAlive field of course).
I am 100% sure that the isAlive field exists into the base (bit type).
So it looks that my problem comes from this bloc:
<asp:TemplateField HeaderText="Obligatoire" >
<ItemTemplate>
<asp:CheckBox ID="CB_id1" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CB_id2" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
Is there anything obvious that I missed??
Also, this is the simplified code, but if I set the "checked" property to the checkbox and correctly binds, the rows checkbox is correctly field. So the issue does not affect the select but only the update.
Try a button column instead so you can specify the specific command names.
<asp:ButtonField ButtonType="Link" Text="Update" CommandName="Update" />
<asp:ButtonField ButtonType="Link" Text="Delete" CommandName="Delete" />
Take action based on e.CommandName.

assign a value to checkbox in a grid header

I have following grid
<asp:GridView ID="grdDWlocations" CssClass="table table-hover table-striped" runat="server" GridLines="None" ShowHeaderWhenEmpty="True"
EmptyDataText="No data found..." AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="" Visible="true">
<HeaderTemplate>
<asp:CheckBox ID="allDWlocchk" runat="server" Checked="true" Width="10px" onclick="CheckAllgrdReqDW(this)"></asp:CheckBox>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk_DWlocReq" runat="server" Checked="true" Width="5px" OnCheckedChanged="chk_Req_CheckedChangedDW_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="lbl_DWCode" runat="server" Text='<%# Bind("Ml_loc_cd") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lbl_DWDescription" runat="server" Text='<%# Bind("Ml_loc_desc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want to assign a value for 'allDWlocchk' which is header check,
how can I do this in code behind
I tried this none of the thing worked
Attempt 1 :
((CheckBox)(grdDWlocations).FindControl("allDWlocchk")).Checked = false;
Attempt 2 :
((CheckBox).FindControl("allDWlocchk")).Checked = false;
You are on the right track, FindControl is the way to go here. But the problem is that it only works with direct children. So instead of searching on the Page or on the GridView you need to be searching in the header row. Which is available as the GridView property. So:
GridViewRow headerRow = grdDWlocations.HeaderRow;
((CheckBox)headerRow.FindControl("allDWlocchk")).Checked = false;

Nested gridview row not (fully) deleted after OnRowDeleting event

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.

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 "

Categories

Resources