my ASP.NET GridView does not bind correctly - c#

I have an ASP.NET GridView supposed to exec a SQL Query.
The query is never executed so I strongly suspect there is a binding issue somewhere.
Here is the aspx code:
<asp:SqlDataSource ID="i_sdsGv" runat="server" ConnectionString="<%$ ConnectionStrings:XXX %>"
SelectCommand="INCOHERENT QUERY IN ORDER TO TRIGGER AN EXCEPTION"
SelectCommandType="Text"
<SelectParameters>
<asp:QueryStringParameter Name="MyTableId" QueryStringField="MyTableId" />
</SelectParameters>
</asp:SqlDataSource>
...
<asp:GridView ID="i_gv" runat="server" AutoGenerateColumns="False" DataKeyNames="MyTableId"
DataSourceID="i_sdsGv" OnRowDataBound="i_gvOptionChoix_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="i_tbName" runat="server" Text='<%# Bind("MyTableName") %>' />
</ItemTemplate>
</Columns>
<EmptyDataTemplate>
NO ROWS TO DISPLAY
</EmptyDataTemplate>
</asp:GridView>
I am 100% sure that if the query string is inexact, an exception is triggered.
In my case, no exception is triggered so the query is not executed.
I get the NO ROWS TO DISPLAY text.
The only obvious binding that I can think about is between the DataSource and the GridView. It does look OK to me.
So I would suspect an issue with :
DataKeyNames="MyTableId" ?
My i_gvOptionChoix_RowDataBound method is empty at the moment but I think it does not matter at this time?
What am I missing so the app actually attempts to execute the query?
Thx in advance for your kind assistance

Related

How to acess ID from EditItemTemplate inside Gridview

I have a WebForms GridView, where I want to update a BoundField conditionally (or I use a value from a DropDown or I use the text from a Textbox), based on the value from another DropDownList.
<asp:GridView ID="gv_results" runat="server" DataKeyNames="ID_RESULTS" DataSourceID="get_results">
<Columns>
<asp:TemplateField HeaderText="DETAIL" SortExpression="DETAIL">
<EditItemTemplate>
<asp:TextBox ID="tb_detail_edit" runat="server"></asp:TextBox>
<asp:DropDownList ID="dd_detail_edit" runat="server" AutoPostBack="True" DataSourceID="get_detail" DataTextField="DETAIL" DataValueField="DETAIL" ></asp:DropDownList>
</asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:SqlDataSource runat="server" ID="get_results"
UpdateCommand="UPDATE RESULTS SET [DETAIL] = COALESCE(#DETAIL,#DETAILwelcome)">
<UpdateParameters>
<asp:ControlParameter ControlID="ctl00$MainContent$gv_results$ctl02$dd_detail_edit" PropertyName="SelectedValue" Name="DETAIL" Type="String"></asp:ControlParameter>
<asp:ControlParameter ControlID="ctl00$MainContent$gv_results$ctl02$tb_detail_edit" PropertyName="Text" Name="DETAILwelcome" Type="String"></asp:ControlParameter>
</UpdateParameters>
</asp:SqlDataSource>
Well, I found out in the google's that I have to use the Direct ID in the Control Parameter. And it works...the thing is , the $ctl02 (for example) before the id of the dd_detail_edit, changes, with different rows in the Gridview (so this id works for one row, but maybe for the next it doesn't work.
Is there some workaround for this?
Using only something like $gv_results$dd_detail_edit , doesn't work, I dunno why :S
TIA and Best Regards,
For one thing it looks like you have an open <ItemTemplate> tag without any closing one.
If you check out the .net documentation you can see where they use the regular control IDs, like ControlID = dd_detail_edit.
I do not think you're providing enough details for me to provide a complete answer, but those are a couple of things I noticed.

GridView display text rather than foreign key

