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

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

dropdown list fill with Linq and convert string to datetime and ordering and stored procedure call.

Posted By:      Posted Date: May 22, 2011    Points: 0   Category :Windows Application

I wanted to share this more than anything,  it took me most of the morning searching and finding various post on various sites but I got it figured out and working.  It might be better coded, but it is a start for some one trying to understand how linq and ASP.Net things work.

What I have is a database table with a datetime in string format and a stored procedure which returns all the data.
What I want to do is load a dropdown list with MonthName and Year for a selection choice on generating monthly report.

The stored procedure is in a Linq to SQL class dbml and the connection string is dynamic, i.e., made througha call to another class.

here is the code.  Enjoy understanding how it works.

// Miscellaneous Details are filled in for helping you get the big picture.
// Some of the using statements are for other things in the code behind, 
// but I left it in so don't get confused,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.ObjectModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using MYProject.LinqtoSQLStuff;

namespace MYProject.ChooseReportPage
	 public partial class TheReportPage : System.Web.UI.Page  
	     protected void Page_Load(object sender, EventArgs e)


View Complete Post

More Related Resource Links

Call SQL Stored Procedure Asyncronously



I have a C# web page that calls a stored procedure. The page passes few parameters to the stored procedure and call it. The stored procedure does so many time consuming tasks on a huge number of database records but does not return any value.

Since the page is not expecting any return from the stored procedure, I want to execute the stored procedure asyncronously so that the user can continue working on the web page and other web pages while the stored procedure is running in the background. Also, I do not want the web server processes to be busy with the running stored procedure.

Any help, please.

Best regards,


TSQL: Passing array/list/set to stored procedure (MS SQL Server)

Passing array/list/set to stored procedure is fairly common task when you are working with Databases. You can meet this when you want to filter some collection. Other case - it can be an import into database from extern sources. I will consider few solutions: creation of sql-query at server code, put set of parameters to sql stored procedure's parameter with next variants: parameters separated by comma, bulk insert, and at last table-valued parameters (it is most interesting approach, which we can use from MS SQL Server 2008). Ok, let's suppose that we have list of items and we need to filter this items by categories ("TV", "TV game device", "DVD-player") and by firms ("Firm 1", "Firm2", "Firm 3). It will look at database like this So we need a query which will return us list of items from database. Also we need opportunity to filter these items by categories or by firms. We will filter them by identifiers. Ok, we know the mission. How we will solve it? Most easy way, used by junior developers - it is creating SQL-instruction with C# code, it can be like this List<int> categories = new List<int>() { 1, 2, 3 };   StringBuilder sbSql = new StringBuilder(); sbSql.Append( @" select i.Name as ItemName, f.Name as FirmName, c.Name as CategoryName from Item i inner join Firm f on i.FirmId =

stored procedure call to C#

Hi I created the Only stored procedure  for dynamically  I want to call that procedure in C# stored procedure CREATE   PROC SearchAndReplace ( @SearchStr nvarchar(100), @ReplaceStr nvarchar(100) ) AS BEGIN   -- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.   -- Purpose: To search all columns of all tables for a given search string and replace it with another string   -- Written by: Narayana Vyas Kondreddi   -- Site: http://vyaskn.tripod.com   -- Tested on: SQL Server 7.0 and SQL Server 2000   -- Date modified: 2nd November 2002 13:50 GMT   SET NOCOUNT ON   DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110), @SQL nvarchar(4000), @RCTR int   SET @TableName = ''   SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')   SET @RCTR = 0   WHILE @TableName IS NOT NULL   BEGIN   SET @ColumnName = ''   SET @TableName =     (   SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))   FROM INFORMATION_SCHEMA.TABLES   WHERE TABLE_TYPE = 'BASE TABLE'   AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName   AND OBJECTPROPERTY(   OBJECT_ID(   QUOTENAME(TABLE_SCHEM

Using IN clause(string parameter) in Stored Procedure

Hi guys. I need to use IN clause in a selection query. From all the resources that I found from google, it's all about adding a function to split a integer parameter into a list. But I got a string parameter, for example 'A1,B1,C1' I tried to use the below where single quotes in @CustCode is double up. ___________________________________ Declare @SQL VarChar(1000)   SELECT @SQL = ' SELECT [something]' SELECT @SQL = @SQL + ' FROM [Table]' SELECT @SQL = @SQL + ' WHERE CustomerCode IN ('  + @CustCode + ')'   EXECUTE (@SQL) _____________ Executing the stored procedure in MSSQL works fine, but it didn't when executing from Visual Studio 2005. Please advice.

"Out-of-Range" Error When Passing DateTime (DD/MM/YYYY) into Stored Procedure

Hi everybody, I hope some of you will be able to help me regarding this datetime problem. The query in the stored procedure doesn't accept DD/MM/YYYY format, although all dates are being saved in the format of DD/MM/YYYY hh:mm:ss. Example of query that throws the error: @sDate = '31/8/2010' @eDate = '1/9/2010' SELECT * FROM tb_Schedule where scheduledate >= @sDate and scheduledate <= @eDate  Error:  The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value FYI, the SQL Server 2005 is defaulted to British English(2057)for all logins and the DB server itself and my server Regional and Language is set to English (United Kingdom). Any help will be appreciated. Thank you very much.  

can a Workflow access a stored procedure and pass the parameters from the list data to the stored pr

The reason that I would like to consider this functionailty is because my table architecture is complicated and I do not want to modify my master table to accept all of this data where some of the data should be normalized into sub tables.  Has anyone see evidence of the stored-procedure parm approach?  Is this best accomplished through VS 2010 or can I do it through SPD? Thanks

New to WCF, how can i call a stored procedure via WCF?

Ok, i may be completely off track.  But i'm trying to get away from the old webservices, so i'm reading up on WCF.  I can't seem to get my head around what i'm doing wrong.  I'm attempting a simple call to a stored procedure on a sql server express. Here is my web.config <system.serviceModel> <services> <service behaviorConfiguration="ndfService" name="ndfService"> <endpoint address="http://localhost:8080/NDFService" binding="wsHttpBinding" contract="NDFService.IService" /> <host> <baseAddresses> <add baseAddress="http://localhost:8080/NDFService"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ndfService"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="true"/> </beha

SQL 2010 SP1 does not fill in Stored Procedure Parameters

I am executing a Stored Procedure in Server Management Studio.  The Procedure gives the expected results but it does not fill in the parameters?  I have stop and restarted the server to no avail. Please help? Thanks. STORED PROCEDURE USE   [char68003f] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[SelectDonorXiD] ( @DonorID varchar(50) , @ContactTitle varchar(7)=null OUTPUT, @ContactFirstName varchar(40)=null OUTPUT, @ContactLastName varchar(40)=null OUTPUT, @ContactAddress1 varchar(40)=null OUTPUT, @ContactAddress2 varchar(40)=null OUTPUT, @ContactCity varchar(30)=null OUTPUT, @ContactStateCode varchar(2)=null OUTPUT, @ContactZipCode varchar(10)=null OUTPUT, @ContactPhone varchar(30)=null OUTPUT, @ContactEmail varchar(80)=null OUTPUT, @BillingTitle varchar(7)=null OUTPUT, @BillingFirstName varchar(40)=null OUTPUT, @BillingLastName varchar(40)=null OUTPUT, @BillingAddress1 varchar(40)=null OUTPUT, @BillingAddress2 varchar(40)=null OUTPUT, @BillingCity varchar(30)=null OUTPUT, @BillingStateCode varchar(2)=null OUTPUT, @BillingZipCode varchar(10)=null OUTPUT, @BillingPhone varchar(30)=null OUTPUT, @BillingEmail varchar(80)=null OUTPUT ) AS Select ContactTitle, ContactFirstName, ContactLastName, ContactAddress1, ContactAddress2, ContactCity, ContactStateCode, ContactZipCode, ContactPhone, ContactEmail, BillingTitle, Bil

Insert a "Select User" row in Linq for a dropdown list

I'm new to Linq. I have searched and searched the web for a soluion, and can't find anything. I have a Linq query and I want to insert a row ("Select User") to the top before I pass it to the drop down list. I've been trying to use the Union but to now avail (it keeps telling me that my object doesn't support the Union method). My code, prior to attempting to inser a row, is very simple.public SelectList DropDown_Users()        {            var context = new VivarianDataContext();            var query = from t in context.AspnetUsers                        select new { t.UserId, t.LastName };            list = new SelectList(query.AsEnumerable(), "UserId", "LastName");            return list;        }Now I try to insert a row and I found this on the internet and it seems to say that his solution will work. But it is filled with syntax errors. http://magicode.wordpress.com/2009/08/20/inserting-an-item-in-iqueryable-object-using-union-met

Cannot call Table Valued Function from Dynamic stored procedure statement

Hello,  I have a table-valued function that splits string into a table column. I can easily call this function from a stored procedure within a regular SELECT statement: SELECT * FROM Table1 WHERE Code1 = '1' AND Code2 IN(SELECT * FROM [dbo].[fnSplitValues](@Code2String))   However when I try to use the same logic for a dynamic SELECT statement: ‘SELECT * FROM Table1 WHERE Code1 = '1' AND Code2 IN(SELECT * FROM ' + [dbo].[fnSplitValues](@Code2String) + ')’ I get an error ‘Cannot find either column "dbo" or the user-defined function or aggregate "dbo.fnSplitValues", or the name is ambiguous.’ Any idea what is wrong with my dynamic SQL?   Please help, Lana

No Return Type for a Stored Procedure in a Linq to SQL Data Layer

