473,748 Members | 2,259 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 3566
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
3639
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
2473
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
4880
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
3293
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
1968
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
1363
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
8130
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
2456
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
6221
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
8980
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8821
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
9523
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
9231
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
8235
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6070
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4862
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3297
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.