c#,linq,datagridviewRelated issues-Collection of common programming errors


  • Qwerty Bob
    c# protocol-buffers protobuf-net
    I updated an older version of protobuf to the current one in a huge project (the used version is around 1-2 years old. I don’t know the rev). Sadly the newer version throws an exceptionCreateWireTypeException in ProtoReader.cs line 292in the following test case:enum Test{test1 = 0,test2};static public void Test1(){Test original = Test.test2;using (MemoryStream ms = new MemoryStream()){Serializer.SerializeWithLengthPrefix<Test>(ms, original, PrefixStyle.Fixed32, 1);ms.Position = 0;Test obj;

  • casperOne
    c# .net system.reactive
    I’m using the reactive extensions for a kind of a in process message bus. The implementation is quite simple.Register looks likepublic IDisposable Register<T>(Action<T> action) where T : IMessage {return this.subject.OfType<T>().Subscribe(action); }And send simply:private void SendMessage(IMessage message){this.subject.OnNext(message);}However i’m now having some trouble with the exception behaviour of RX. One an exception is thrown in a registered/subscribed action – the Obser

  • MikO
    c# .net multithreading task
    This question already has an answer here:Access to foreach variable in closure1 answerCan anybody explain why this snippet:// Create required tasks foreach (var messageToSend in messagesToSend) {EmailMessage messageToBeSent = messageToSend;Task<bool> processingTask = new Task<bool>(() => SendMessage(messageToBeSent));processingTask.Start(); }Works differently from this one:// Create required tasks foreach (var messageToSend in messagesToSend) {Task<bool> processingTask = new

  • chrislarson
    c# microsoft-metro windows-runtime
    I’m writing a Windows 8 Metro app. I’m trying to draw a GridView with three Groups. I want one of those groups to layout their items differently than the others. I’ve used Selectors before in WPF, so I thought that’d be a good route. So I tried the GroupStyleSelector and I found this example on MSDN :public class ListGroupStyleSelector : GroupStyleSelector {protected override GroupStyle SelectGroupStyleCore(object group, uint level){return (GroupStyle)App.Current.Resources[“listViewGroupStyle”];

  • eitan barazani
    c# windows-8 sharepoint2013 csom
    I am developing a Win8 (WinRT, C#, XAML) client application (CSOM) that needs to download/upload files from/to SharePoint 2013.How do I do the Download/Upload? Thx

  • Brian Ball
    c# lambda
    I’m running into a problem that I did not expect. An example will probably illustrate my question better than a paragraph:UPDATED: Skip to last code-block for a more eloquent code example.public class A {public string B { get; set; } }public class C : A { }Here is some code from a method:var a = typeof(C).GetMember(“B”)[0]; var b = typeof(A).GetMember(“B”)[0];Expression<Func<C, string>> c = x => x.B;var d = (c.Body as MemberExpression).Member;Here are the results of some compariso

  • Matthew Watson
    c# optimization
    Consider the following code…In my tests for a RELEASE (not debug!) x86 build on a Windows 7 x64 PC (Intel i7 3GHz) I obtained the following results:CreateSequence() with new() took 00:00:00.9158071 CreateSequence() with creator() took 00:00:00.1383482CreateSequence() with new() took 00:00:00.9198317 CreateSequence() with creator() took 00:00:00.1372920CreateSequence() with new() took 00:00:00.9340462 CreateSequence() with creator() took 00:00:00.1447375CreateSequence() with new() took 00:00:00

  • Axel Magagnini
    c# .net windows-services desktop-application watchdog
    I need some way to monitor a desktop application and restart it if it dies. Initially I assumed the best way would be to monitor/restart the process from a Windows service, until I found out that since Vista Windows services should not interact with the desktopI’ve seen several questions dealing with this issue, but every answer I’ve seen involved some kind of hack that is discouraged by Microsoft and will likely stop working in future OS updates.So, a Windows service is probably not an option a

  • Jens
    c# .net networking
    I am trying to (more or less) uniquely identify a system for licensing purposes. I have chosen the computer’s on-board network adapter’s MAC address for this task, since I can be sure that every cmputer running this software actually has one, and this avoids re-activation when changing e.g. the harddrive.I am having troubles reliably identifying the onboard network adapter, though. Using the “Win32_NetworkAdapterConfiguration” ManagementClass, I can get a whole lot of MAC Addresses, including th

  • Nailuj
    c# reflection attributes tdd assert
    I have an example classpublic class MyClass{ActionResult Method1(){….} [Authorize]ActionResult Method2(){….}[Authorize] ActionResult Method3(int value){….}}Now what I want is to write a function returning true/false that can be executed like thisvar controller = new MyClass();Assert.IsFalse(MethodHasAuthorizeAttribute(controller.Method1)); Assert.IsTrue(MethodHasAuthorizeAttribute(controller.Method2)); Assert.IsTrue(MethodHasAuthorizeAttribute(controller.Method3));I got to the point whe

  • Daryl
    c# arrays linq generics
    I ran across this issue today and I’m not understanding what’s going on:enum Foo {Zero,One,Two }void Main() {IEnumerable<Foo> a = new Foo[]{ Foo.Zero, Foo.One, Foo.Two};IEnumerable<Foo> b = a.ToList();PrintGeneric(a.Cast<int>());PrintGeneric(b.Cast<int>());Print(a.Cast<int>());Print(b.Cast<int>()); }public static void PrintGeneric<T>(IEnumerable<T> values){foreach(T value in values){Console.WriteLine(value);} }public static void Print(IEnumerable v

  • Alex K.
    c# asp.net .net linq entity-framework
    I’m using the Code First approach and have the following Model:public class Person {public int ID {get; set;}public string Name {get; set;}public int CurrentStationID {get; set;}public virtual Station CurrentStation {get; set;}public int CurrentTransportationID {get; set;}public virtual Transportation CurrentTransporation {get; set;} }And the following code in my controller:Models.Person model = myDBContext.Persons.Include(“CurrentStation”).Include(“CurrentTransportation”).Where(p => p.ID ==

  • bill weaver
    c# linq linq-to-sql linq-to-xml
    I’m pretty new to Linq to SQL & Linq to XML but have cobbled together some code together that put the XML results from a stored proc into an XElement. However, it’s started failing, apparently now that the XML data is getting larger (2K+) and my .Parse is reading truncated XML (the XML data comes back in two rows). Before i start fumbling into the weeds using xmlReaders and all that, maybe i’m looking at this wrong and there are better approaches.My exact problem is below, but i’m also curio

  • benjy
    c# linq entity-framework linq-to-entities
    Is there a version of the DataLoadOptions class that exists in LINQ to SQL for LINQ to Entities? Basically I want to have one place that stores all of the eager loading configuration and not have to add .Include() calls to all of my LINQ to Entities queries. Or if someone has a better solution definitely open to that as well.TIA, Benjy

  • Abbas
    c# xml linq windows-phone-7 windows-phone-7.1
    For the last couple of hours I was struggling with LINQ to XML on Windows Phone 7. I simply just want to add new element to an existing XML file.XElement newItem = new XElement(“item”,new XAttribute(“id”,3), new XElement(“content”,”Buy groceries”),new XElement(“status”,”false”));IsolatedStorageFile isFile = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream stream = new IsolatedStorageFileStream(“/Items.xml”, System.IO.FileMode.Open, isFile);XDocument loadedDoc = XDocume

  • sweetfa
    linq c#-4.0 typemock
    If I have a typemock test that fakes an instance where the members must specify return values such as below:WallLayers layers = Isolate.Fake.Instance<WallLayers>(Members.MustSpecifyReturnValues); Isolate.WhenCalled(() => layers.GetCoreProfile()).CallOriginal();If within the original GetCoreProfile method I have a linq querywallPoints = fe.GetFacePointsConstrainedBy<Int32>(FaceExtractor.BottomFace, constraints, selector1).Where(p => p.Z == wallReferenceLevel)when running the tes

  • gdoron
    c# .net linq entity-framework lazy-loading
    I read the Loading Related Entities post by the Entity Framework team and got a bit confused by the last paragraph:Sometimes it is useful to know how many entities are related to another entity in the database without actually incurring the cost of loading all those entities. The Query method with the LINQ Count method can be used to do this. For example:using (var context = new BloggingContext()) {var blog = context.Blogs.Find(1);// Count how many posts the blog has var postCount = context.Ent

  • SUMIT CHATTERJEE
    c# linq
    Why changes to the outer data-source is not reflected, while they show-up for the inner data-source?? Pls helppublic static void MyMethod(char[] inputDS1, char[] inputDS2) {Console.WriteLine(“\n’from’ clause – Display all possible combinations of a-b-c-d.”);//query syntaxIEnumerable<ChrPair> resultset = from res1 in inputDS1from res2 in inputDS2select new ChrPair(res1, res2);//Write result-setConsole.WriteLine(“\n\nOutput list –>”);displayList(resultset);//swap positions//obs: changes

  • chobo2
    c# .net linq nhibernate
    Say I have Table A that has many Table B’s. Table B has only one Table A.Now say Table B has a property called Name. How can I do the following in linq.Get all Table A’s where Table B has Name == “bob” then get all Table B’s inside table A.ExampleTable B Name TableA_Id bob 1 bob 1 bob 1 jim 1 jon 2So if I would a query I would want one Table A object back with 3 Table B objects within it.I triedsession.Query<TableB>().where(x => x.Name == “bob”).select(x => x.TableA)

  • David
    c# linq
    I have a process where I identity rows in a list (unmatchedClient) then call a separate method to delete them (pingtree.RemoveNodes). This seems a little long winded and I could acheive the same thing by merely setting the value of the property “DeleteFlag” to true. But how do I set the value using linq?var unmatchedClient = pingtree.Nodes.Where(x =>_application.LoanAmount < x.Lender.MinLoanAmount ||_application.LoanAmount > x.Lender.MaxLoanAmount ||_application.LoanTerm < x.Lender.M

  • Arnold4107176
    c# list datagridview virtual
    Previously I asked a question about my dataGridView’s performance due to it havign to display a large amount of rows that get added based on an incoming stream. Multiple solutions were given, one of them enabling virtual mode. MSDN has an article on the subject but it feels more complicated than what I need as it uses a database and an editable field. My DataGridView is only for displaying and the data I display is placed in a List.After I accepted an answer I received this link: http://www.code

  • kobaltz
    c# csv datagridview datasource
    I have the following code which pulls the data from a CSV file specified by the user. The CSV file is without any headers and has four columns of data. I’m trying to import this data into the dataGridView datasource, but get unexpected results. Each time, it takes the first row and makes it the header column. I tried inserting a row at the beginning (commented out text), but it will only add the row to the datasource, but not treat it as the header. I’m not too worried about having headers, but

  • Igby Largeman
    c# .net sql ado.net datagridview
    My DataGridView is bound to a database query result via a SqlDataReader, and when I test a cell value for null, I’m getting unexpected results.My code is something like this:SqlConnection con = new SqlConnection(“Data Source = .;Initial Catalog = SAHS;integrated security = true”); con.Open(); SqlCommand cmd3 = new SqlCommand(“select Status from vw_stdtfeedetail where Std= 6 and Div =’B’ and name=’bbkk’ and mnthname =’June'”, con); SqlDataReader dr = cmd3.ExecuteReader(); BindingSource bs = new

  • davioooh
    c# .net winforms validation datagridview
    I’m working with DataGridViews in a Windows Form project. I’d like to obtain something similar to what appens, in edit mode, in MS SQL Server Management Studio.I try to explain: I’ve some mandatory columns in my datagrid and I’d like a row is added to the grid only if the values in these columns are valid. If the value of a cell is not valid I’d like to warn the user with a message box and pressing ESC, the incorrect row should be resetted.I tried using CellValidating and RowValidating events, b

  • SteveZ
    vb.net datagridview listbox
    I am encountering what appears to be buggy behaviour by the DGV ListBox control. I’m wondering if there are some “properties” I need to set differently, or alternatively, whether someone has coded some work-arounds for these annoying traits of this control.Regular VB ListBox drop-down control: The first MouseClick on Control causes the dropdown to appear but the edit box remains as it was, either with data which was there originally, or empty if it was empty. If the user then clicks in the free

  • Leron
    winforms visual-studio-2010 datagridview
    I have a dataGridView with a few columns that I’ve arranged according to the order they must appear. However in Visual Studio 2010 in the design view I get this :But when I start the project i debug mode I see this :As yo can see the Delete column has moved. I don’t know why. I tried different scenarios like editing the grid myself and moving the Delete column somewhere else but with no effect. I use a dummy class to get this empty row of data if this somehow has impact on the behavior of this

  • Afnan Bashir
    c# winforms exception datagridview
    I have 1 MDI Parent form named as MainForm and 2 child forms WorkForm and UserOp.WorkForm has datagridview that displays the users and its datasource is BindingList.the BindingList is created from a List of type user and list is declared in parent and is accessed in this with refrence i.e if i make any change to this list eventually it changes the list at parent. here is code how it is done.MainForm mainForm;public WorkForm(MainForm main){InitializeComponent();this.mainForm = main; }similarly it

  • Robert Harvey
    c# linq-to-sql datagridview
    I want to be able to select the columns that are displayed in my DataGridView. I.e., I have a linq query that returns an IEnumerable but I don’t want to display all the properties of Policy – I want to allow the user to choose what to display. So I thought something like this might work to create a “narrower” object with only the columns I want.IEnumerable<Policy> policies = repository.GetPolicies(); var results = from p in policies select new {if (userPicked(“PropertyOne”)) PropertyOne =

  • Muhammad
    c# winforms datagridview formatting int
    I have a databound datagridview. In it I have a column that has NULL values and 1-12. How can I at runtime make the datagridview turn the 1 into January and display it in the cell? And the NULL into another pre-defined string?I tried looking at the cell format, changed it to custom, then put in “MMM” but it did not work and displayed “MMM” in the actual cell.Please help.EDIT: Its winforms c#4.0, the field is bound to Int field from an entity in EF. And no need for culture sensitive, english is f

  • John Saunders
    c# winforms linq linq-to-sql datagridview
    // From my formBindingSource bs = new BindingSource();private void fillStudentGrid() {bs.DataSource = Admin.GetStudents();dgViewStudents.DataSource = bs; }// From the Admin classpublic static List<Student> GetStudents(){DojoDBDataContext conn = new DojoDBDataContext();var query =(from s in conn.Studentsselect new Student{ID = s.ID,FirstName = s.FirstName,LastName = s.LastName,Belt = s.Belt}).ToList();return query; }I’m trying to fill a datagridview control in Winforms, and I only want a fe

Web site is in building