Hello. First, I don't know if this is the right forum section to post this in, but I couldn't fine a more suitable one. Feel free to move this if it's totally worng. I have a weird problem when using LINQ to SQL and Store Procedures with a return value... The problem is that when I drag my SP's onto the "Methods Pane" the property field "Return Type" is set to (None) and greyed out. And here's the most weird thing... I created a test SP yesterday wich returned SCOPE_IDENTITY() and it worked flawlessly. Dragged it onto the "Methods Pane", could play with the return type property (hence it was not greyed out) and everything was working out nice. I used a ISingleResult<T> and could fetch the .ReturnValue... Today I was going to contiune to create the rest of the SP's i needed with a return type but today when I drag my Store Procedures to my Methods Pane, I couldn't access the Return Type property... I even dragged the SAME procedure I used yesterday (wich then worked great) and now I can't get the dbml-layer to notice that there is a return value... I've tried to create new solutions, new Data Layers, used different databases/servers, but still the same problem... Don't really know if it's LINQ or something else that's causing this... This is how part of my SP wich I used yesterday to test looks

Convert SSIS DateTime to a String


Being a newbie to SSIS I'm not sure of the most efficient method of converting a DateTime object to a String.


I'm from a C# background where this would be easy using DateTime.ToString("YYYYMMdd"). I want to use the date in a file name so don't require most of the parts.


I'm sure I could do this using a script task to produce a file name for each row of data in my table and add that filename to the dataset but it seem like overkill to do something that should be simple. Also as I'm supposed to be getting to grips with SSIS I shouldn't keep running back to what I know.


My current approach is to derive a column and build up an expression to convert the date into a string. The only problem being that it doesn't work.

The expression I'm working with is:

(DT_WSTR, 50)([OrgName] ) + "_" + (DT_WSTR, 50)( [PayrollName] ) + (DT_WSTR, 4)(YEAR( [ProcessedDate] )) + (DT_WSTR, 2)(MONTH( [ProcessedDate] )) + (DT_WSTR, 2)(DAY( [ProcessedDate] )) ".txt"


Can anyone see where I'm going wrong?


All comments greatly received.

How do I convert a Sql Datetime value into a string including the miliseconds?


 Hi all,

Currently I am able to bring the datetime from my SQL table but I also need the milisecods. Here is the line of code:

DateTime latestTimeStamp = DateTime.UtcNow;
string select = "select max(timeStamp) from Table1";

SqlConnection myConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["UctConnectionString"].ConnectionString);
SqlCommand mySqlCommand = new SqlCommand(select, myConnection);

latestTimeStamp = (DateTime)mySqlCommand.ExecuteScalar();

So latestTimeStamp = {9/22/2010 6:24:09 PM} but I needed it to be latestTimeStamp = {9/22/2010 6:24:09:080 PM}
since the SQL field value is 2010-09-22 18:24:09.080 and I want to do an accurate datetime comparison.

Thank you

can I create a job to call a stored procedure?




Can I create a job to call a stored procedure everyday? If yes, how to do it?



call to stored procedure occasionally returns empty recordset



I have a devil of an intermittent problem that I have so far found nothing to help me solve.

I have a web application/module in Dotnetnuke that requires data for a simple form from another SQL server DB on a different server.  The app uses a connection string in the web.config like this:

<add name="CompanyUpdate" connectionString="Data Source=mail.mydatabase.be;Initial Catalog=MA_Online;Persist Security Info=True;User ID=Gus;Password=xxxxxx" providerName="System.Data.SqlClient" />

The application calls a stored proc and most of the time data is returned as expected. There should always be a row returned from the SP.  However, if the form is idle for a while or the module has only just loaded the call to the stored proc returns as empty recordset. A 'table not found' error occurs.

There is no connection issue otherwise there would be a connection error instead of an empty recordset right?. But I cannot work out why sometimes no data is returned. I can go onto the server and run management studio and run the sp over and again and always get data.

I don't have control over the target DB but the person who does thinks it's something to do with connection pooling. I tried turning this off in the connection string and found that I got an empty recordset every time the sp was called wit

Need a string output from stored procedure


hai everyone,,

I got a situation now... i had a stored proc: How can i get the final select statement in the code behind.

Here is the stored proc.

ALTER PROCEDURE [dbo].[tgms_reclass_PO_bip](@po VARCHAR(20), @old_gl VARCHAR(20), @new_gl VARCHAR(20),@output varchar(500) out )

IF (SELECT COUNT(*) FROM mm2po WHERE scode = @po) = 0
    --SET @output = '1'
    SET @output = 'Invalid PO Number'

Check if Old GL Code is valid
IF (@output = '' AND (SELECT COUNT(*) FROM acct WHERE scode = REPLACE(@old_gl,'-','')) = 0)
    --SET @output = '2'
    SET @output = 'Invalid Old GL Account'

Check if New GL Code is valid
IF (@output = '' AND (SELECT COUNT(*) FROM acct WHERE scode = REPLACE(@new_gl,'-','')) = 0)
    --SET @output = '3'
    SET @output = 'Invalid New GL Account'


Pass list to stored procedure



I'm looking to pass a list into a stored procedure, stored as List<myClass>.  I've passed a table in before but I'm not sure how to pass a list - anyone help?

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