Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
SLOSifl
Aug 10, 2002


Grid Commander posted:

Switch is basically a special case that does not fit your need in this scenario.
Switch can not be used for your example at all.
Edit: Meaning a new programming construct would be required to make code as you have suggested above work.
It looks like you basically need a bunch of if statements here.

Here is what you describe above (except rewritten):
What? All you did was nest ifs in a weird way and make the final else separate for some reason. Here's my code in valid C#:
code:
switch ( comparisonVariable ) {
   case someValue:
      // do stuff
      break;
   case somethingElse:
      // do stuff
      break;
   case whatever:
   case whateverElse:
      // multiple values
      break;
   default:
      // yeah
      break;
}
And in an if-else:
code:
if ( compVar == someValue ) {
  // do stuff
} else if ( compVar == somethingElse ) {
  // do stuff
} else if ( compVar == whatever || compVar == whateverElse ) {
  // multiple values
} else {
  // default
}
The switch statement does not fit C# convention. It uses code labels for each case which is found nowhere else in common code. It uses a code-block concept but requires a keyword to terminate the block rather than a curly brace. I like the fact that C# switch cases don't fall through (unless empty).

A switch construct is essentially an if-else statement. Nothing special about it other than it's a mess of special language constructs and unintuitive behavior.

Adbot
ADBOT LOVES YOU

biznatchio
Mar 31, 2001


Buglord

SLOSifl posted:

A switch construct is essentially an if-else statement. Nothing special about it other than it's a mess of special language constructs and unintuitive behavior.

A switch block can be compiled to a block of code that runs more efficiently once you get above a certain number of cases.

SLOSifl
Aug 10, 2002


biznatchio posted:

A switch block can be compiled to a block of code that runs more efficiently once you get above a certain number of cases.
I mean as far as what you can do with it as a programmer, it's essentially an if/else. I'm sure there are optimizations made, and there are obvious times when a switch is more natural than a long, repetitive if-else anyway.

I'm not saying there's no point or benefit to switch blocks, just that the syntactic construct itself should have been updated with the development of C#.

Victor
Jun 18, 2004
Implicit fall-through in switch statements is allowed for empty bodies. Otherwise, you need to use "goto case ..." syntax. I like it. I think I will agree with Grid Commander that a better syntax could have been chosen, but what is done is done.

foxxtrot, I must disagree with you on the requirement that the ternary operator's value be used as an r-value, and that non-zero values should be implicitly converted to zero. The latter issue is probably due to the nature of the programming I do: I don't do many bit tests. I think that if one is not careful about implicit conversion to boolean, code can have hard-to-find bugs and be unreadable. It's a trade-off, and my opinion is that the C# team chose the right path. If the situation were optimal, the main .NET language in use would be more ideal (like not having C syntax), have functional characteristics, etc. That is not the case, although C# 3.0 is a bit functional, which is quite cool. Let me know if you're interested in more of my thoughts on the issue.

Toenail Ninja
Sep 10, 2003

Superman is back!
It's great!

Toenail Ninja posted:

I'm currently evaluating our ability to upgrade from Visual Studio 2003 to 2005 and .NET 2.0. I've run into some issues, but the biggest one is our Crystal Reports. We use Crystal Reports Server and Developer 10 in our ASP.NET 1.1 application. I've upgraded a local copy of our web app to 2.0, and when I try to run a Report, I get an "An Enterprise Report Application Server was not found" error. I can run the reports from our development solution perfectly.

Is it possible to continue using CR 10 with VS2005, or do we have to shell out the money to upgrade to 11?

Anyone have any thoughts on this? Google has been incredibly unhelpful.

foxxtrot
Jan 4, 2004

Ambassador of
Awesomeness

Victor posted:

foxxtrot, I must disagree with you on the requirement that the ternary operator's value be used as an r-value, and that non-zero values should be implicitly converted to zero. The latter issue is probably due to the nature of the programming I do: I don't do many bit tests. I think that if one is not careful about implicit conversion to boolean, code can have hard-to-find bugs and be unreadable. It's a trade-off, and my opinion is that the C# team chose the right path. If the situation were optimal, the main .NET language in use would be more ideal (like not having C syntax), have functional characteristics, etc. That is not the case, although C# 3.0 is a bit functional, which is quite cool. Let me know if you're interested in more of my thoughts on the issue.

