populate a DataSet via a LINQ query (Linq to XML)

Is there a way to populate a DataSet via a LINQ query?

(Linq to XML)

Instead of;
     DataSet ds = new DataSet();
     ds.ReadXml(myfile.xml, XmlReadMode.InferTypedSchema);
     dataGridView1.DataSource = ds.DefaultViewManager;
     dataGridView1.DataMember = "myNode";


Anthony 


0
Anthony
4/13/2010 4:21:04 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

12 Replies
1472 Views

Similar Articles

[PageSpeed] 37

Anthony wrote:
> Is there a way to populate a DataSet via a LINQ query?
> 
> (Linq to XML)
> 
> Instead of;
>      DataSet ds = new DataSet();
>      ds.ReadXml(myfile.xml, XmlReadMode.InferTypedSchema);
>      dataGridView1.DataSource = ds.DefaultViewManager;
>      dataGridView1.DataMember = "myNode";
> 
> 
> Anthony 
> 
> 

You use a Linq-2-XML query and just bind the Linq query results to the 
control. You can do that. You don't need a dataset.
0
Mr
4/13/2010 4:39:34 PM
> You use a Linq-2-XML query and just bind the Linq query results to the 
> control. You can do that. You don't need a dataset.

How can i bind the Linq query results to the control ?

Anthony 


0
Anthony
4/13/2010 5:10:57 PM
Anthony wrote:
>> You use a Linq-2-XML query and just bind the Linq query results to the 
>> control. You can do that. You don't need a dataset.
> 
> How can i bind the Linq query results to the control ?
> 

It's in the link.

http://blogs.techrepublic.com.com/programming-and-development/?p=594
0
Mr
4/13/2010 5:56:17 PM
> It's in the link.
>
> http://blogs.techrepublic.com.com/programming-and-development/?p=594

I still have a problem.
I've a windows form application and DataGridView does not contain a 
definition for 'DataBind' and no extension method 'DataBind'.

Anthony 


0
Anthony
4/16/2010 6:36:03 AM
Anthony wrote:
>> It's in the link.
>>
>> http://blogs.techrepublic.com.com/programming-and-development/?p=594
> 
> I still have a problem.
> I've a windows form application and DataGridView does not contain a 
> definition for 'DataBind' and no extension method 'DataBind'.


XDocument xmlDoc = XDocument.Load(@"c:sites.xml");
var q = from c in xmlDoc.Descendants("site")
where c.Attribute("technical").Value == "true"
select new {
name = c.Element("name").Value,
url = c.Element("url").Value
};

All you have to do here is this.
dataGridView1.DataSource = q;

I think it will bind to the List<T> 'q'. 'q' is a collection of objects

You may look into BindingSource control still using BS.Datasource = q;
0
Mr
4/16/2010 7:56:47 AM
[ . . ]

> dataGridView1.DataSource = q;

This does not work

> You may look into BindingSource control still using BS.Datasource = q;

Tried this:
   bindingSource1.DataSource = q;
and set the DataGrid's datasource to bindingSource1

This does not work either.

Anthony


0
Anthony
4/16/2010 5:12:53 PM
Anthony wrote:
> [ . . ]
> 
>> dataGridView1.DataSource = q;
> 
> This does not work

Try
   dataGridView1.DataSource = q.ToList();



-- 

	Martin Honnen --- MVP Data Platform Development
	http://msmvps.com/blogs/martin_honnen/
0
Martin
4/16/2010 5:27:35 PM
> Try
>   dataGridView1.DataSource = q.ToList();

That's the trick :-))))

Thank you very much !

Anthony 


0
Anthony
4/16/2010 6:27:25 PM
Anthony wrote:
> [ . . ]
> 
>> dataGridView1.DataSource = q;
> 
> This does not work
> 
>> You may look into BindingSource control still using BS.Datasource = q;
> 
> Tried this:
>    bindingSource1.DataSource = q;
> and set the DataGrid's datasource to bindingSource1
> 
> This does not work either.
> 
> Anthony
> 
> 