I have just started to learn how to use the Gridview Control to display SQL data. I have been able to get almost everything to work except for displaying the more user friendly information for one of my data fields that I populate from a lookup table. The entire concept of the page I want to be able to Update, Insert and Delete new records too and for some reason I could not get these options to work when I was using the SqlDataSource so I use LinqDataSource and all is now working (except I haven’t figured out Insert yet…a separate question)
I am also using the controls tabs in Visual Studio to choose and edit the attributes of the controls so kind of using the wizards and not hand coding the example.
What I cannot figure out is how to make my column with employeetypeid that contains the foreign key from the employeetypelookup table to show the employeetype text value for the user so this makes more sense. I found a “Walkthrough: Displaying a Drop-Down List While Editing in the GridView Web Server Control“ and this works perfectly. When I go into edit mode the dropdownlist shows the employeetype text and when I choose a different type, the appropriate employeetype id gets stored in the database.
So how can I modify something (the Datasource???) to display the employeetype text in the DataGrid.
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="SNRmain.SNRmainDataContext" EntityTypeName="" OrderBy="lastname, preferredfirstname" Select="new (personnelid, lastfirstname)" TableName="masterpersonnellastpreferreds"></asp:LinqDataSource>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="LinqDataSource1" DataTextField="lastfirstname" DataValueField="personnelid">
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="SNRmain.SNRmainDataContext" EnableDelete="True" EnableInsert="True" EnableUpdate="True" EntityTypeName="" TableName="tblappointmentdates" Where="personnelid == #personnelid" OrderBy="startdate desc">
<WhereParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="personnelid" PropertyName="SelectedValue" Type="Int32" />
</WhereParameters>
</asp:LinqDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="snrappointmentid" DataSourceID="LinqDataSource2">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="startdate" HeaderText="startdate" SortExpression="startdate" />
<asp:BoundField DataField="endingdate" HeaderText="endingdate" SortExpression="endingdate" />
<asp:TemplateField HeaderText="employeetypeid" SortExpression="employeetypeid">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="LinqDataSource3" DataTextField="employeetypetext" DataValueField="employeetypeid" SelectedValue='<%# Bind("employeetypeid", "{0}") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("employeetypeid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="apptcomment" HeaderText="apptcomment" SortExpression="apptcomment" />
<asp:BoundField DataField="dateentered" HeaderText="dateentered" SortExpression="dateentered" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource3" runat="server" ContextTypeName="SNRmain.SNRmainDataContext" EntityTypeName="" OrderBy="employeetypetext" Select="new (employeetypeid, employeetypetext)" TableName="tblemployeetypelookups">
</asp:LinqDataSource>
I have tried to modify the LinqDataSource2 to include a statement like the one below but that does not work and I get an error that does not make sense to me. "System.Web.Query.Dynameic.ParseException: Syntax error.
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="SNRmain.SNRmainDataContext" EntityTypeName="" Select="snrappointmentid,
personnelid, startdate,
endingdate, employeetypeid,
tblemployeetypelookup.employeetypetext
from tblappointmentdates
join tblemployeetypelookups on tblappointmentdates.employeetypeid = tblemployeetypelookups.employeetypeid" TableName="tblappointmentdates" Where="personnelid == #personnelid">
<WhereParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="personnelid" PropertyName="SelectedValue" Type="Int32" />
</WhereParameters>
</asp:LinqDataSource>
thanks in advance.
Ok if I understood correctly what you should do is to pass the employeetypeid in a function and retrieve the text and bind that to control like this.
from
<asp:Label ID="Label1" runat="server" Text='<%# Bind("employeetypeid") %>'></asp:Label>
to
<asp:Label ID="Label1" runat="server" Text='<% #GetEmployeeName(Eval("employeetypeid"))%>' runat="server" />
so now GetEmployeeName is a server function you would write to fetch name from id.
protected string GetEmployeeName(int employeetypeid)
{
//What ever is the way to query and return from here
}
Also as side note I noticed you do naming like Label1 which is very poor practice.

Gridview's (populated by SqlDataSource) Update is not updating, don't know how to trace

I'm still a newbie in ASP.NET, and right now, my Gridview is not "updating" when I hit "Update". Here is how I have my GridView w/ the SqlDataSource :
<asp:GridView ID="ProjectTable" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="PopulateProjectTable" DataKeyNames="ProjectID">
<Columns>
<asp:BoundField DataField="ProjectID" HeaderText="Project ID" ReadOnly="True" SortExpression="ProjectID" />
<asp:BoundField DataField="ProjectDescription" HeaderText="Project Description" ReadOnly="True" SortExpression="ProjectDescription" />
<asp:BoundField DataField="ProjectNotes" HeaderText="Project Notes" SortExpression="ProjectNotes" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="PopulateProjectTable" runat="server" ConnectionString="<%$ ConnectionStrings:sandboxConnectionString %>" SelectCommand="SELECT * FROM [Projects]" UpdateCommand="UPDATE [Projects] SET ProjectNotes = #project_notes">
<UpdateParameters>
<asp:Parameter Name="project_notes" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
I have no code in the code behind. When I hit "Edit", the third column is suppose to be "editable". When I hit "Update", the page does a postback but what was entered in the third column does not persist and is instead lost. What is going on?
In addition, how would I trace this issue? This is so in the future, I can see what the SQL string is. Thank you.
EDIT: Turns out to be a typo that caused my issue. Problem solved!
Is the spelling correct on the ProjectNotes DataField? The problem you are describing sounds like the field is not bound properly.
I would run SQL profiler while hitting the update. To see what exactly was being sent back to the Database.
You should see your parameter as well. Set the filter to the DB your looking at if you have multiple and give it a try and realtime run the same test by hitting the update button again.
Please modify your update command from this
UpdateCommand="UPDATE [Projects] SET ProjectNotes = #project_notes"
to this
UpdateCommand="UPDATE [Projects] SET ProjectNotes = #project_notes" WHERE ProjectID=#ProjectID
Please add to your DataSource
OnUpdated="OnDSUpdatedHandler">
and add the following method
<script runat="server">
private void OnDSUpdatedHandler(Object source, SqlDataSourceStatusEventArgs e) {
var dbg = e;
}
</script>
Set breakpoint on line
var dbg = e;
and examine what is being in that variable. The answer should be there