I've done a fair amount of low-level programming in C++, so there are plenty of times I've used the ternary operator as a one-line If-Then-Else. It's convenient, and as long as it's only used at appropriate times, it never really sacrificed much code readability.

I agree with you about the nature of C# though, there are times that they made decisions regarding the language because "that's what C/C++ does" rather than "this makes sense for our language and our goals." Personally, I like C syntax because I'm comfortable with it, which is the main reason that I do most of my .NET programming in C# (though I've started playing around a bit with boo).

I haven't really looked at C# 3.0, the book I have for C# was made for .NET 1.1, is there are good reference for the updates to the language since that time?

MagicAlex
Jan 6, 2007

Not sure if this has been asked before, but I'm up to page 6 and I have to go to work.

Can you work with data sets in C# and Visual Studio without having SQL Server running? I'm trying to display info in a DataGrid, but I don't have any kind of database set up. Furthermore, the program is supposed to be for personal use so I don't really want to run a server just for this one program.

Victor
Jun 18, 2004

foxxtrot posted:

I haven't really looked at C# 3.0, the book I have for C# was made for .NET 1.1, is there are good reference for the updates to the language since that time?
I don't know about C# 3.0 books, but you should read CLR via C# if you have not. You might also find some of my C# links useful. I can't wait for C# 3.0 to come out; quite a bit of my code could be made more elegant via LINQ.

foxxtrot
Jan 4, 2004

Ambassador of
Awesomeness

MagicAlex posted:

Can you work with data sets in C# and Visual Studio without having SQL Server running?

You could create the database in Access and use the OdbcDatacConnection to access it.

genki
Nov 12, 2003

MagicAlex posted:

Not sure if this has been asked before, but I'm up to page 6 and I have to go to work.

Can you work with data sets in C# and Visual Studio without having SQL Server running? I'm trying to display info in a DataGrid, but I don't have any kind of database set up. Furthermore, the program is supposed to be for personal use so I don't really want to run a server just for this one program.
Yes. You can create datatables, create columns in the datatables, populate info programmatically, and display it in a datagrid.

edit:
here's some quick sample code. create a new windows app, stick in a datagrid view, add these methods, call CreateDataTable() in Load, it will populate the datagrid view.

code:
        public void CreateDataTable()
        {
            int colcount = 3;
            DataTable dt = new DataTable();
            for (int i = 0; i < colcount; i++)
            {
                dt.Columns.Add(CreateColumn(i));
            }
            for (int i = 0; i < 20; i++)
            {                
                dt.Rows.Add(CreateRow(dt.NewRow(), i));
            }
            dataGridView1.DataSource = dt;
        }

        public DataColumn CreateColumn(int i)
        {
            DataColumn col = new DataColumn("Column" + i.ToString("00"));
            col.DataType = typeof(string);
            return col;
        }

        public DataRow CreateRow(DataRow row, int i)
        {
            foreach (DataColumn col in row.Table.Columns)
            {
                row[col] = "Data" + i.ToString("00") + col.ColumnName;         
            }
            return row;
        }

genki fucked around with this message at 22:08 on Feb 16, 2007

Colbo
Jul 12, 2002

The monkey is not impressed

MagicAlex posted:

Not sure if this has been asked before, but I'm up to page 6 and I have to go to work.

Can you work with data sets in C# and Visual Studio without having SQL Server running? I'm trying to display info in a DataGrid, but I don't have any kind of database set up. Furthermore, the program is supposed to be for personal use so I don't really want to run a server just for this one program.


You certainly can. DataSets have no dependency on any datasource as far as just working with them in code. If you need to save/load data you can always use an xml document to store your data and use the DataSet.LoadXML or DataSet.WriteXML methods to load/save it.

fankey
Aug 31, 2001

I have a class I'd like to serialize using the binary formatter. This class contains a System.Windows.Media.Color field which is a structure that is not inherently serializable. What's the most straightforward way to deal with this issue? I see a couple of options, none of which are ideal.

1. Implement ISerializable and do everything by hand. I don't like this idea since any field I add in the future I have to remember to add them to the constructor and GetObjectData members.