I copied the xml for sites to a file on the HD  from the link I provided 
you.

I ran this code and it showed the data in the dataGridView.

         private void Form1_Load(object sender, EventArgs e)
         {

             XDocument xmlDoc = XDocument.Load(@"d:\\duane1\\sites.xml");

             var q = from c in xmlDoc.Descendants("site")
                     where c.Attribute("technical").Value == "true"
                     select new
                     {
                         Name = c.Element("name").Value,
                         URL = c.Element("url").Value
                     };

             var bs = new BindingSource {DataSource = q};

             dataGridView1.AutoGenerateColumns = true;
             dataGridView1.AutoSize = true;

             dataGridView1.DataSource = bs;
         }
0
Mr
4/16/2010 6:35:25 PM
>             var bs = new BindingSource {DataSource = q};
>
>             dataGridView1.AutoGenerateColumns = true;
>             dataGridView1.AutoSize = true;
>
>             dataGridView1.DataSource = bs;
>         }

That's another trick (with a few more lines of code)    :-))))

Do you know why i now can't sort the DataGrid by clicking the column header?
By default, users can sort the data in a DataGridView control by clicking 
the header of a column.

Thank you very much !

Anthony 


0
Anthony
4/17/2010 7:24:00 AM
Anthony wrote:
>>             var bs = new BindingSource {DataSource = q};
>>
>>             dataGridView1.AutoGenerateColumns = true;
>>             dataGridView1.AutoSize = true;
>>
>>             dataGridView1.DataSource = bs;
>>         }
> 
> That's another trick (with a few more lines of code)    :-))))
> 
> Do you know why i now can't sort the DataGrid by clicking the column header?
> By default, users can sort the data in a DataGridView control by clicking 
> the header of a column.
> 
> Thank you very much !

I am more of a Web.UI.Control programmer rather that Windows.UI.Control 
programmer. So, I don't know why the sort by column header doesn't work 
for you.

You may have to do it manually if someone can't help you to make it work 
automatically.

http://msdn.microsoft.com/en-us/library/0868ft3z.aspx

You can also consider this event.

ColumnHeaderMouseClick
This event is used to capture when a header is clicked.
Sometimes you may need to modify the direction that the
sort glyph is pointing in the column squares.
You can check e.ColumnIndex on the event parameter to
find out which of the column headers was clicked.

http://dotnetperls.com/datagridview-tips

You might use this event, and based on e.ColumnIndex, query and sort 'q' 
on corresponding property in the list of objects in 'q' and rebind.

If(e.ColumnIndex == 0)
{
   var q1 = (from a in q.OrderBy(b => b.Name) select a).tolist();
   // bind q1
}

If you want descending then q.OrderByDescending(b => b.Name).

HTH

0
Mr
4/17/2010 1:26:43 PM
> I am more of a Web.UI.Control programmer rather that Windows.UI.Control 
> programmer. So, I don't know why the sort by column header doesn't work 
> for you.
>
> You may have to do it manually if someone can't help you to make it work 
> automatically.
>
> http://msdn.microsoft.com/en-us/library/0868ft3z.aspx
>
> You can also consider this event.
>
> ColumnHeaderMouseClick
> This event is used to capture when a header is clicked.
> Sometimes you may need to modify the direction that the
> sort glyph is pointing in the column squares.
> You can check e.ColumnIndex on the event parameter to
> find out which of the column headers was clicked.
>
> http://dotnetperls.com/datagridview-tips
>
> You might use this event, and based on e.ColumnIndex, query and sort 'q' 
> on corresponding property in the list of objects in 'q' and rebind.
>
> If(e.ColumnIndex == 0)
> {
>   var q1 = (from a in q.OrderBy(b => b.Name) select a).tolist();
>   // bind q1
> }
>
> If you want descending then q.OrderByDescending(b => b.Name).
>
> HTH
>

Thank you for the explanation.

But it is weird that the default sort by clicking the header of a column 
disappeared.
I've checked all settings again, but no result.

Anthony 


0
Anthony
4/19/2010 5:49:34 AM
Reply:

Similar Artilces:

why doesn't this modification to XML receipt work?
how can i modify the fullpage.xml file so that if the sale is charged to the customer's store account, the title of the receipt is 'SALES INVOICE' - otherwise we want the title to be 'SALES RECEIPT'...i tried modifying the file as shown below without success: <IF><CONDITION> Tender.Descriptor.TenderType = 4 </CONDITION> <THEN> <TEXT> "SALES INVOICE" </TEXT> </THEN> <ELSE> <TEXT> "SALES RECEIPT" </TEXT> </ELSE> <...

eConnect
In eConnect, I tried adding an additional XML node to the existing XML schema. I like to have these to be added in line item level. When I tried this, it worked fine when I added a node (along with a procedure in db) at the header level. But it fails to perform at line item level. Please help me with the steps to achieve the same. Thanks in advance. ...

Sequence Not populated for the MO Numbers during Data Collection
When data collection is done for the MO Numbers by using the Data Collection Window under Manufaturing, the Sequnce look up does not show the whole list, it only shows NOTES, for the user to select and enter the necessary data. why does this happen in the case of some MO Numbers and in the others it shows all the sequnces as NOTES,MAKE READY, PRESS RUN, WASH UP, MAINTENANCE, REPAIRS, REWIND/INSPECTION, etc. Any information would be much appreciated -- Thanks AshaM It should show all of the router steps. Are some of your steps possibly marked to backflush labor? These steps would not...

GetXml from DataSet
Hello, I transfer data from a dataset to an XML-document by using the GetXml-method in VB.NET. I noticed, that for datafields, which are empty (have no content) in the dataset, no elements are created in the XML-document. How can I force to generate elements (with no content) for this kind of datafields ? Thanks em Check out http://www.topxml.com/sqlxml/default.asp It has some excellent information on this. Regards Keith Chadwick "em" <nix@nix.nix> wrote in message news:018f01c3ba37$e4b0b760$a001280a@phx.gbl... > Hello, > I transfer data from a dataset to an XML...

optional parameter query
I have a form with start date and end date parameters that the user can input to run a query. I would like the query to be set up so that null parameters means to ignore that constraint. That is to say: if a is not null and b is not null then c between a and b else if a is not null and b is null then c >= a else if a is null and b is not null then c <= b else do nothing and move on except using iif because if/then/else doesn't work in sql as far as i know. What is the real code for "do nothing and move on?" I tried using wildcards (else a = *), but it didn't work, pr...

Drill down pivot table data via VBA macro
I am trying to create a macro that will drill down subtotals from a pivot table. Since the number of rows, and colums, changes frequently I need to reference the total for the row or column. Can this be done via VBA macro? -- jmon76 ------------------------------------------------------------------------ jmon76's Profile: http://www.thecodecage.com/forumz/member.php?u=1909 View this thread: http://www.thecodecage.com/forumz/showthread.php?t=204538 http://www.thecodecage.com/forumz Excel 2007 PivotTable Show subtotal details via macro. Define subtotal with PivotField...

