.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

selecting nearest value

Posted By:      Posted Date: October 23, 2010    Points: 0   Category :ASP.Net


How would i make a select statement select the row with the nearest values? e.g.:

I have 3 labels, labels1 2 and 3, with values of 1.2, 2 and 5.8

In my table i have 4 columns, first is the data im after, and the next 3 relate to the three labels.

I want to select one row, where the values of labels match it the closest.

e.g. i have 2 rows:

   label     1       2     3

hello        1     2.5     6

hello2      2     2.6    6.2

for this, the select would select row 1 'hello' because the figures match most closely to the labels.

Can anyone help with this?


View Complete Post

More Related Resource Links

Round off time to the nearest minute

How would you round this up to the nearest minute? There isn't a built in function to do this so you have to use a little bit of maths to get there. There are 60 seconds in a minute. We already have 38 seconds on the clock. So we need to add on 60 - 38 = 22 more seconds.

Error message when selecting a row in webdatagrid



I have a webdatagrid control that is loaded by using an sqldatasource.  I have add and edit methods that behave correctly, however, I have a problem when I delete a row.   I can delete the row correctly from the datagrid and the database, but as soon as I select another row in the grid straight after, I get an error:

Microsoft JScript runtime error: 'undefined' is null or not an object


There are no events wired up to the row select, so it doesn't appear to be that.


Can anyone help?


Help needed in selecting coulmns from 2 tables using entity framework


Hi all,

I have two tabels as mentioned below. I am using entity framework and vs2010.I am not able to write linq query to get data from both the tables. there is one to many relationship(for one category ther can be multiple articles). Please help me out as this is very urgent. Thanks in advance.

1) Article

ArticleID bigint Unchecked
CategoryID int Unchecked
ArticleName varchar(500) Unchecked
ArticleDesc nchar(1024) Unchecked

DropDownList and TemplateInfo not selecting proper value


I am having trouble with DropDownList (and/or DropDownListFor) when using TemplateInfo's HtmlFieldPrefix in a strongly-typed view.  DropDownList properly selects the value from the model when the prefix hos not been site.  Once I set the value of HtmlFieldPrefix, the value from the model is not selected in the drop-down list.

I am using .NET 3.5SP1 and ASP.NET MVC 2 RC2.


public class TestModel
    public string Text { get; set; }
    public string Option { get; set; }

    public IEnumerable<String> Options
            yield return "One";
            yield return "Two";
            yield return "Three";


public class TestController : Controller
    public ActionResult Test()
        return View(new TestModel

Why won't my Model accept what I'm selecting from the DropDownList?


I edit the Dinner (from the NerdDinner tutorial) and save it, but the Country isn't persisted. Here's my code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NerdDinner.Models
public class DinnerFormViewModel
private static string[] _countries = new[]{

public Dinner Dinner { get; private set; }
public SelectList Countries { get; private set; }

public DinnerFormViewModel(Dinner dinner)
Dinner = dinner;
Countries = new SelectList(_countries, dinner.Country);

Then in my controller I use it like so:
    public ActionResult Edit(int id)
        Dinner dinner = dinnerRepository.GetDinner(id);        

Filtering/selecting rows based on date


I have a gridview, based on thsi datasource:


<asp:SqlDataSource ID="SqlDataSourceAllLoads" runat="server" 
        ConnectionString="<%$ ConnectionStrings:tplatz_dk_dbConnectionString %>"               
        SelectCommand="SELECT DISTINCT DATEADD(day, 0, DATEDIFF(day, 0, tblDelivered.delivered_Date)) AS delivered_Date, tblDelivered.delivered_LoadNo, tblDelivered.delivered_TrailerNo, ISNULL(tblDeliveredInfo.deliveryInfo_FirmaNavn, N'?') AS Expr1 FROM tblDelivered FULL OUTER JOIN tblDeliveredInfo ON tblDelivered.delivered_LoadNo = tblDeliveredInfo.deliveryInfo_LoadNr ORDER BY delivered_Date DESC">

Using a dropdownlist, I can filter (by changing datasource) the results based on customer names in a dropdownlist. This datasource, working perfectly, looks like this:


<asp:SqlDataSource ID="sqldataSourceKundeLoads" runat="server" 
        ConnectionString="<%$ ConnectionStrings:tplatz_dk_dbConnectionString %>" 
        SelectCommand="SELECT  DATEADD(day, 0, DATEDIFF(day, 0, tblDelivered.delivered_Date)) AS delivered_Date, tblDelivered.delivered_LoadNo, tblDelivered.delivered_TrailerNo, ISNULL(tblDeliveredInfo.deliveryInfo_FirmaNavn, N'?&#

selecting between query and stored procedure

<!-- /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:1033506322; mso-list-type:hybrid; mso-list-template-ids:369124590 67698703 67698713 67698715 67698703 67698713 67698715 67698703 67698713 67698715;} @list l0:level1 {mso-level-tab-stop:.5in; mso-level-number-position:left; text-indent:-.25in;} ol {margin-bottom:0in;} ul {margin-bottom:0in;} --> What would prefer to pull data out from sources stored procedure or query? and why?

Selecting the correct auto-generated ID associated with a given customer

I have the following two tables (among many) in an OLTP database: TABLE NAME: BusinessEntity TABLE FIELDS: BusinessEntityID, int, IDENTITY(1,1), NOT NULL, PRIMARY KEY BusinessEntityType, nvarchar(10), NULL TABLE NAME: Person TABLE FIELDS: BusinessEntityID, int, NOT NULL, PRIMARY KEY, FOREIGN KEY to BusinessEntity.BusinessEntityID FirstName, nvarchar(30), NULL LastName, nvarchar(30), NULL There is a 1-to-1 Identifying Relationship between the BusinessEntity and Person tables. When a new customer needs to be added to the database, I execute the following T-SQL statement: INSERT INTO BusinessEntity (BusinessEntityType) VALUES (‘Customer’); What I don’t know how to do is retrieve the value of BusinessEntity.BusinessEntityID that was automatically assigned to the new customer so I can then append it to Person.BusinessEntityID. While I know I can execute: SELECT MAX (BusinessEntityID) FROM BusinessEntity; there is no guarantee that the BusinessEntityID will be the one associated with the new customer I just added because it is possible that other new customers can be added to the BusinessEntity table by other users during the interim period between the time I execute the previously mentioned INSERT command and then SELECT command. Any help/guidance in resolving this issue would be greatly appreciated.  Thanks.

Selecting Particular Commands with sp_repldone

Is it possible to use sp_repldone to mark all commands distributed up to a certain point? We have a scenario where the log reader is unable to construct a command from one problematic command. Log Reader Agent failed to construct a replicated command from log sequence number (LSN) {0000fc2c:000afd81:0009}. Back up the publication database and contact Customer Support Services. (Source: MSSQLServer, Error number: 18805) In order to correct this problem we issue the following: EXEC sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1 EXEC sp_replflush GO Unfortunately, this marks all commands as being distributed, even the commands that occurred after the problematic one.  From BOL it seems as though it’s possible to mark the problematic command and all earlier commands as distributed. (With sp_repldone, you can manually tell the server that a transaction has been replicated (sent to the Distributor). It also allows you to change the transaction marked as the next one awaiting replication. You can move forward or backward in the list of replicated transactions. (All transactions less than or equal to that transaction are marked as distributed.)) Does anyone know how to do this? I found an interesting article which discusses this but it’s from 2003 so I’m reluctant to rely on it in a production system. http://www

Selecting the Appropriate Type of Replication

I have 2 servers 1) Production Server 2) Reporting Server I create seprate tables for reports at production sever. I fill those table from stored procedure thru sql job daily. First i truncate the tables then insert whole data in reporting tables each time. So now i have to implement replication to replicate the reporting tables data to reporting server database. I wan't to know which type of replication is used (Snapshot, Transactional, Merge).    