2. Make a wrapper class for Color. Once again, not ideal from a code management standpoint.

Is the built in serialization support just too limiting? Any easy way to accomplish this?

wwb
Aug 17, 2004

On datasets: rather than creating them in code, you can use the dataset designer to create your own strongly typed dataset.

fankey
Aug 31, 2001

I have a question about doing custom serialization. I have a base class and a derived class and would like to automatically serialize the fields defined in each object. I can't use the auto-generated serialization since I need to have hooks for missing/changed data in my objects. I figured all I needed to so was to implement GetObjectData in my base class and have that iterate each field and write it out.

When I call Type.GetFields on my derived type I only get the public and protected fields, not any private fields. If I then call GetFields() on the base type ( until Type.BaseType returns null ) I can then iterate all private fields of my class hierarchy. The problem is when I serialize the data I get an exception - Cannot add the same member twice to a SerializationInfo object.

I think this is happening because any base class protected fields in my object are 'found' twice since they're visable in both the base and derived class. If I make all fields private then the serializaion works properly. Is this a safe way to go about serializing my data? Should I take another approach? Here's some code that shows the problem -

code:
  [Serializable]
  class Base : ISerializable
  {
    // making this protected breaks serialization
    private string Name;
    public Base(string Name)
    {
      this.Name = Name;
    }
    private void _GetObjectData(Type type, SerializationInfo info, StreamingContext context )
    {
      if (type != null) 
      {
        System.Console.WriteLine("saving " + type.FullName + "...");
        System.Console.WriteLine("GetFields()...");
        foreach (System.Reflection.FieldInfo fi in type.GetFields(
          System.Reflection.BindingFlags.NonPublic |
          System.Reflection.BindingFlags.Instance ))
        {
          if (fi.IsNotSerialized)
          {
            Console.WriteLine("not saving " + fi.Name );
          }
          else
          {
            Console.WriteLine("writing {0} : {1}", fi.Name, fi.GetValue(this));
            info.AddValue(fi.Name, fi.GetValue(this));
          }
        }
        _GetObjectData(type.BaseType, info, context );
      }
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
      _GetObjectData(this.GetType(), info, context);
    }
  }

  [Serializable]
  class Derived : Base
  {
    protected string Prop = "a property";
    public Derived(string Name, string Prop ) : base( Name ) 
    {
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      try
      {
        Derived d = new Derived("a name", "a prop");
        BinaryFormatter bf = new BinaryFormatter();
        FileStream fs = new FileStream("test.dat", FileMode.Create, FileAccess.Write, FileShare.None);
        bf.Serialize(fs, d);

      }
      catch (Exception ex)
      {
        System.Console.WriteLine(ex.Message);
      }
    }
  }
EDIT: It looks like adding DeclaredOnly as an additional flag to GetFields works for me. I still have a question as to if this is a good way to go about this.

fankey fucked around with this message at 21:28 on Feb 19, 2007

biznatchio
Mar 31, 2001


Buglord

fankey posted:

EDIT: It looks like adding DeclaredOnly as an additional flag to GetFields works for me. I still have a question as to if this is a good way to go about this.

If it works, go with it. Revisit it at a later date if performance ends up being a problem and profiling determines it as a cause.

Arms_Akimbo
Sep 29, 2006

It's so damn...literal.
This should be a pretty simple one...

I'm working on a proof of delivery input system for my company in ASP.net 2.0 (VB in VS 05, if that matters) I want to create a drop down list that has all the driver names in it, in a "Last Name, First Name" format. The problem is that the name is stored across two fields on the driver DB, last_name and first_name.

Is there some kind of way I can populate this drop down list without any additional code? I know I can do a Do Until EOF -> .Text(x) = y type thing, but i'm curious if there's another way to either link two fields to the object and set a text format or create a query in SQL 05 that will output pre-formatted data. If the latter is possible, I can find a suitable query elsewhere if it's outside the scope of this thread.

Thanks :)

Ch00k
Feb 18, 2004
Chicken
This should do it:

SELECT last_name + ', ' + first_name AS name FROM ...

Some RTRIM()'s around those might be a good idea.

Arms_Akimbo
Sep 29, 2006