ASP Dropdown list not changing the value

First off, I'm still getting my web dev legs under me. I've combed through piles of SO posts, blogs, newsgroups and articles and I cannot seem to fix my problem. It's very similar to at least 10 different posts I've looked at.
I have an ASP gridview, which acts as a display and a select column. When you click select it throws the data into a detailsview. I have one field that needs to be a drop down box, but whenever I change the value and click update the value that is sent to the command is the original value.
Page Markup:
<asp:TemplateField HeaderText="Planner Name">
<ItemTemplate>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cboCurrentPlanner" runat="server" DataSourceID="plannerDataSource"
DataTextField="planner_name" DataValueField="planner_id" SelectedValue='<%# Eval("planner_id") %>' AutoPostBack="true" ></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Fields>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
</asp:DetailsView>
sqlDataSource:
SelectCommand="SELECT vendor_key, vendor, planner_name, street, city, state_country, planner_id, country FROM V_MAP_MarkerInfo WHERE (vendor_key = #vendor_key)"
UpdateCommand="MAP_usp_webUpdatePlanToVendor"
UpdateCommandType="StoredProcedure" onupdating="mapDetailSource_Updating" >
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="vendor_key"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="vendor_key" Type="String" />
<asp:Parameter Name="planner_id" Type="Int32" />
<asp:Parameter Name = "vendor" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="plannerDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:vendor_mapConnectionString %>"
SelectCommand="SELECT [planner_id], [planner_name] FROM [MAP_planners]"
OldValuesParameterFormatString="original_{0}">
</asp:SqlDataSource>
I won't post the stored procedure code, I know that is working. The original value is the only value that makes it to the parameter.
I've tried all sorts of combinations of <%# Bind/Eval() %> postbacks but I can't find the right combination.
When I click select, I want the current planner to be selected in the dropdown list. When I select a new planner and click update I would like the planner to update. I'm not sure why this is so difficult or what I have royally screwed up to make it difficult but I am at my wits end. If at all possible, I would like an explanation of what is going on and not just the magical line of code that makes it work.
Flabbergasted is an understatement.
EDITS: ViewStateEnbabled="true" added to dropdownlist, the selectedIndexChanged event is firing.
EDIT AGAIN: Changed the planner_id to <asp:ControlParameter> added monitors to DetailsView1_OnDataBind and MapDataSource1_updating and the value is all over the place. but I can't see where it's being reset.
Do you have EnableViewState="false" set on the #Control or #Page settings? If viewstate is not enabled the control will always have the default value as the selected value. This can be set at the aspx level or the ascx level.
http://msdn.microsoft.com/en-us/library/ms972976.aspx
So I am a complete idiot, the DetailsView DataKeyNames property was not set correctly. I had accidentally added "planner_id" as a key from the wizard.
The code was fine all along. Thank you to everyone for trying, but I am a lost cause!

How to add multiple paramaters to a SQL select query using a checkboxlist?

I'm hoping to retrieve data-rows from a database using a query with a checkboxlist as a control parameter. The problem is multiple selected values on the checkboxlist only return one value as seen here...
Illustration
<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal" DataSourceID="SqlDataSource1" DataTextField="Fruit" DataValueField="Fruit" ></asp:CheckBoxList>
<asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:f-StopConnectionString %>' SelectCommand="SELECT [Fruit] FROM [Table_1]"></asp:SqlDataSource>
<br />
<asp:Button ID="Button1" runat="server" Text="Select" OnClick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource4">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID"></asp:BoundField>
<asp:BoundField DataField="Fruit" HeaderText="Fruit" SortExpression="Fruit"></asp:BoundField>
</Columns>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSource4" ConnectionString='<%$ ConnectionStrings:f-StopConnectionString %>'
SelectCommand="SELECT * FROM [Table_1] WHERE ([Fruit] LIKE '%' + #Fruit + '%')">
<SelectParameters>
<asp:ControlParameter ControlID="CheckBoxList1" PropertyName="SelectedValue" Name="Fruit" Type="String"></asp:ControlParameter>
</SelectParameters>
</asp:SqlDataSource>
Is there a way to pass multiple selections so that the query would read:
(WHERE [Fruit] LIKE '%'Apples'%') OR (WHERE [Fruit] LIKE '%'Oranges'%')
Any help at all would be greatly appreciated.
As far as I understand, as you have provided no code, you want to use linq (or entity framework) to query database.
You need then to build lambda expression depending on user selection and pass it to your query.
See Lambda expressions trees here for start:
http://www.codeproject.com/Articles/17575/Lambda-Expressions-and-Expression-Trees-An-Introdu
This can help also:
Can I use custom delegate method in Where method of Entity Framework?
If you want just to pass sql select command string, then you should build custom where clause depending on user selection.

Categories