LINQ - Linq to Datatables

Asked By Sree
08-Sep-10 02:45 PM
Datatable PMB(PostalCode,RID)
A1A2A3  000018
A1A2B3  000019
A1A2C3  000020
A1A2D3  000021


DATATABLE MOS(PostalCode,C_Grp,C_Type)
A1A2A3  P A16
A1A2A3  R A18
A1A2B3  F A06
A1A2C3  G B08
A1A2D3  K C09

I am using the following to get PMB Join MOS to get all the records int result DATATABLE Result(RID,C_Grp,C_Type)

var PMBQuery = ds1.Tables["PMB"].AsEnumerable();

var MosQuery = ds1.Tables["Mos"].AsEnumerable();

var query = (from m in MosQuery 

join p in PMBQuery  on m.Field<string>("PostalCode") equals p.Field<string>("PostalCode")

select new

{

RID=p.Field<string>("RID"),

F_Grp=m.Field<string>("C_GRP"),

F_Mos=m.Field<string>("C_MOS"),

 

}).ToList();

dgr3.DataSource = query;


Problem: I am just getting first matched record .
000018 P A16

I should get all the matched records

Any ideas?Am I missing something?


Thanks
Thiru
  Web Star replied to Sree
08-Sep-10 03:00 PM
Try this way this is working perfect in my project.

DataClasses1DataContext dcx = new DataClasses1DataContext(connectionString);
        dcx.Log = Console.Out;

        var orders = from ord in dcx.Orders
             where ord.OrderDate.Value.Year == 1998
             orderby ord.CustomerID, ord.OrderDate
             select new {
               Order_ID = ord.OrderID,      // can just use ord.OrderID
               Customer_ID = ord.CustomerID,  // field name reassignment is optional
               Order_Date = ord.OrderDate  
             };

        this.dataGridView1.DataSource = orders.ToList();

  Sree replied to Web Star
08-Sep-10 03:03 PM
I need a join two datatables and get the resulting datatable having columns from both input tables.
Thanks
  Web Star replied to Sree
08-Sep-10 03:09 PM
You can join two or more table in query and get column which you need
this is working in my project

// Join 3 tables and show couple fields from each

        DataClasses1DataContext dcx = new DataClasses1DataContext(connectionString);

        var joined = from ord in dcx.Orders             // Inner Join
                join detail in dcx.Order_Details
                  on ord.OrderID equals detail.OrderID
                join product in dcx.Products
                  on detail.ProductID equals product.ProductID
          select new {
               ord.OrderID,
               ord.CustomerID,
               ord.OrderDate,
               detail.UnitPrice,
               detail.Quantity,
               product.ProductName
             };

        this.dataGridView1.DataSource = joined.ToList();

  Sree replied to Web Star
08-Sep-10 03:41 PM
is anything wrong in my code that brings only First matched records.
  Sree replied to Web Star
08-Sep-10 03:58 PM
BTW: I am using VS2010.  and Datatables are created from text and Csv files.
  karthik karthik replied to Sree
09-Sep-10 12:09 AM

Hai


Instead Of using the Linq to Datatable U Can use the dataset Merge Concept Like this:
------------------------------------------------------------------------------------------------------------
For Eg tablename1,tablename2 Contains like this records:
----------------------------------------------------------------

TBLKEY EMPKEY EMPNAME  tablename1

----------- ------------------------------ ------------------------------

1       101     RAJA

2       105     POOJA

3       106     THRIU

 

EMPKEY EMPNAME        tablename2

------------------------------ ------------------------------

102     RAJA

103     KARTHIK

105      POOJA

109     ROJA

 

 

this.Page.Unload += new EventHandler(Page_Unload);

sconn.Open();

DataSet ds = new DataSet();

SqlDataAdapter da = new SqlDataAdapter("SELECT * from tablename1", sconn);

da.Fill(ds);

 

 

da = new SqlDataAdapter("SELECT * from tablename2", sconn);

DataSet ds1 = new DataSet();

da.Fill(ds1);

//ds.Merge(ds1);

 

ds.Tables.Add(new DataTable());

ds1.Tables.Add(new DataTable());

 

// primary keys must be set in order for the merge to work

 

ds.Tables[0].PrimaryKey = new DataColumn[] { ds.Tables[0].Columns["EMPKEY"] };

ds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns["EMPKEY"] };

// this is the critical line

 

ds.Merge(ds1, true, MissingSchemaAction.Add);

output like this it will get in the ds after merge:
----------------------------------------------

Serial No Key Empid Empname
1 1   101   RAJA  
2   102   RAJA  
3   103   KARTHIK  
4 2   105   POOJA  
5 3   106   THRIU  
6   109   ROJA  

Try This if its work give me reply.