can alias in select be used for selecting other column in that table?

Hi All,I want to use an alias name in a select clause to select other column in that table? select   top 1 (   case when CreatedByName <> '' then 'yy'         else 'xx' end) as filName, (filName + 'xx')from Order       But it throws error like " Invalid column name 'fileName'."Could you please help me out?

Selecting VIEW dynamically from a stored procedure

What's the best way to dynamically reference a view in a sproc? I want to pass a View Name into a stored procedure, but I'm guessing this is only possible with a table in SQL Server 2008. Is the only way to do this through dynamic SQL (passing in the View name as a string, and executing the query as a built string)?. My concern is that if I use Dynamic SQL, what performance gain I might get by using a view may be undone by using Exec('string').   Any thoughts?   Thanks Steve

Selecting different no. of records from the same table

Hello all, This might seem a basic thing but bothering me from last few days. Suppose I have a table containing 5 million records and I am running queries one by one (one query executes completly and then next query is fired)as below on that table. SELECT top 20000 FROM MyTable SELECT top 200000 FROM MyTable SELECT top 2000000 FROM MyTable  Now my questions are; Will SQL Server use same execution plan? As I am running these queries one by one in same order as given above, will second query take less time than it should if run standalone (only second query is fired, no query fired before that) and similarly will third query take less time than it should if run standalone (only third query is fired, no query fired before that), since there is a possibility of same execution plan being used?  Regards.    

Selecting One Radio Button In A GridView

Hello, how do I add a RadioButton column to a gridview so that only one button is selectable? Here is what I have now. <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:RadioButton ID="RadioButton2" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:HyperLinkField DataTextField="Text" DataNavigateUrlFields="NavigateURL" /> </Columns> </asp:GridView>  

datagrid item.ItemIndex keep selecting the wrong row number

I apologize in advance for my poor english:1. I have a dropdownList within my datagrid and its already populated fine (22 rows in my datagrid)2. The select item for the 21 row is the same as the select item of the 22 row3. When trying to do selectedIndexChange for the 22 row, it didn't seem to work. The error: Dim ddl As DropDownList = CType(sender, DropDownList)Dim dgi As DataGridItem = CType(ddl.Parent.Parent, DataGridItem)Dim rowID As Integer = dgi.ItemIndex The rowID keep staying at 20 even though the selectedIndexChanged is happening in row 22( ie. rowID should be 21)Does anyone seen this problem before??

Display specific table from the start vs selecting from a list.

Hello all, I'm using VS2010, EF 4.0. I want to display a list view from a specific table from the start -instead of the standard default page that list all the tables. Any ideas are welcome. 

People Picker gets error when selecting user from a trusted domain(one way forest trust)

  Hello all,   Our current setup is SharePoint 2010 Foundation server in one external forest(Trusting forest), and trying to have users in a separate internal forest(Trusted forest) access the site. The external forest's DC and SharePoint server are in a DMZ separated by a firewall with the internal forest's DC and users. A one way transitive forest trust was successfully created and has been validated. On SharePoint, we're ran the sts commands to set the setapppassword as well as the peoplepicker-searchadforests adding the domain that the SharePoint server is in, as well as the trusted forest. An iisreset was issued after running these commands. In SharePoint, we can then search for users from the trusted domain, and select the users in the Select People page, but when hitting the final Ok, an error is received: An unexpected error has occurred in which a correlation ID is provided. Reviewing the SharePoint logs we find the following: <!-- /* Font Definitions */ @font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:-520092929 1073786111 9 0 415 0;} @font-face {font-family:Tahoma; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:-520081665 -1073717157 41 0 66047 0;} /* Style Defin
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend