473,618 Members | 3,170 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trouble with DataGrid and adding Rows

Hey guys,

I have a DataGrid and DataTable field in my class :

private ImageDataGrid dataGrid1; //ImageDataGrid extends dataGrid and just
overides OnMouseDown

private DataTable dt = new DataTable("MyTa ble");

In the classes constructor, after InitializeCompo nent() I call the following
method:

private void CreateMyDataGri d()
{
dt.Columns.Add( new DataColumn("Fro m Cell"));
dt.Columns.Add( new DataColumn("Go" ,typeof(int)));
dt.Columns.Add( new DataColumn("To Cell"));

//Set some styles, etc.

dataGrid1.DataS ource = dt;
dataGrid1.Selec t(); //If I comment this line out everything works OK
}

Now, in some other methods that are called later on I try the following:

DataRow _moveRow = dt.NewRow();
_moveRow[0] = _currentCell.In dex;
_moveRow[1] = 0;
_moveRow[2] = _nextCell.Index ;
dt.Rows.Add(_mo veRow);

When that code runs I get the following error:

A first chance exception of type 'System.IndexOu tOfRangeExcepti on' occurred
in system.windows. forms.dll

Additional information: Index was outside the bounds of the array.

However, if I comment out the last line in CreateMyDataGri d(), the Selecet
line, everything works fine?

Any ideas why this is so?

Mar 2 '06 #1
2 3555
Flack,

I tried out your code. I added a datagrid to a blank form. I added the private dt and copied your
given code for CreateMyDataGri d() and called it after InitializeCompo nent. I didn't get any
exceptions. I even tried dataGrid1.Selec t(0) and it selected the first row, which had nothing in
it.

If you comment out your style sets in the createmydatagri d() function does it work?

---Tome

On Thu, 2 Mar 2006 13:58:31 -0800, "Flack" <Fl***@discussi ons.microsoft.c om> wrote:
Hey guys,

I have a DataGrid and DataTable field in my class :

private ImageDataGrid dataGrid1; //ImageDataGrid extends dataGrid and just
overides OnMouseDown

private DataTable dt = new DataTable("MyTa ble");

In the classes constructor, after InitializeCompo nent() I call the following
method:

private void CreateMyDataGri d()
{
dt.Columns.Add( new DataColumn("Fro m Cell"));
dt.Columns.Add( new DataColumn("Go" ,typeof(int)));
dt.Columns.Add( new DataColumn("To Cell"));

//Set some styles, etc.

dataGrid1.DataS ource = dt;
dataGrid1.Selec t(); //If I comment this line out everything works OK
}

Now, in some other methods that are called later on I try the following:

DataRow _moveRow = dt.NewRow();
_moveRow[0] = _currentCell.In dex;
_moveRow[1] = 0;
_moveRow[2] = _nextCell.Index ;
dt.Rows.Add(_m oveRow);

When that code runs I get the following error:

A first chance exception of type 'System.IndexOu tOfRangeExcepti on' occurred
in system.windows. forms.dll

Additional information: Index was outside the bounds of the array.

However, if I comment out the last line in CreateMyDataGri d(), the Selecet
line, everything works fine?

Any ideas why this is so?

Mar 3 '06 #2
Thanks for the help Tome.

I figured out what was causing the exception to be thrown. If you set the
ReadOnly property of the DataGrid to true:

this.dataGrid1. ReadOnly = true;

then an IndexOutOfRange Exception will be thrown when you try to add a row.
The thing is, it will only be thrown when I have the following line:

dataGrid1.Selec t();

So, in summary, I have two options. I can not select the datagrid before
adding new rows or I can leave readonly as true and set it to false before I
display the grid.

Can anyone tell me why this behavior is so?

Below I pasted a small example that shows what I found

=============== =============== =============== ==
using System;
using System.Data;
using System.Componen tModel;
using System.Windows. Forms;

