Monday, April 4, 2011

Fetch Data from Control Without Loop- Best Use of LINQ

Hi friends….

Many times I need to generate collection type Data from GridView or Repeater or any other control.. and in that case I used to loop through each rowitem of particular control..

here each row of repeater is listitem of LINQ query.

same way you can perform for all DataBound Controls like GridView, Repeater, DataList, DropDownlist, CheckboxList, Radiobuttonlist etc…

but after using LINQ, I am able to do that very easily

here is sample of Repeater control to Get List of data

List ctrls = (from item in rptctrlList.Items.Cast()
                                    where ((CheckBox)item.FindControl("chkctrl")).Checked
                                    select new ctrlInfo()
                                    {
                                        ctrlId = Convert.ToInt32(((HiddenField)item.FindControl("hdnctrlId")).Value),
                                        UserctrlId = Convert.ToInt64(((HiddenField)item.FindControl("hdnUserctrlId")).Value),
                                    }).ToList();


now I can pass XML to database from this List<ctrlInfo> using


 



var ctrlXML = from ctrl in ctrls
                          select new XElement("ctrl",
                          new XElement("UserId", ctrl.UserId),
                          new XElement("ctrlId", ctrl.ctrlId),
                          new XElement("UserctrlId", ctrl.UserctrlId));
            ctrlsXML.Add(ctrlXML);





Now…. You can pass the XML to Stored Procedure. and in Stored Procedure


using


SELECT 
c.value('ctrlId[1]','int') As ctrlId
, c.value('UserId[1]','BigInt') As UserId
, c.value('UserctrlId[1]','BigInt') As UserctrlId
FROM @ctrlIdListXML.nodes('/ctrls/ctrl')e(c)




you can have Table of selected records of Repeater control.


using merge statement you can perform operation.


 


Hope this Helps


All the Best

No comments: