|
Bound grids cannot have rows arbitrarily deleted from or added to them. You have to delete/add them from/to the source they are bound to.
You have a choice. Bind the grid and gain speed or don't bind the grid and loose the speed. There is no such thing as "bind and forget" the way you describe. Once you unbind the grid, it forgets about all the data that came across that binding.
I hear you asking "but I've seen rows being added to bound grids?". They're not adding the row to the grid. The grid is editing a blank row that was added to the source by the grid through a BindingNavigator.
The fastest your going to get is a databound grid that has Virtual mode turned on.
There is no such as Virtual mode when manually adding rows to an unbound grid. It only works with bound sources.
|
|
|
|
|
Appreciate your input . . . I understand. I also understand I may be in over my head. I'm not a programmer by profession . . I have written many programs related to my work as CPA tax planner & investment advisor. Of course, I would like to have a databound grid.
I have not bound anything before. Having a hard time getting head around it . . may have to start from scratch instead of trying to edit what I have. Hard to decide since what I have (unbound)works but is slow.
Basically, I have a master csv file that takes another csv file (generatded by a commercial tax program) and updates my master csv file. One question . . . my unbound program adds any new row (from small csv file) to master csv file. My changed program that now has a DGV bound to a datatable. Where I have added a row to my DGV . . . do I now change the coding to add a row to the datatable?
Dave, thanks again for your input. If you think I need to start over from scratch, can you suggest any tutorials that will help me get the concept (binding DGV - datatable in my head)?
|
|
|
|
|
Yes, you would have to add the row to the DataTable, then refresh the grid.
I don't have any tutorials on the DGV, but Google does. "datagridview tutorial[^]"
|
|
|
|
|
The other solution is to read the CSV using an existing reader. This would probably do it: A Fast CSV Reader[^]
(it's certainly a better approach than reading the file as lines, since CSV files can contain newlines as part of the text if it's within an open set of quotes)
Then it's pretty simple:
using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(@"D:\Temp\Data.csv"), true))
{
dgvData.DataSource = csv;
}
That loads a couple of thousand rows of 22 columns in a second or so.
Never underestimate the power of stupid things in large numbers
--- Serious Sam
|
|
|
|
|
As others have already said, you'd like to synchronize with the CSV, not use it directly as your datasource. Also, binding takes some time that can be avoided by putting the datagridview in virtual mode[^].
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
I´m working on a game using XNA and C#.
It´s a kind of two (or more) uboat-game where you place an uboat somewhere and then the opponent are going to find the uboat.
The game is maybe going to be an online-game or maybe between two computers.
I also need chat but that can be a separat program.
Anyway, right now I have a form which contains a picturebox where the actual game are.
I have a button in the form and would like to be able to affect the sprites using that button.
Right now the uboat is placed in the upper left corner. Then I want to move the uboat to destination of my choice.
However I can't affect hte uboat (enemy) with the button once the game has started.
Is it even possible?
I'm quite new to XNA and I have used this a tutorial:
Here´s my code:
Program:
using System;
namespace WindowsGame1
{
#if WINDOWS || XBOX
static class Program
{
static void Main(string[] args)
{
Form1 form = new Form1();
form.Show();
Game1 game = new Game1(form.getDrawSurface());
game.Run();
}
}
#endif
}
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Game1 game1 = new Game1();
int counter = 1;
public IntPtr getDrawSurface()
{
return pctSurface.Handle;
}
private void button1_Click(object sender, EventArgs e)
{
game1.buttonHit(350, 450, true);
counter++;
label1.Text = counter.ToString();
}
}
}
Game1
public class Game1 : Microsoft.Xna.Framework.Game
{
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private Player player;
private Player player2;
private Enemy enemy;
private Texture2D backgroundTexture;
int screenWidth;
int screenHeight;
GraphicsDevice device;
Rectangle textBox;
private IntPtr drawSurface;
int x;
int y;
bool isActive = false;
public void buttonHit(int X, int Y, bool IsActive)
{
x = X;
y = Y;
isActive = IsActive;
}
public Game1(IntPtr drawSurface)
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
this.drawSurface = drawSurface;
graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
System.Windows.Forms.Control.FromHandle((this.Window.Handle)).VisibleChanged += new EventHandler(Game1_VisibleChanged);
}
public Game1()
{
}
void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
{
e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle =
drawSurface;
}
private void Game1_VisibleChanged(object sender, EventArgs e)
{
if (System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible == true)
System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible = false;
}
protected override void Initialize()
{
graphics.PreferredBackBufferWidth = 1500;
graphics.PreferredBackBufferHeight = 800;
graphics.IsFullScreen = false;
graphics.ApplyChanges();
Window.Title = "Enigma";
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
device = graphics.GraphicsDevice;
enemy = new Enemy(Content.Load<Texture2D>("images/enemies/uboat2_small"), 0, 0);
player = new Player(Content.Load<Texture2D>("images/player/Ship"), 300, 400);
if (isActive == true)
player2 = new Player(Content.Load<Texture2D>("images/player/Ship"), x, y);
backgroundTexture = Content.Load<Texture2D>("images/Background/Atlanten3_1");
screenWidth = device.PresentationParameters.BackBufferWidth;
screenHeight = device.PresentationParameters.BackBufferHeight;
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
player.update(Window);
if (isActive == true)
player2.update(Window);
enemy.Update2(Window, x, y);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
DrawScenery();
player.Draw(spriteBatch);
if (isActive == true)
player2.Draw(spriteBatch);
enemy.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
private void DrawScenery()
{
Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);
spriteBatch.Draw(backgroundTexture, screenRectangle, Color.White);
}
}
}
GameObject-class: (base-class):
public class GameObject
{
public Texture2D texture; // Rymdskeppets textur (Från Player-klassen)
public Vector2 ship_vector; // Rymnskeppets koordinater (Från Player-klassen)
public GameObject(Texture2D texture, float X, float Y) //Delvis från Player-klassen
{
this.texture = texture;
this.ship_vector.X = X;
this.ship_vector.Y = Y;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, ship_vector, Color.White);
}
public float X //Egenskap för att komma åt skeppets vågräta position
{
get
{
return ship_vector.X;
}
set
{
ship_vector.X = value;
}
}
public float Y //Egenskap för att komma åt skeppets lodräta position
{
get
{
return ship_vector.Y;
}
set
{
ship_vector.Y = value;
}
}
public float Width //Egenskap för att komma åt bredd på ship_texture
{
get
{
return texture.Width;
}
}
public float Height //Egenskap för att komma åt höjd på ship_texture
{
get
{
return texture.Height;
}
}
}
}
MovingObject-class:
public abstract class MovingObject : GameObject
{
public Vector2 ship_speed;
public MovingObject(Texture2D texture, float X, float Y, float speedX, float speedY) : base(texture, X, Y)
{
this.ship_speed.X = speedX;
this.ship_speed.Y = speedY;
}
}
}
Player-class:
public class Player : MovingObject
{
bool isAlive = true;
public Player(Texture2D texture, float X, float Y) : base(texture, X, Y, 0.05f, 0.05f)
{
}
public void update(GameWindow window)
{
KeyboardState keyboardState = Keyboard.GetState();
if (ship_vector.X <= window.ClientBounds.Width - texture.Width && ship_vector.X >= 0)
if (keyboardState.IsKeyDown(Keys.NumPad5))
ship_vector.X += 1;
ship_vector.X -= ship_speed.X;
ship_vector.Y -= ship_speed.Y;
if (ship_vector.X > window.ClientBounds.Width - texture.Width || ship_vector.X < 0)
ship_speed.X *= -1;
if (ship_vector.Y > window.ClientBounds.Height)
isAlive = false;
}
public bool IsAlive
{
get { return isAlive; }
set { isAlive = value; }
}
}
}
Enemy-class:
<pre lang="c#">
public class Enemy : MovingObject
{
bool isAlive = true;
public Enemy(Texture2D texture, float X, float Y) : base(texture, X, Y, 0.05f, 0.05f)
{
}
public void Update(GameWindow window)
{
ship_vector.X += ship_speed.X;
ship_vector.Y += ship_speed.Y;
if (ship_vector.X > window.ClientBounds.Width - texture.Width || ship_vector.X < 0)
ship_speed.X *= -1;
if (ship_vector.Y > window.ClientBounds.Height)
isAlive = false;
}
public void Update2(GameWindow window, int x, int y)
{
ship_vector.X = x;
ship_vector.Y = y;
}
public bool IsAlive
{
get { return isAlive; }
set { isAlive = value; }
}
}
}
|
|
|
|
|
Change Form1 to this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Game1 game1;
int counter = 1;
public Game1 Game { get { return game1; } set { game1 = value; } }
public IntPtr getDrawSurface()
{
return pctSurface.Handle;
}
private void button1_Click(object sender, EventArgs e)
{
game1.buttonHit(350, 450, true);
counter++;
label1.Text = counter.ToString();
}
}
}
Then change Program.cs to:
static void Main(string[] args)
{
Form1 form = new Form1();
Game1 game = new Game1(form.getDrawSurface());
form.Game = game;
form.Show();
game.Run();
}
Can you see why? You create a game in the Program.cs file, and you create another one in the Form1.cs file. Even though the names are the same, they are not the same game, essentially you have two Game1 objects created. The one you are talking to in Form1 is not the one you created when the program starts. Somehow you need to give Form1 a reference to the game you created. This is one way, there are others, for example, you could also do this:
Form1.cs:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int counter = 1;
public IntPtr getDrawSurface()
{
return pctSurface.Handle;
}
private void button1_Click(object sender, EventArgs e)
{
Program.game.buttonHit(350, 450, true);
counter++;
label1.Text = counter.ToString();
}
}
}
Then change Program.cs to:
static Game1 game;
static void Main(string[] args)
{
Form1 form = new Form1();
form.Show();
game = new Game1(form.getDrawSurface());
game.Run();
}
There are many ways to skin a cat, but these are two of the easiest.
|
|
|
|
|
Great, thanks!
The first method works fine but can you explain what you do in the second?
|
|
|
|
|
Program is a static class, meaning it is available to the entire application. By adding a static variable inside this class, you also make it available to the entire application. You initialize the game, then create the form. The form, or any other form for that matter can access Program.Game to get an instance of the running game and manipulate it.
Its the same as the first one, except it changes where the reference to the game is contained.
|
|
|
|
|
|
Hi again. I can now change values in the winforms that affects the game, so thank you very much for that.
How can I do the opposite (if possible) affect the winform from my game. Let say I want to make a button enabled or disabled when something in my game happends.
|
|
|
|
|
how i can auto searching devices and sending file with bluetooth using 32feet ,C#,WPf.
please take example for me.
tanks.
|
|
|
|
|
|
Hi
I am trying to create a TCP Socket Listener that installes as a windows service. I have created a console applications that works file, see code. But after reading pages and pages on how to create a window service I am stuck. It is how to handle start and stop of the service that is my biggest problem. Does any one have any ideas/tips?
Regards
Tobben
public class SynchronousSocketListener
{
public static string data = null;
public static void StartListening()
{
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("=)") > -1)
{
System.Diagnostics.Process.Start(@"C:\Windows\System32\Notepad.exe");
break;
}
if (data.IndexOf("=(") > -1)
{
System.Diagnostics.Process.Start(@"C:\Windows\System32\cmd.exe");
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
|
|
|
|
|
I'm assuming, since you posted the code that works and not the code you are having problems with, is that you are calling StartListening in the OnStart method of the service.
Here is a Walkthrough for creating a Windows Service[^]
Note what it says in the note under the OnStart method:
Quote: A service application is designed to be long running. Therefore, it usually polls or monitors something in the system. The monitoring is set up in the OnStart method. However, OnStart does not actually do the monitoring. The OnStart method must return to the operating system after the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.
Your code does exactly that, it loops forever (while(true) ).
So, how would you take care of that? Well you can either use the asynchronous methods instead of the synchronous ones, see Socket.BeginReceive[^] or you can create a new thread (I'd use BackgroundWorker[^]).
Remember to keep a way to stop your service, so if you use the asynchronous socket methods you will have to be able to cancel the operation, or if you use background worker you will need to have some kind of flag to exit your function.
|
|
|
|
|
Hi I am using System.Timer class in my xaml.cs class.
my MainWindow Constructor looks like as below
public MainWindow()
{
Timer timer = new Timer(3000);
InitializeComponent();
timer.Interval = 3.0;
timer.Elapsed += new System.Timers.ElapsedEventHandler(LoadObjectValue);
}
OnButton Click i am starting the Timer
private void Button_Click(object sender, RoutedEventArgs e)
{
timer.Enabled=true;
}
My LoadObjectValue method looks like below
void LoadObjectValue(object sender, ElapsedEventArgs e)
{
dataGrid.ItemsSource = DeviceObjectVM.DeviceObjectCollection; //ObservableCollection
}
But when i am executing i am getting Exception: "Calling Thread can not access the because it owns by the other thread". It looks like my dataGrid is owns by the UI Thread and my Timer is running on the other thread. Which does not have access to dataGrid. How Can i set ItemSource of datagrid using Timer.
Please Help.
|
|
|
|
|
You can use the Dispatcher to Invoke the ItemsSource binding.
|
|
|
|
|
Your timer setup code is a bit messed up. You first create a new Timer with an interval of 3 seconds, then a couple of lines later you change the interval to 3 milliseconds. I don't think that's correct as you'd be forcing the grid to rebind and probably redraw itself nearly continuously.
|
|
|
|
|
for a quick workaround use CheckForIllegalCrossThreadCalls=false on your control/form.
|
|
|
|
|
Thanks Guys for your quick help.
The problem is solved using DispatcherTimer.
Below is the code: of MainWindow.xaml.cs class
public partial class MainWindow : Window
{
private DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Window1_Loaded);
}
void Window1_Loaded(object sender, RoutedEventArgs e)
{
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(3);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
DeviceObjectVM deviceObjectVM = new DeviceObjectVM();
dgDeviceValue3.ItemsSource = deviceObjectVM.DeviceObjectCollection;
}
}
Where DeviceObjectVM is my viewmodel class and dgDeviceValue3 is my datagrid. which is bound to the vm's observablecollection.
Using DispatcherTimer i was able to update my UI Control dgDeviceValue3.
|
|
|
|
|
Hi
I have a rather large table in sql server 2012 which I am pulling into a C# winform app datagridview. I am having problem with getting the navigator to work.
Background
I am only using a single table
I am using the sortable example here
<a href="http://www.codeproject.com/Articles/31418/Implementing-a-Sortable-BindingList-Very-Very-Quic">Implementing a Sortable BindingList Very, Very Quickly</a>
Here is my linq
dbcontext = new LOBappsContext();
dbcontext.myTable.Load();
this.myTableBindingSource.DataSource = dbcontext.myTable.Local.ToBindingList();
//
Cursor.Current = Cursors.WaitCursor;
strSubvertical = this.cboSubverticalOnly.SelectedItem.ToString();
var theGridData = new List<LOBapp.myTable>();
theGridData = (
from g in dbcontext.myTable
where g.System_and_Projects == strSubvertical
orderby g.Project_Name
select g
).ToList();
var sortableCollection = new customSortableBindingList<myTable>(theGridData);
BindingSource bs = new BindingSource();
bs.DataSource = sortableCollection;
this.myTableBindingNavigator.BindingSource = bs;
this.myTableDataGridView1.DataSource = sortableCollection;
myTableBindingNavigator.Update();
myTableBindingNavigator.Refresh();
hideGridColumns();
Cursor.Current = Cursors.Arrow;
The problem
When I click on the left and right arrows (any arrow actually), the little triangle next to the selected row does not move to next row.
I would appreciate any help with this.
Thanks
|
|
|
|
|
Hi,
I think it's just a simple error in the wiring. Link the binding source to the datagridview and it should work correctly.
BindingSource bs = new BindingSource();
bs.DataSource = sortableCollection;
this.myTableBindingNavigator.BindingSource = bs;
this.myTableDataGridView1.DataSource = sortableCollection
this.myTableDataGridView1.DataSource = bs;
Alan.
|
|
|
|
|
|
Did you get a code signing certificate from a known certificate authority available on the web??
|
|
|
|
|
|