namespace GridTest
{
public class Test : System.Windows. Forms.Form
{
DataTable dt = new DataTable();
private System.Componen tModel.Containe r components = null;
private System.Windows. Forms.DataGrid dataGrid1;

public Test()
{
InitializeCompo nent();
CreateMyDataGri d();
AddRows();
}

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Disp ose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.dataGrid1 = new System.Windows. Forms.DataGrid( );

((System.Compon entModel.ISuppo rtInitialize)(t his.dataGrid1)) .BeginInit();
this.SuspendLay out();
//
// dataGrid1
//
this.dataGrid1. AllowSorting = false;
this.dataGrid1. BorderStyle = System.Windows. Forms.BorderSty le.None;
this.dataGrid1. DataMember = "";
this.dataGrid1. HeaderForeColor =
System.Drawing. SystemColors.Co ntrolText;
this.dataGrid1. Location = new System.Drawing. Point(8, 8);
this.dataGrid1. Name = "dataGrid1" ;
this.dataGrid1. ReadOnly = true;
this.dataGrid1. Size = new System.Drawing. Size(224, 160);
this.dataGrid1. TabIndex = 0;
//
// Test
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
this.BackColor = System.Drawing. Color.White;
this.ClientSize = new System.Drawing. Size(242, 176);
this.Controls.A ddRange(new System.Windows. Forms.Control[] {

this.dataGrid1} );
this.FormBorder Style = System.Windows. Forms.FormBorde rStyle.FixedSin gle;
this.Name = "Test";
this.Text = "Test";
((System.Compon entModel.ISuppo rtInitialize)(t his.dataGrid1)) .EndInit();
this.ResumeLayo ut(false);

}
#endregion

[STAThread]
static void Main()
{
Application.Run (new Test());
}

private void CreateMyDataGri d()
{
dt.Columns.Add( new DataColumn("Fro m Cell"));
dt.Columns.Add( new DataColumn("Go" ,typeof(string) ));
dt.Columns.Add( new DataColumn("To Cell"));

dataGrid1.DataS ource = dt;

//If the following line is not commented out and dataGrid1.ReadO nly
//is set to true, IndexOutOfBound sExceptions will be thrown when you
//try to add new rows to the grid. If you need this line and don't
want the
//exceptions to be thrown, set dataGrid1.ReadO nly to false
dataGrid1.Selec t();
}

private void AddRows()
{
DataRow dr = dt.NewRow();
dr[0] = 0;
dr[1] = 1;
dr[2] = 2;
dt.Rows.Add(dr) ; //Exception thrown here

/*
dt.BeginLoadDat a();
DataRow _moveRow = dt.NewRow();
_moveRow[0] = 0;
_moveRow[1] = 1;
_moveRow[2] = 2;
dt.Rows.Add(_mo veRow);
dt.EndLoadData( ); //Exception thrown here
*/
}
}
}
=============== =============== =============== ==

"Tome" wrote:
Flack,

I tried out your code. I added a datagrid to a blank form. I added the private dt and copied your
given code for CreateMyDataGri d() and called it after InitializeCompo nent. I didn't get any
exceptions. I even tried dataGrid1.Selec t(0) and it selected the first row, which had nothing in
it.

If you comment out your style sets in the createmydatagri d() function does it work?

---Tome

On Thu, 2 Mar 2006 13:58:31 -0800, "Flack" <Fl***@discussi ons.microsoft.c om> wrote:
Hey guys,

I have a DataGrid and DataTable field in my class :

private ImageDataGrid dataGrid1; //ImageDataGrid extends dataGrid and just
overides OnMouseDown

private DataTable dt = new DataTable("MyTa ble");

In the classes constructor, after InitializeCompo nent() I call the following
method:

private void CreateMyDataGri d()
{
dt.Columns.Add( new DataColumn("Fro m Cell"));
dt.Columns.Add( new DataColumn("Go" ,typeof(int)));
dt.Columns.Add( new DataColumn("To Cell"));

//Set some styles, etc.

dataGrid1.DataS ource = dt;
dataGrid1.Selec t(); //If I comment this line out everything works OK
}

