.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

Pass Linq results to another function

Posted By:      Posted Date: April 10, 2011    Points: 0   Category :ASP.Net

I have 2 linq queries, 1 get data by name the other by id, both return the same data and I want to populate the same form with it, but I can't seem to pass the results to a method and still have intellisense.

Basically something like this:

protected void uxSearchUserName_Click(object sender, EventArgs e) {
     if (SearchingByName){
          var selUserData = Entites.UserTable.FirstOrDefault(un => un.Name == uxUserName.Text);
          var selUserData = Entites.UserTable.FirstOrDefault(un => un.id == uxUserID.Text);     }

public void BuildForm(results){
     string Name = results.Name;
     ......populate fields with data from results

I found examples where I have to create a property for each field but that will get tedious with large datasets. Was hoping there's an easier way.



View Complete Post

More Related Resource Links

Need Syntax To Make Results of LINQ Union Return Non-Generic Type



I have the below SQL which works just fine:

SELECT     Message, CreateDate, AccountId, AlertTypeId
FROM       dbo.Alerts
SELECT     TOP (100) PERCENT Status, CreateDate, AccountId,
                          (SELECT     10 AS Expr1) AS AlertTypeId
FROM         dbo.StatusUpdates
WHERE AccountId = PassedInParameter

I have been going about trying to convert the above into a LINQ method and am having problems with return types.
As the above SQL illustrates, I am querying two distinct LINQ tables - Alerts and StatusUpdates -
and then attempting to perform a Union on them. In order to do the union in LINQ, I have to have agreeing types. So, I
am using "var" to make the results of "alerts" and "updates" generic before the union.  

public IList GetStatusUpdatesAsAlertsByAccountId<T>(Int32 accountId)
            using (WorkbookDataContext dc = _conn.GetCont

Linq query results to List collection



I have a GridView in my page. I want to use below code in code beind. query nothwing DB using linq . add linq query result to new list and then bind list as gridview Datasource

I use below code . But I don't know how to add results to List? Could any one tell me how !

Public Class OrderCity
        Private _name As String
        Private _city As String
        Public Property name As String
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value

            End Set
        End Property
        Public Property city As String
                Return _city
            End Get
            Set(ByVal value As String)
                _city = value

            End Set
        End Property
    End Class
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim dbe As New SFFAV1DataContext
        Dim latestadsDs = From p In dbe.Products _
                            Select New With {p.Title, p.ProducedCity} _
                             Take (2)

        Dim FilteredList As New List(Of OrderCity)()
        For Each result In latestadsDs
            Dim Menedfcou = Nothing
            FilteredList.Insert(0, Menedfcou)

EF4/Linq Eager Loading with Include fails to populate all results

Hi, I'm trying out EF4 as part of a .Net 4.0 WCF service. The aim of the service is to return document data as an array of entity objects to any of our ASP.Net apps. The apps are still in .Net 2.0. Due to the nature of the solution I've disabled LazyLoading at context level. I started with this:var revQuery = from revs in context.DocRevision                         where (revs.ID == myIDVar)                         select revs;  Everything works ok, I receive the correct number of populated objects. However when I add an Include into my query to allow us to pickup fields from a related table that has a defined navigation only the first record is returned fully populated to a calling application:var revQuery = from revs in context.DocRevision.Include("StaffNames")                         where (revs.ID == myIDVar)                         select revs;  The array is the correct size but all elements after the first are blank, default placeholders. Its like using the Include has reverted to LazyLoading and I can't seem to kick it into line. Anyone else had this problem?

How can i pass function as parameter to show in gridview

Hello, I have one common Data Access function which returns output as dataset which is as below   Public Shared Function ExecuteDataSet(ByVal sql As String, ByVal type As CommandType, ByVal ParamArray parameters As SqlParameter()) As DataSetDim RetVal As Object = Nothing   Try Cmd = Cmd.Connection = OpenConnection() Cmd.CommandType = type Cmd.CommandText = sql Cmd.Parameters.AddRange(parameters) Sda = Ds = Sda.Fill(Ds)       New SqlCommand()New SqlDataAdapter(Cmd)New DataSetCatch ex As ExceptionThrow New Exception(ex.Message.ToString())Finally CloseConnection() Sda.Dispose() End Try   Return Ds End Function   this function normally i use to get data from database and returns to dataset   now,I want to created one more function which output type is gridview and its parameter is  dataset which i got output in previous funtion   i want like this public funtion BindDatatoGridView(ExecuteDataSet("SELECT...",commandType.text,Parameter....)) as GridView End Function   how can i solve this, please help me out

Use of PATINDEX function in select clause With Linq

hello       i have an problem to use of PATINDEX function in select clause with Linq.      if anyone have any clue about it then please update me its urgent.Thanks In Advance.

pass number of rows of Gridview to a javascript function

using vb.net/asp.net 2005.I need to pass the number of rows of the Gridview to a javascript function does anyone know how to do this?  thanks

Return linq query in function

I try to return a var query from a function, but i'll get the error: Error:Error 41 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<System.Xml.XmlElement>'. An explicit conversion exists (are you missing a cast?)  Code: protected static IEnumerable<XmlElement> GetModels(byte MerkID) { string rawXML = AutoDisk.GetModels(12345, true, MerkID, "2010", ""); XmlDocument xml = new XmlDocument(); xml.LoadXml(rawXML); var query = from feed in xml.DocumentElement.ChildNodes.Cast<XmlNode>() select new { nModelID = feed.SelectSingleNode("nModelID").InnerText, Modelnaam = feed.SelectSingleNode("Modelnaam").InnerText }; return query; } Whats wrong and how can i make this working ?  

Can't pass string to javascript function(unterminated string)

Hello,I have a problem. I can't pass string like this  ": Mar 15 2004 12:00AM  Refnr: 20040315!m>N0"to javascript function because I have symbols like these >, <, % ?tc.Situation:I have a Grid and I have column with DataItemTemplate,Within my dataitemtemplate I have <a href="javascript:void(0);"  onclick="ShowAccountStatementNote(document.getElementById('<%= lblHiddenNoteText.ClientID %>').value);" >                                                          Bekijken...                                                      </a><a href="javascript:void(0);"  onclick="ShowNote('<%# EncodeStringToHTML(Eval("Note")) %>');" > Notes </a>ShowNote function just show popup with text = NoteEncodeStringToHTML do Server.HtmlEncode(); But It doesn't help because even if we change text on server .... e.g. "dfdf%" convert to "dfdf&#37;"  anyway on client it becomes again "dfdf%" and problem still exists.On clien

Pass string to Javascript function from code-behind...



I'm trying to send a error message to a javascript function from code-behind, but it's not working. When the javascript is executed the output error is: [object Object]

Here's my Javascript:

function Error(error) 
            document.getElementById("<%= errorText.ClientID %>").innerText = error;

And my C#:

        textError = "This is not working!!!";

        ScriptManager.RegisterStartupScript(Page, this.GetType(), "Error", "javascript:Error('" + textError + "');", true);                

Even if i pass the string instead of the 'textError' variable i still get the same error :(

Can anyone help me?

How to pass argument to javascript function



in aspx page i have taken a simple html anchor tag like this:

<a id="l1" href="javascript:OnLookup();">Click</a>

when "Click" is clicked, that OnLookup function is called. But if i want to pass argument in that function then how can i pass ?

This anchor tag is generated dynamically through another javascript function.There can be more than one anchor tags, and each having different arguments in OnLookup function call .

How can pass arguments dynamically ?

I need to pass a variable from a url to an .aspx search/results page


When I was using FrontPage, a .asp page would receive a varialbe from the url when ?field=value was added to the end of the url.  I am now using Expression Web and have found that this doesn't work with .aspx pages.  Can anyone tell me what code needs to be added to the page to accomplish this with .aspx?  I create the .aspx page with VB as the coding selection.

I am not sure what forum this should be in.



Eleanor V

Linq and stored procedure - cannot get results


Hi to all,

i try call a stored procedure from my linq code in order to validate a user credentials. I have tried via linq to sql and sql commands and everything works as expected. But when comes to calling a stored procedure via linq, i cannot get the results i expect.

This is my code:

stored procedure:

ALTER PROCEDURE [dbo].[ValidateUser] (@UserName varchar(50), @UserCode varchar(4))

	SELECT ISNULL(FirstName, ''), ISNULL(LastName, '')
	FROM Users
	WHERE (UserName =@UserName AND UserCode=@UserCode)


                dbContext = new MyDBDataContext();
                var result = dbContext.ValidateUser("Jim", "1234");

                if(result != null)
                    //true, so user is validated so set response status to OK
                    response.Status = ResponseStatus.OK;

                    //set returned params to response
                    var paramsReturned = result.FirstOrDefault();

                    response.FirstName = paramsReturned.Column1;
                    response.LastName = paramsReturned.Column2;
                    //false, so set respone to the corresponding error

Public Function Testing (ByVal FirstString as String, ByVal FirstInteger as Integer), how to pass a


I have the following function, sometimes I want to pass a DBNULL.Value to the function so I update the database with a null value, but it won't let me as the DBNULL.Value is not a string or an integer, how can I get this to work?

Public Function Testing (ByVal FirstString as String, ByVal FirstInteger as Integer), how to pass a DBNULL.Value?

' update database

Return value

End Function

Help with linking LINQ results to a grid



I'm getting the following error message when running the code below: yx returns a value of '1' for example

Error: Both DataSource and DataSourceID are defined on 'GridView4'. Remove one definition


Dim vc1 As Integer

For Each row As GridViewRow In GridView2.Rows

'Find checkbox in the row

Dim chb As CheckBox = DirectCast(row.FindControl("CheckBox1"), CheckBox)

'if checkbox is found and is checked then add the id to string

If chb IsNot Nothing AndAlso chb.Checked Then

If vc1 > 0 Then

yx = yx & "'" & row.Cells(1).Text & "'"


yx = "'" & row.Cells(1).Text & "'"

End If

vc1 = vc1 + 1

End If


' MsgBox(yx)

Dim DB As New AOP29ClassesDataContext

Dim Query = From p In DB.Link_Tables _

Where p.Link_ID Like yx _

Select New With {p.Receiver.Receiver, p.Donor.Donor}


GridView4.DataSource = Query


Any ideas how to fix this problem? Using the design property of the grid, I tried removing the datasource link from the grid but the grid doesn't appear unless the data source in linked to a table.


MDX Root()-function: different results in Cube Browser and Excel


I try to write a calculated member that returns the percentage of total (but independent from the chosen dimensions). So i started with the included template "Percentage of total".

When i use the measure in my cube browser, it works so far, but not when i use the measure in excel client.

The problem is the root-function. When i place my dimension in the rows-section and deselect some members in the filter-window, the root-function isn't influenced by the filter in excel. When i browse the cube in SSMS it gives the correct result, because the filter is applied to it.

You can reconstruct the problem very easily by adding this measure: "Root([Dimension Name]),[Measures].[Measure Name]"

This is a big problem in my case, because i absolutely need a grand total, that uses the filter-selections.

I already spent days to find a way, how to write e calculated measure, that just gives me the grand total according to the filter and which i can use with different dimensions. Or is there any way to access the calculated grand total cell in MDX? I can't believe that my problem is so difficult to solve.

Please help me out!


Sum Function Not returning proper results


I was wondering if someone could explain to me why this isn't returning the correct answer. 

Create View [dbo].[viewWyanAvail]


SELECT 'Wyan4' As TableGroup, Event_Type, Unit_Code, EventStartTS, EventEndTS, Avail_Cap 

FROM dbo.Wyan4 


SELECT 'Wyan5' As TableGroup, Event_Type, Unit_Code, EventStartTS, EventEndTS, Avail_Cap 

FROM dbo.Wyan5


SELECT 'Wyan6' As TableGroup, Event_Type, Unit_Code, EventStartTS, EventEndTS, Avail_Cap 

FROM dbo.Wyan6


SELECT 'Wyan7' As TableGroup, Event_Type, Unit_Code, EventStartTS, EventEndTS, Avail_Cap 

FROM dbo.Wyan7



Create FUNCTION [dbo].[fncGetDesignated_Amount_WyanAvail] (

	@TableGroup varchar(10),

	@Unit_Code varchar(5))




declare @Amount float

if not exists (select 1 from dbo.viewWyanAvail)

    select top 1 @Amount = Amount

 from dbo.Designated_Amount

Where Unit_Code = @Unit_Code


select top 1 @Amount = CAST(dbo.Designated_Amount.Amount AS Float) 

 FROM dbo.Designated_Amount INNER JOIN

 dbo.viewWyanAvail ON dbo.Designated_Amount.Unit_Code = dbo.viewWyanAvail.Unit_Code 

 WHERE not exists (SELECT 1

FROM dbo.Designated_Amount INNER JOIN

 dbo.viewWyanAvail ON dbo.Designated_Amount.Unit_Code = dbo.viewWyanAvail.Unit_Code

WHERE dbo.viewWyanAvail.Avail_Cap = 0 AND dbo.viewWyanA

LINQ error if function


            tbl_PotniNalogi potninalogi = new tbl_PotniNalogi()
                        if (Session["ID"] != null)
            Button1.Text = Convert.ToString((int)Session["ID"]);

                Stevilka = MaxStevilka + 1,
                Leto = Convert.ToString(DateTime.Now.Year),
                DatumIzdaje = txtDatum.SelectedDate.Value,
                Voznik = ddlVoznik.Text,
                NaslovVoznika = "Cankarjeva 9",
                SluzbenoVozilo = Convert.ToBoolean("True"),
                Vozilo = ddlVozilo.Text,
                Odredil = ddlOdredil.Text,
                ZacetnoStanje = Convert.ToInt32(txtZacetnoStanje.Text),
                KoncnoStanje = Convert.ToInt32(txtKoncnoStanje.Text),

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1513: } expected

Source Error:

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