It's so damn...literal.

Ch00k posted:

This should do it:

SELECT last_name + ', ' + first_name AS name FROM ...

Some RTRIM()'s around those might be a good idea.

Awesome, thanks a ton.

mmmGamer
Jul 23, 2004

I have a XAML question... Let's say I create a template of a button like the following :

code:
<ControlTemplate x:Key="office2007ishButton" TargetType="{x:Type Button}">
 
<Border Height="36" Width="36" BorderThickness="1" CornerRadius="18" BorderBrush="#6593CF" VerticalAlignment="Center" Margin="1,0,0,0" x:Name="mainBorder">
  <Border.Background>
		<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
			<GradientStop Color="#E3EFFF" Offset="0" />
			<GradientStop Color="#C4DDFF" Offset="0.4" />
			<GradientStop Color="#ADD1FF" Offset="0.4" />
			<GradientStop Color="#C0DBFF" Offset="1" />			
		</LinearGradientBrush>	
  </Border.Background>
	<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" TextElement.FontFamily="Segoe UI" />
  </Border>

  <ControlTemplate.Triggers>

<Trigger Property="IsMouseOver" Value="True">
		<Setter TargetName="mainBorder" Property="Background">
			<Setter.Value>
		<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
			<GradientStop Color="#FFFEE4" Offset="0" />
			<GradientStop Color="#FFE8A7" Offset="0.4"/>
			<GradientStop Color="#FFD767" Offset="0.4"/>
			<GradientStop Color="#FFE69E" Offset="1"/>
		</LinearGradientBrush>
			</Setter.Value>
		</Setter>
	<Trigger.EnterActions>
	 <BeginStoryboard>
		<Storyboard>
			<DoubleAnimation Storyboard.TargetProperty="Height" Storyboard.TargetName="mainBorder" To="42" Duration="00:00:00.18"/>
			<DoubleAnimation Storyboard.TargetProperty="Width" Storyboard.TargetName="mainBorder" To="150" Duration="00:00:00.18"/>
		</Storyboard>
	 </BeginStoryboard>
	</Trigger.EnterActions>
	<Trigger.ExitActions>
	 <BeginStoryboard>
		<Storyboard>
			<DoubleAnimation Storyboard.TargetProperty="Height" Storyboard.TargetName="mainBorder" Duration="00:00:00.18"/>
			<DoubleAnimation Storyboard.TargetProperty="Width" Storyboard.TargetName="mainBorder" Duration="00:00:00.18"/>
		</Storyboard>
	 </BeginStoryboard>

	</Trigger.ExitActions>
         
	</Trigger>

	<Trigger Property="IsPressed" Value="True">
		<Setter TargetName="mainBorder" Property="Background">
			<Setter.Value>
		<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
			<GradientStop Color="#FFD9AA" Offset="0" />
			<GradientStop Color="#FFBC71" Offset="0.4"/>
			<GradientStop Color="#FFAB3F" Offset="0.4"/>
			<GradientStop Color="#FEE079" Offset="1"/>
		</LinearGradientBrush>	
			</Setter.Value>
		</Setter>
	</Trigger>


  </ControlTemplate.Triggers>
 		
</ControlTemplate>
Right now, whenever I want to make the reverse animation, I simply take the animations used in the .EnterAction and remove the "To=" property from it, and add it to the ExitAction of my trigger. It works nicely however, there has to be a cleaner way to do the reverse animation without having to "reset" my values like I do. I tried the RemoveStoryboard however, it won't do the reverse animation.

Boogeyman
Sep 29, 2004

Boo, motherfucker.
Stupid webservice question time! I have two classes...let's pretend they look like this...

code:
Public Class Query

  Public QueryId As Guid
  Public StartTime As Datetime
  Public EndTime As Datetime
  Public Results As List(Of Results)

End Class

Public Class Result

  Public ResultId As Guid
  <SoapIgnore()> Public Query As Query
  Public Info1 As String
  Public Info2 As String

End Class
Everything works great until I try to return an array of Results from a web method. .NET bitches and moans about a circular reference, which makes sense because a Query can contain multiple Results and each Result holds a reference to its parent Query.