Now, in some other methods that are called later on I try the following:

DataRow _moveRow = dt.NewRow();
_moveRow[0] = _currentCell.In dex;
_moveRow[1] = 0;
_moveRow[2] = _nextCell.Index ;
dt.Rows.Add(_m oveRow);

When that code runs I get the following error:

A first chance exception of type 'System.IndexOu tOfRangeExcepti on' occurred
in system.windows. forms.dll

Additional information: Index was outside the bounds of the array.

However, if I comment out the last line in CreateMyDataGri d(), the Selecet
line, everything works fine?

Any ideas why this is so?

Mar 3 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3626
by: Clayton Hamilton | last post by:
I have a DataGrid on a webform bound to a Datasource and can successfully use <ItemTemplate> to create edit/update/cancel functionality for user maintenance of data. I use separate logic to delete a row. Everything works just fine. BUT I would like to add a button to (for example) the DataGrid header, which when pressed will add a new row to the datagrid. This should then allow the user to enter information into text boxes (in some...
0
2465
by: sameer mowade via .NET 247 | last post by:
Hello All, I have problem while dynamically removing row from the Datagrid which i have added dynamically as shown in the following code snippet. The problem is that while removing dynamically added row it also removes the row at the end along with the added row. Plz tell me if, I am missing any thing. Code </asp:datagrid>
3
4868
by: Jim Heavey | last post by:
Trying to figure out the technique which should be used to add rows to a datagrid. I am thinking that I would want an "Add" button on the footer, but I am not quite sure how to do that. Is that the best method? Do you have a sample of how to do this?
1
3272
by: Andrew | last post by:
Hey all, I am very new to ASP.Net (and .Net in general), but that isn't stopping the boss from wanting to begin new projects in it. This latest project has me kinda stumped and after a couple days of struggling, I figure asking you all (the experts) will keep me from going down some dark and dangerous road. The project I have is a fairly simple one, in theory anyway. The gist is to create a page where the user enters an IDNumber,...
2
1958
by: Praveen Balanagendra via .NET 247 | last post by:
here is the source code private void AddRow() { TableCell tc = new TableCell(); tc.Controls.Add(new LiteralControl("NewRow")); DataGridItem di = new DataGridItem(DataGrid1.Items.Count+1,DataGrid1.Items.Count+1,ListItemType.Item); di.Cells.Add(tc); di.Cells.Add(tc1);
16
1347
by: scorpion53061 | last post by:
Well as some of you know I was using a tab control for a project I was building for my boss. Today he tells me that he wants: When he switches tabs to be able to switch back and see whatever it was he was doing on the other tab. That may not sound like a big thing but I used the same controls for each tab and then manually cleared the page so he didnt see the same in another
10
8111
by: Aaron Smith | last post by:
If I have a datagrid and the bound data file only have 4 rows in it, the grid will show the 4 rows. However, there is blank space below that until it reaches the bottom of the grid. Is there a way to have a fixed number of rows regardless of what data is in the bound table? Thanks, Aaron -- --- Aaron Smith
13
2443
by: shookim | last post by:
I don't care how one suggests I do it, but I've been searching for days on how to implement this concept. I'm trying to use some kind of grid control (doesn't have to be a grid control, whatever works best) to display a dropdown menu of fields populated from table tblInvoiceData. This control also includes a textbox which the user can input a value. These two columns are side by side and not in a vertical layout. The user then clicks on...
12
6205
by: JMO | last post by:
I can import a csv file with no problem. I can also add columns to the datagrid upon import. I want to be able to start importing at the 3rd row. This will pick up the headers necessary for the datagrid. Once I can get to that point I need some way to be able to add new data only to the new columns that were added. Here is some of my code: //Function For Importing Data From CSV File public DataSet ConnectCSV(string filetable)
0
8150
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8650
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8593
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8303
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8453
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4064
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4147
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1760
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1455
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.