Update to Access Multiple tables via VBA
I'm somewhat familiar with updating from Excel to Access via VBA. How can I update to multiple tables in Access that have a one to many relationship using VBA. Table are linked via key. tbl_One is one Many with tbl_Two via Foreign Key tbl_One is one Many with tbl_Three via Foreign Key Set db = OpenDatabase("C:\LinkedTest\LinkTestDB.mdb") ' open the database Set rs = db.OpenRecordset("tbl_One", dbOpenTable) With rs ..AddNew ' create a new record ' add values to each field in the record .Fields(&...

Loosing parameters via xml control
Howdy I have an xslt that accepts parameters. In my code I set these paramaters and pass them to the xml control to transform and display the xml according to the xslt. When I throw the form directly into the response.write it shows my paramaters just fine. Since I altered the code to use the Xml Control, these parameters are not received by the Xslt upon transformation via the xml control. Here is my code. '*CTE00 - Throw the Document into a xml navigator. '************************************************* NavApproveCondition = DocApproveCondition.CreateNaviga...

ms crm startup sap document via .Net Connector
Has anyone used the SAP .Net Connector to show account details based on the sap customer id ? Any example or info is more than welcome ...

Populating Excel from CSV
Hello all, I need to know how to populate an Excel template with data from a external CSV file. Let's say I have this nice pretty colourful templat that is far more pleasing to the eye than the usual chunk of importe CSV data, what are some methods to populate it with data from a CS file?? Any ideas or suggestions or redirections would be much appreciated. Thanks in advance : -- AJMorgan59 ----------------------------------------------------------------------- AJMorgan591's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=2777 View this thread: http://www.ex...

Dlookup in query
Hi guys, I have a query in which i want to use a dlookup which i have embedded in a function. Strange thing is that the first record returns the correct value and after that i get a invalid use of null.. ?? scenario (for testing purposes) table1: MyDate (set to date time) MyAmount (set to currency - standard - two decimals) table2: Dummy (text field) FutureDate (Set to date time) Created a query with the two fields from table2 both fields added to the querygrid. Third field added as follows: Amount: getprice(FutureDate) Module: function GetPrice(FutureDate) as d...

query LDAP
I'd like to make a worksheet with the following columns: Username Full name Email This data is somewhere inside our address book server, an LDAP server (not Windows). I have Googled this but have not yet found interesting results. -- Amedee Van Gasse using XanaNews 1.17.3.1 If it has an "X" in the name, it must be Linux? How To Ask Questions The Smart Way http://www.catb.org/~esr/faqs/smart-questions.html How to Report Bugs Effectively http://www.chiark.greenend.org.uk/~sgtatham/bugs.html Only ask questions with yes/no answers if you want "yes" or "no" a...

Subform Linking via Code
Hello All, I am trying to change the child/master links for a subform at the click of a button. The reason for this is to switch between current and completed projects in the subform. There is already a filter on the parent for which proved too difficult to amend. My problem occurs when I click on the button. I get a warning that tells me that the master and child properties must contain the same number of fields. Is there a way to bypass this warning so that the rest of my script can run? Here is the code I have so far: Private Sub Toggle_Current_Complete_Click() Me.PMInterfaceSub.Li...

how do populate empty cells with the contents of populated cells .
I have this worksheet problem. The work sheet is thousands of rows long. One of my columns has cells not populated. I would like to get any empty cell in this column to populate itself with the contents of the next populated cell below it? Kind of a "find and replace" action where by an empty cell says to it self;"I'm going fill myself in with the next thing I find below me" I would greatly appreciate if someone can relate how to do this. Thanks Jim, Select the column, use Edit | Go To... Special , Blanks, OK. Then type an equal sign, press the down arrow...

Help : Using Parameters with External Date Query
For some reason, whenever I do an external data query, the Parameters button/feture is ghosted and unavailable. Can someone explain why this might be happening? ...

The kerberos client received a KRB_AP_ERR_MODIFIED error and Failed to query SPN registration on DC 'hostname_ho.domainname.local'
We have various branches connected to our main branch, but one of the domain controller from one of the small branches is having issue and is not replicating with DCs in the main office. It is also generating the event ID #4: "The kerberos client received a KRB_AP_ERR_MODIFIED error from the server host/name_host.domainname.local. The target name used was host2/ name.host.domainname.local. This indicates that the password used to encrypt the kerberos service ticket is different than that on the target server. Commonly, this is due to identically named server accounts in the tar...

Autoplay for Pictures Not Populated
I inserted my XD card in to my card reader today and the autoplay pop up window asking what I wanted Windows to do was blank. For Video, Music and Mixed content the options are there but not for Pictures - it is just blank. I have tried running autofix.exe but this has not fixed it. Any ideas? Is this a Microsoft problem or has something else caused this? It worked fine until today. Thanks. Peachypumpkin wrote: > I inserted my XD card in to my card reader today and the autoplay > pop up window asking what I wanted Windows to do was blank. For > Video, Music and Mi...

Query parent elements (newbe question)
Hi, I have a XML file where I want to query elements but id of the element is buried deep inside child elements for example: <XmlRoot> <XmlPosition> <PositionRecordInfo> <PositionId>1</PositionId> <PositionStatus>Active</PositionStatus> </PositionRecordInfo> <PositionTitle>.NET Developer</PositionTitle> <PositionDescription>Some sample text here</PositionDescription> </XmlPosition> <XmlPosition> <PositionRecordInfo> ...

Microsoft Query in Excel
I am trying to set up some queries in excel that reference an access database. Problem is that the location of the database and the name changes based on what project I am working on. What I guess I want to do is set up a query template and then change the location where those templates pull data from. The database objects will not change when copied, only the database name and location. Is this possible? Feel free to contact me with any questions. 518-464-1717 Thanks, Marc Bachand ...

City and State Populated by Zip Code
Does anyone know of a way to load a program that when you type in the Zip Code the City and State are automatically populated? I have seen a MSCRM add-in from a company called QAS (http://www.qas.com/). This is more than just Zip Code/City&State. It's a full address validator along with streamlined data entry. They have integrated with CRM via an ISV pop-up and it seems to work fairly smoothly. Matt Parks MVP - Microsoft CRM ---------------------------------------- ---------------------------------------- On 15 Apr 2005 11:13:56 -0700, "Morgan" <tzeoli@att.net> wr...

Pass cell data to Query
Anyone know how to pass the contents of a cell to an sql query? I have a worksheet that I have connected to an SQL database that I want to query to get data. The worksheet is like an invoice. What I want is the user to input a product code and currency then the query to return the price. It sounds simple enough to do with a nested function but the price list is made complex by prices in different currencies so the level of nesting allowed is insufficient. I thought a database query would be a more appropriate solution but I can't find any information on how to do it in this way. -...

query with insert but how
Hello everybody, I have two tables with this structure: table1: 1) ID (Counter + primary 2) lfd_nr (integer) 3) Field1 (Text) Table2: 1) ID (Integer) 2) lfd_nr (integer) 3) Field1 (Text) ID from the first and second table are in 1:n Relation Now I would like to insert the records from the first table where lfd_nr=1 in the same table with lfd_nr=2. Further I would like to insert the records from the second table where lfd_nr=1 in the same table with lfd_nr=2 but so that the ID-field in new records (lfd_nr=2) corresponds the ID-field in the first table where lfd_nr=1. Please help! Mario ...

cannot add user into Active Directory via c#.net
My System Have 2 Computer: Frist Computer act as A domain Controller that has a Active Directory,RADIUS Server,DHCP and DNS Second Computer act as A Web Server(join domain with a first computer already) and use Microsoft Visual Studio Team System 2008 I create a website on a second computer to add user in active directory. I have 3 file: 1.Default.aspx - Let user fill their privacy information 2.ViewRegisterdata.aspx - Let user confirm their information before it's added to active directory. In this file,there is a Viewregisterdata.aspx.cs which collect user information...

Populating a field
I want to populate a description field based on a par number that is entered in the field before it. In other owrds, you enter a part number and presto, in the next field, the description is entered for you. Can you help?? Thanx Tom On Thu, 6 Dec 2007 08:48:01 -0800, Tom <Tom@discussions.microsoft.com> wrote: >I want to populate a description field based on a par number that is entered >in the field before it. In other owrds, you enter a part number and presto, >in the next field, the description is entered for you. > >Can you help?? > >Thanx >Tom If yo...

Web Query HELP!!!
Hi, I am using Excel 2003 Web Query. I have an ASPX web page that prints a Database table, and when I enter the URL in the "Data->Import External Data->Web Query" wizard, the Page displays correctly in the preview pane. But, when I am done (hit import button), Excel tries to retrieve the data but fails with the message: "The Web query returned no data. To modify the query, click OK, click the name of the external data range in the name box on the formula bar and then click Edit Query on the External Data toolbar." I have not been able to trace the problem. Any h...