Now, I don't actually want to return the Query object to the end user, so I've marked it with a SoapIgnoreAttribute, which should keep that field from being serialized. Unfortunately, this does not work and I still get the circular reference error.

I guess my only option is to write yet another loving wrapper class that contains only the fields from Result (so I'll have InternalResult and Result or some poo poo like that) that should be returned from the service. Is that the way these things are normally done, or am I missing something.

wwb
Aug 17, 2004

^^^Try <XmlIgnore>

PS: Thought I should explain. It is not the soapy bits bitching, it is the XmlSerializer bitching. SoapIgnore is a bit more specialized.

wwb fucked around with this message at 22:46 on Feb 22, 2007

Boogeyman
Sep 29, 2004

Boo, motherfucker.

wwb posted:

^^^Try <XmlIgnore>

You fuckin' rock...that did the trick!

Darn Cotts
Mar 12, 2004

\Job"ber*nowl`\, n. [OE. jobbernoule, fr. jobarde a stupid fellow; cf. E. noll.] A blockhead. [Colloq. & Obs.]
I have a custom control that does a lot of its own drawing and needs to redraw itself every time the mouse moves over it. Hence, in its MouseMove event handler, I call Invalidate().

In this control I have a timer which fires a few times a second, which raises one of the control's events. The control's parent form subscribes to this event and in its handler for it updates a label on the form.

This all works fine when the mouse isn't moving over the control.. but when it is then the label on the parent form isn't being updated at all. Any ideas why this could be?

edit: Fixed. The mouse movement events were flooding the window message queue and the timer ones weren't getting a look in. Changed from using a forms timer to a System.Timers.Timer and all is well :woop:

Darn Cotts fucked around with this message at 00:36 on Feb 23, 2007

slovach
Oct 6, 2005
Lennie Fuckin' Briscoe
How do I change a file extension to a file? I figured it would be as simple as Path.ChangeExtension(openShit.FileName, "lolextension");

but nothing changes afterwards.

Question #2, how would I do this to an entire folder full of files at once? I guess I'm going to need to dip into a foreach? But i've never used that before, so could somebody provide a little example to get me started?

Darn Cotts
Mar 12, 2004

\Job"ber*nowl`\, n. [OE. jobbernoule, fr. jobarde a stupid fellow; cf. E. noll.] A blockhead. [Colloq. & Obs.]

slovach posted:

How do I change a file extension to a file? I figured it would be as simple as Path.ChangeExtension(openShit.FileName, "lolextension");

but nothing changes afterwards.

Question #2, how would I do this to an entire folder full of files at once? I guess I'm going to need to dip into a foreach? But i've never used that before, so could somebody provide a little example to get me started?
All Path.ChangeExtension does is return a string containing the filename you give it but with the extension changed to what you want, it doesn't actually do anything to the file system.

So Path.ChangeExtension("blah.txt", "jpg") simply returns "blah.jpg" and does nothing else. To actually "rename" the file you need to use the File.Move method. Something like the following would work:

code:
string newFilename = Path.ChangeExtension(openShit.FileName, "lolextension");
File.move(openShit.FileName, newFilename);
However, I'm guessing that openShit is an open file. You'll probably have trouble moving a file that you have open, so you'll need to close it first. This is normal - you can't ever rename files that you have open.

As for doing it for every file in a directory, you can use the Directory.GetFiles method. This will return an array of strings, one for each file in the directory. You can then use foreach to iterate over these and rename each one. Something like this:

code:
string[] filenames = Directory.GetFiles("c:\Some\Path\");
foreach (string filename in filenames) {
    string newFilename = Path.ChangeExtension(filename, "newextension");
    File.move(filename, newFilename);
}

slovach
Oct 6, 2005
Lennie Fuckin' Briscoe
:aaa::aaa:

Thank you so much for the awesome explanations and help!

poopiehead
Oct 6, 2004

With C#, is there a way to listen on a port that's already being listened to by a windows service or something?

It's a long story, but I wrote a program to run on a VM to let it work as a proxy for the host machine to talk to the VPN. It works perfectly for a bunch of ports, but if I need to pass on RPC port(TCP 135) to a machine on the VPN, it won't let me listen because windows is already listening on the port.

Now is there a way to intercept those packets when they come in over a certain IP? So I want to be able to listen on 169.254.80.32:135 without otherwise interfering with windows. (that IP is a direct connection between the host and vm).

Is that possible?

EDIT: that's probably a security concern and impossible....... How about anyone know a way to switch the port before it gets there, either on the way out of the host or into the VM?

poopiehead fucked around with this message at 02:29 on Feb 23, 2007

slovach
Oct 6, 2005
Lennie Fuckin' Briscoe

slovach posted:

:aaa::aaa:

Thank you so much for the awesome explanations and help!

Oh Jesus Christ a slight typo ended up yielding a Battlefield 2142 folder (instead of just the movies) with just about everything renamed. :gonk:

I am not meant for this poo poo. Atleast it doesn't take long to reinstall. :lol: :(

e2: hurrrr.

e3: last stupid question.

i need to get this file, examplelol.exe and get it without that lol.
i am frying my brain trying to figure this one out

slovach fucked around with this message at 03:34 on Feb 23, 2007

csammis
Aug 26, 2003

Mental Institution

slovach posted:

i need to get this file, examplelol.exe and get it without that lol.
i am frying my brain trying to figure this one out

code:
string lol = "examplelol.exe";
int extindex = lol.LastIndexOf('.');
string nolol = lol.Substring(0, extindex - 3) + lol.Substring(extindex);
Look for the index of the extension (last period) and chop the string up from the beginning to extension - 3 (cutting out 'lol'), then tack on the last part of it.

slovach
Oct 6, 2005
Lennie Fuckin' Briscoe
perfect, thank you.

e2: i figured out out and i'm dumb as poo poo. :downs:

slovach fucked around with this message at 05:25 on Feb 23, 2007

MrBishop
Sep 30, 2006

I see what you did there...

Soiled Meat
Is it possible to inherit from a generic class to create a subclass that's only "semi-generic"? In other words, I want to limit my generic to working with a single interface or class (and its children). Specifically, what I want is to subclass BindingList<T> but limit it certain classes.

Code like this compiles:
code:
protected override void RemoveItem(
  int index
  )
{
  DataEntity  entity = this.Items[ index ] as DataEntity;

  if ( entity.Id > 0 )
      _deletedIds.Add( entity.Id );

  base.RemoveItem( index );
}
But it feels wrong, and I can see at some point in the future I'm going to accidentally try to use it with a class that won't work. What's the best way to handle this?

poopiehead
Oct 6, 2004

^^^^^Do you mean something like this:

code:
    class ColorList : System.Collections.Generic.List<System.Drawing.Color>
    {

    }
(This works)

Inquisitus
Aug 4, 2006

I have a large barge with a radio antenna on it.

MrBishop posted:

Is it possible to inherit from a generic class to create a subclass that's only "semi-generic"? In other words, I want to limit my generic to working with a single interface or class (and its children). Specifically, what I want is to subclass BindingList<T> but limit it certain classes.

Code like this compiles:
code:
protected override void RemoveItem(
  int index
  )
{
  DataEntity  entity = this.Items[ index ] as DataEntity;

  if ( entity.Id > 0 )
      _deletedIds.Add( entity.Id );

  base.RemoveItem( index );
}
But it feels wrong, and I can see at some point in the future I'm going to accidentally try to use it with a class that won't work. What's the best way to handle this?

I may well be misunderstanding what you're trying to do, but can't you just do this?
code:
public class SpecialisedBindingList<T> : BindingList<T> where T : SomeInterfaceOrClass
{
    // Stuff.
}
This would keep the sub class generic, but restrict the type to descendents of a certain class/interface.

wwb
Aug 17, 2004

I have some experience with using the where predicates. And, in most cases, you are probably better off just using (or inheriting) from a List<IWhatever> because that is what you actually want.

Well, unless you are doing funny things with abstract base classes.

poopiehead
Oct 6, 2004

wwb posted:

I have some experience with using the where predicates. And, in most cases, you are probably better off just using (or inheriting) from a List<IWhatever> because that is what you actually want.

But then you lose the advantage of the class being generic. If you don't want a generic class, then that makes sense. But, let's say you want a list that can be cloned. You have to make sure the entries are ICloneable, and then use the Clone() method of the items in your Clone() method. But if you just do CloneableList : List<ICloneable>, then you can't use it as a generic list. You have to a lot of casting and can't guarantee that everything in the list is the same type.

poopiehead fucked around with this message at 17:07 on Feb 23, 2007

MrBishop
Sep 30, 2006

I see what you did there...

Soiled Meat

Inquisitus posted:

I may well be misunderstanding what you're trying to do, but can't you just do this?
code:
public class SpecialisedBindingList<T> : BindingList<T> where T : SomeInterfaceOrClass
{
    // Stuff.
}
This would keep the sub class generic, but restrict the type to descendents of a certain class/interface.

That's exactly what I was trying to say, thank you. I remember now seeing something like this a couple pages back, but didn't really understand the application of it. Now I get it (I think) :awesome:

wwb posted:

Well, unless you are doing funny things with abstract base classes.
^
| Yes, this.

Darn Cotts
Mar 12, 2004

\Job"ber*nowl`\, n. [OE. jobbernoule, fr. jobarde a stupid fellow; cf. E. noll.] A blockhead. [Colloq. & Obs.]
I'm creating a custom column/cell type for a DataGridView. It's based on a textbox but also has autocomplete.

My question is: how do I update the value of the Cell object when the value of the textbox control changes? I can't subscribe to the TextChanged event in InitializeEditingControl because that gets called every time the cell is entered, so I would end up subscribing to the same event many times.

There doesn't seem to be any kind of event handler in DataGridViewCell that I can override that will be called when the cell comes out of edit mode. If I had something like this then I could just do something like Value = editingControl.Text.

Any ideas?

Edit: Never mind, I got it. Wasn't calling EditingControlDataGridView.NotifyCurrentCellDirty(true); :downs:

Darn Cotts fucked around with this message at 22:14 on Feb 24, 2007

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Two Questions.

First how can I pass a property by reference? I've searched a few sites and the answer seems to be no, but then I read some stuff on delegates and I thought that those might be able to help me. I read this blog and thought I might be able to implement it, but I get some error about get_Property not being able to be referenced directly.

I have a class class called Atributes which has a few simple properties like this:
code:
public int STR
        {
            get
            {
                return strength;
            }
            set
            {
                strength = value;
            }
        }
Then in my user control I have a button that affects each property. It basically just increments the Property by one each time I push the button. Right now it works because I copied and pasted the same code for each event handler, but I thought the best way to do it was to simply call a method from each event handler which would pass the property I need to handle by reference. After reading around I found that if have methods like getStrength and setStrength then I could use two delgates to handle it.
code:
delegate int Getter(); 
delegate void Setter(int val);
But this feels like going back to Java and it ruins the whole purpose of using properties in the first place. So my question is, what's the correct way to do it?



Second question.
I want the user to be able to drag a textfield around the form and when it's released to swap values with the textfield underneath it. In Java I used a MouseInputListener which had the methods for mousePressed, mouseDragged, and mouseReleased. I'm trying it with the MouseClick and MouseMoved but the text field keeps flickering between 0,0 and the mouse cursor.
code:
private void strField_MouseDown(object sender, MouseEventArgs e)
        {
            originalLoc = ((TextBox)sender).Location;
            mouseDown = true;
        }

        private void strField_MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseDown)
            {
                Point p = new Point(e.X, e.Y);
                ((TextBox)sender).Location = p;
            }
        }

        private void strField_MouseUp(object sender, MouseEventArgs e)
        {
            ((TextBox)sender).Location = originalLoc;
            mouseDown = false;
        }

Victor
Jun 18, 2004
Hiro2k, did you see this page about using reflection to enable you to pass properties by reference? The reason C# won't let you pass properties by reference is that it can't always determine what ref parameters will be properties and generate getter/setter versions of every method call that might have to accept properties.

If your class will never need anything more than the simplest get/set, you might just use public fields. Yes, people always say that public fields are anathema, but they're really no different from naïve properties. Now, a problem would occur if you were to start out with fields and then switch to properties.

Adbot
ADBOT LOVES YOU

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I forgot to mention that I did read that page, but I didn't understand the syntax to implement it in my own code. :(

I guess you're right about the public fields, properties are just complicating my design.

  • Locked thread