.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

Help with linking LINQ results to a grid

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


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.


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?

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

Getting a Single node, in linq results to:


A part of my rawXML i get from a webservice:

<GetOpties>\n  <Table>\n    <nOptieLijstIDHist>167613</nOptieLijstIDHist>\n    <Code>W01</Code>\n    <Omschrijving>ADVANCE PAKKET</Omschrijving>\n    <Prijs>1990</Prijs>\n    <Bijzonderheden>Lichtmetalen velgen Porto 7J x 17\" met 22545 R17 banden + 15 mm verlaagd onderstel + straffe demping en versterkte vering + 35% getint glas achter</Bijzonderheden>........ 

I try to get the the values in a linq query:

var query = from feed in xml.DocumentElement.ChildNodes.Cast<XmlNode>()
                            select new AutoDiskClass.Options
                                nOptieLijstIDHistField = feed.SelectSingleNode("nOptieLijstIDHist").InnerText,

Copy phone numbers from results grid to excel, numbers have leading 0


Hi I need to copy a column of phone numbers into excel they should be treated as text however excel wants to treat it as a number.

Is there anything I can do to force excel to treat the copy and paste from management studio as text and retain the leading 0?

Linq to Sql multiple results



I am kartheek. I had some doubt regarding Linq to Sql multiple results. I am new to Linq.

The following is my code, please help me.

My sql procedure is 

ALTER procedure [dbo].[GetParentResourcesDataWithFilters]
@ResourceClubId bigint,
@Keyword varchar(100),
@Status varchar(10),
@CurrentPage int,
@RecordsPerPage int
as begin

How to search grid results based on user provided values?


I would like a user to be able to enter some criteria in a search box and then have them click on a search button to filter the data using a "contains" logic and not an exact match.

 Anyone know if this is possible?

I have downloaded the DynamicFilterRepeater and that works well, but you end up with one search box per colulmn...I would like to have one search box that columns could subscribe to and that would be filtered automatically.

Not sure how to go about doing something like that...I'm still quite new to DD and I am still trying to get a grasp on the basic stuff.


Pass Linq results to another function


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.



Playing with Linq grouping: GroupByMany?

One of its features is grouping. Many people understand grouping like it is defined in Sql. Linq is implementing grouping quite the same way. Let's discover this syntax and how to make consecutive groups easier.

LINQ : Implementing IN and NOT IN

I got tried of typing

var result = from s in source
where items.Contains(s)
select s;and so I implemented the IN and NOT IN methods as extension methods:

101 LINQ Samples Tutorials

101 LINQ Example with sample code snippets....This sample prints each element of an input integer array whose value is less than 5. The sample uses a query expression to create a new sequence of integers and then iterates over each element in the sequence, printing its value

Linq: how to share parameters between lambda expressions ?

When using Linq to objects, you will quickly feel the need to pass some parameters from a method to another but it's not so easy because each Linq method is not calling the following one. In a Linq sequence, each method is using the result computed by the previous one. So, local contexts are not visible from one method to another.
The compiler is using two technical different ways to let parameters go out of a method.

Linq to Sql CompiledQuery container

Ok now let's go. Here is just a little trick but with some interesting patterns that could be useful in some other contexts not connected to Linq to Sql.

When using Linq expressions, like with Linq to Sql, translating the expression into something else (sql for example) is taking time and resources. Sometimes it's negligible, sometimes not...

Building a grouping Grid with GridView and ASP.NET AJAX toolkit CollapsiblePanel

I've posted an update to this post to apply on demand loading of Details data using ASP.NET AJAX PageMethods. I'm demonstrating the usage if CollapsiblePanelExtender client events on the new post. Check it out.

I admit, Matt Berseth is really inspiring me! Few days ago I pass through 2 of his great posts:

.Surrounding your Data Table and Dialog Controls with ComponentArt Styled Panels
.Building a Grouping Grid with the ASP.NET 3.5 LinqDataSource and ListView Controls
The first one is pure design tips one which I used for making good presentation of my demo here. The 2nd post is actually the idea.

LINQ to SQL Paging using GridView in C# and ASP.NET 3.5

This tutorial will show you how we can extend the LINQ to SQL Class and create methods that will allow us to page data from a SQL database. C# version.

What is Lambda Expressions In LINQ

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:
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