Create New Account
help
DataGridView populates? Here's how I populate it: DataSet ds = new DataSet(); dgvShipmentHistory.DataSource = null; SqlDataAdapter da = new SqlDataAdapter(mySQLClass.Query, mySQLClass.SqlCon); da.MissingSchemaAction = MissingSchemaAction.AddWithKey; da.Fill(ds, "ShipmentHistory"); dgvShipmentHistory.DataSource = ds.Tables[0]; dgvShipmentHistory.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); I type column so that users can click the hyperlink and I can throw up a page. I bind the grid at runtime, so cannot do this at design time. Thanks C# Discussions DataGridViewAutoSizeColumnsMode.AllCells (1) MissingSchemaAction.AddWithKey (1) MissingSchemaAction (1) MySQLClass.SqlCon (1) SqlDataAdapter (1) DgvShipmentHistory.AutoResizeColumns (1) MySQLClass.Query (1) DgvShipmentHistory.DataSource (1) Rahvyn, You are going to
As New SqlConnection("Server = yileiw2;uid = sqlauth;pwd = sqlauth;database = pubs") Dim da As New SqlDataAdapter("Select * From pub_info", con) Dim MyCB As SqlCommandBuilder = New SqlCommandBuilder(da) Dim ds As New DataSet() da.MissingSchemaAction = MissingSchemaAction.AddWithKey con.Open() da.Fill(ds, "Pub_info") Dim fs As New FileStream _ ("C: \ SomePath sConnectionString) { SqlConnection oConn = new SqlConnection(); DataTable oTable = new DataTable(); try { oConn.ConnectionString = sConnectionString; oConn.Open(); SqlDataAdapter oDA = new SqlDataAdapter("EXEC " + sQuery, oConn); oDA.Fill(oTable); oConn.Close(); } catch (Exception e) { throw new Exception(e retrieve: private void Page_Load( object sender, System.EventArgs e) { / / Put user code to initialize the page here MemoryStream stream = new MemoryStream (); SqlConnection connection = new SqlConnection ( @" server = INDIA \ INDIA;database = iSense;uid NULL ) ON [ PRIMARY ] TEXTIMAGE_ON [ PRIMARY ] • Actually IMAGE field is just holding the reference to the page containing the binary data so we have to convert our image into bytes. • I used above steps you can retrieve and display the image from the database to the web page. refer http: / / www.dotnet-guide.com / save-image-in-sql.html for details. -Paresh Create
code to show that specific record of that product filter with that equipment type in page load try this code Private Sub Button3_Click( ByVal sender As System.Object, ByVal e As sel As String = "SELECT * FROM Customers" Dim ds As DataSet = New DataSet() Dim da As SqlDataAdapter = New SqlDataAdapter(sel, conn) da.MissingSchemaAction = MissingSchemaAction.AddWithKey Dim custCB As SqlCommandBuilder = New SqlCommandBuilder(da) custCB.QuotePrefix = "[" custCB.QuoteSuffix = "]" da.Fill(ds
update my db. I am pulling info from the NW db on my Default.aspx page. I then click the edit btn and pass the data to my Details.aspx page. That works fine. The issue is getting the ds to actually update the db. I tried to do this with code-behind, I normally just use a SqlDS on the page, but want to make the page look cleaner. . . Protected Sub dvDetails_ItemUpdating(ByVal sender As Object, ByVal e As DetailsViewUpdateEventArgs) Handles dvDetails FirstName, Title = @Title, Address = @Address, " & _ HireDate = @HireDate WHERE EmployeeID = @EmployeeID" Dim da As New SqlDataAdapter Dim ds As New DataSet Dim ds1 As New DataSet Dim upCmd As New SqlCommand Update Employees Table ds1 = ds.GetChanges(DataRowState.Modified) da.Update(ds1) ds.Merge(ds1, False, MissingSchemaAction.Add) ds.AcceptChanges() dvDetails.DataBind() Catch ex As Exception 'Display Error Console.WriteLine("Error: " & ex understand it before putting it into a live app. Thanks ADO.NET Discussions DetailsViewUpdateEventArgs (1) MissingSchemaAction (1) DataRowVersion (1) SqlDataAdapter (1) DataRowState (1) SqlDbType (1) SqlConnection (1) SqlParameter (1) It does not look like you
to fill ds and then assign datasource thats works DataSet ds = new DataSet() / / Create a SqlDataAdapter. SqlDataAdapter myAdapter = new SqlDataAdapter() SqlCommand sqlNamesCmd = new SqlCommand ("Select Emp_name from Employee", Con) myAdapter.SelectCommand = sqlNamesCmd myAdapter.Fill(ds Studio 2005, drag and drop File Upload control and a Button control into the web page. 2. In the code-behind, add the namespace System.IO. In the Button’s Button1_Click myConnection.Close(); } 1. Create a Handler.ashx file to perform image retrieval. This Handler.ashx page will contain only one method called ProcessRequest. This method will return binary data to the byte[])dr["Image_Content"]); dr.Close(); myConnection.Close(); } 2. Place a GridView control in your aspx page, with one TemplateField column, add an Image control into the TemplateField's ItemTemplate section. Specify GridView control. The code for FetchAllImagesInfo is public DataTable FetchAllImagesInfo()) { string sql = "Select * from ImageGallery"; SqlDataAdapter da = new SqlDataAdapter(sql, "Your Connection String"); DataTable dt = new DataTable(); da.Fill(dt); return dt; } That's