System.ArgumentOutOfRange Exception: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index' [duplicate] - c#

I'm trying to add data as one by one row to a datagridview here is my code and it says:
"Index was out of range. Must be non-negative and less than the size of the collection
parameter name:index"
What does this mean? What is the problem in my code?
String Sqlstr2 = "select ItemName from Item where ItemID = '" + tbItemID.Text + "'";
db.DataRead(Sqlstr2);
string ItemName = db.dr["ItemName"].ToString();
DataGridView dataGridView1 = new DataGridView();
dataGridView1.Columns[0].Name = "ItemID";
dataGridView1.Columns[1].Name = "ItemName";
dataGridView1.Columns[2].Name = "Qty";
dataGridView1.Columns[3].Name = "UnitPrice";
dataGridView1.Columns[4].Name = "Amount";
string firstColum = tbItemID.Text;
string secondColum = ItemName;
string thirdColum = tbQuantity.Text;
string fourthColum = Convert.ToString(UnitPrice);
string fifthColum = Convert.ToString(sum);
string[] row = new string[]{ firstColum, secondColum, thirdColum, fourthColum, fifthColum };
dataGridView1.Rows.Add(row);

The error says "The index is out of range". That means you were trying to index an object with a value that was not valid. If you have two books, and I ask you to give me your third book, you will look at me funny. This is the computer looking at you funny. You said - "create a collection". So it did. But initially the collection is empty: not only is there nothing in it - it has no space to hold anything. "It has no hands".
Then you said "the first element of the collection is now 'ItemID'". And the computer says "I never was asked to create space for a 'first item'." I have no hands to hold this item you are giving me.
In terms of your code, you created a view, but never specified the size. You need a
dataGridView1.ColumnCount = 5;
Before trying to access any columns. Modify
DataGridView dataGridView1 = new DataGridView();
dataGridView1.Columns[0].Name = "ItemID";
to
DataGridView dataGridView1 = new DataGridView();
dataGridView1.ColumnCount = 5;
dataGridView1.Columns[0].Name = "ItemID";
See http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columncount.aspx

You're not adding columns to your DataGridView
DataGridView dataGridView1 = new DataGridView();//Create new grid
dataGridView1.Columns[0].Name = "ItemID";// refer to column which is not there
Is it clear now why you get an exception?
Add this line before you use columns to fix the error
dataGridView1.ColumnCount = 5;

what this means ? is there any problem in my code
It means that you are accessing a location or index which is not present in collection.
To find this, Make sure your Gridview has 5 columns as you are using it's 5th column by this line
dataGridView1.Columns[4].Name = "Amount";
Here is the image which shows the elements of an array. So if your gridview has less column then the (index + 1) by which you are accessing it, then this exception arises.

dataGridView1.Columns is probably of a length less than 5. Accessing dataGridView1.Columns[4] then will be outside the list.

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.
int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();
Hope this answers the question.

Related

DataGridViewComboBoxColumn get value from other column

I pull the data from sql database and fill datagridView1 with it:
dataGridView1.DataSource = bsour;
User will be able to edit value in 1 column, but possible values for that column are only Null, 0, 1 or 2 so to prevent from inputting incorrect value i decided to do a ComboBoxColumn:
DataGridViewComboBoxColumn col1 = new DataGridViewComboBoxColumn();
col1.Name = "il_normal_combo";
col1.HeaderText = "Normal";
col1.Items.Add("");
col1.Items.Add("0");
col1.Items.Add("1");
col1.Items.Add("2");
dataGridView1.Columns.Insert(5, col1);
The other now unnecessary column I'll hide with .Visible = false;
I want the ComboBoxColumn to display database values from that other column that will be hidden and i can't seem to get it to work.
What i have tried:
col1.ValueMember = "il_normal";
col1.DisplayMember = "il_normal";
Those don't work but without error message.
This doesn't work and produces error "Values are incorrect"
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[5].Value = dataGridView1.Rows[i].Cells[7].Value;
}
I found similar question here
Change DataGridViewColumn to DataGridViewComboBoxColumn in bound DataGridView
but solution in that post didn't work for me. In ComboBoxColumn instead of number, I got System.Data.DataRows.(something) so i deduced that it doesn't know which column to use (even though there was only one in DataSource) so i added
col1.DisplayMember = "number";
And then it worked :-)

GridView Remove first Row

I am Producing a score card for a pool league and have 2 result set's. The first results set 'ds' is the frames & the second, 'dsres' is the result of the match.
I am outputting these results to a grid view like so:
GridView gv = new GridView();
gv.ID = "_gridview" + i;
gv.DataSource = ds;
gv.DataBind();
gv.CssClass = "Grid";
GridView gvres = new GridView();
gvres.ID = "_gridviewres" + i;
gvres.DataSource = dsres;
gvres.DataBind();
gvres.CssClass = "Grid";
ph.Controls.Add(gv);
ph.Controls.Add(gvres);
ph.Controls.Add(new LiteralControl("</br>"));
Both Grid views are added to asp:PlaceHolder 'ph' which produces two tables:
I would like to hide the second tables Header row.
I have tried rows[0].Visible = false; but this returns a out of bounds exception.
Please could someone tell me where I am going wrong. Thank you.
You can apply the attribute to disable header like this. Make sure to put it before the .DataBind();
gvres.ShowHeader = false;

Manually added column not showing in windows form DataGridView

I have a DataGridView (CurrentLine) with a DataSet source table. I have added a combobox column with a different datasource, which works fine. The I tried adding another column, but the DataGridView refuses to show it!
I have tried adding a regular column via DataGridViewColumn and via DataGridViewTextBoxColumn (as I basically need a regular column with nothing but numbers).
I tried setting the visibility property to true.
Nothing seems to work and I have no idea why.
da1.Fill(Orders, Order);
da2.Fill(Orders, Lines);
da3.Fill(Orders, Products);
CurrentLine.DataSource = Orders.Tables[Lines];
CurrentLine.Columns["fkPrdctnum"].Visible = false;
CurrentLine.Columns["linenum"].Width = 60;
CurrentLine.Columns["linenum"].HeaderText = "Number";
CurrentLine.Columns["linenum"].ReadOnly = true;
CurrentLine.Columns["lineQuantity"].HeaderText = "Quantity";
CurrentLine.Columns["lineQuantity"].Width = 70;
CurrentLine.Columns["linePrdctPrice"].HeaderText = "Unit Price";
CurrentLine.Columns["linePrdctPrice"].Width = 100;
DataGridViewComboBoxColumn prod = new DataGridViewComboBoxColumn();
prod.DataSource = Orders.Tables[Products];
prod.DisplayMember = "prdctName";
prod.ValueMember = "prdctNum";
prod.HeaderText = "Product";
CurrentLine.Columns.Add(prod);
for (int i=0; i<CurrentLine.Rows.Count; i++)
{
int product = Convert.ToInt32(Orders.Tables[Lines].Rows[i][1]); //This loop sets the values of the combobox according to the order lines in the orderline table in the dataset.
CurrentLine.Rows[i].Cells[4].Value = product;
}
DataGridViewColumn LinePrice = new DataGridViewColumn();
LinePrice.HeaderText = "Line Price";
LinePrice.Width = 100;
LinePrice.ReadOnly = true;
CurrentLine.Columns.Add(LinePrice);
Just to be clear: the combobox works fine, and the loop to set its values also works fine. The problem seems to be somewhere with the DataGridViewColumn LinePrice.
Any idea what's going on? Why does one type of column (combobox) works fine but the other does not?
p.s. I have cut lines of code regarding another DataGridView which fills with the Order table, as that one works fine and is irrelevant to the problem so far as I can tell).
UPDATE: When I move the box to before the combobox column, it suddenly appears... Not sure why though, and it's not where I want it to be in the DataGridView.
Change your code as :
DataTable Orders = Orders.Tables[Lines];
CurrentLine.DataSource = Orders;
for (int i = 0; i < CurrentLine.Rows.Count-1; i++)
{
string product =Orders.Rows[i][1].ToString (); //This loop sets the values of the combobox according to the order lines in the orderline table in the dataset.
CurrentLine.Rows[i].Cells[4].Value = product;
}
DataColumn LinePrice = new DataColumn("Line Price");
Orders.Columns.Add(LinePrice);
It should be works
I made use of your code and I encountered the below error during the execution of code fragment which adds "Line Price" column.
Column cannot be added because its CellType property is null.
The above error can be generated if columns are added after you have already added rows into the DataGridView since it is not possible determine the cell type.
I managed to display the column based on the order you requested using the below code fragment. Please try to add in the new line and confirm if this helps to resolve your issue.
DataGridViewColumn LinePrice = new DataGridViewColumn();
LinePrice.HeaderText = "Line Price";
LinePrice.Width = 100;
LinePrice.ReadOnly = true;
LinePrice.CellTemplate = new DataGridViewTextBoxCell(); // Define the cell type of the new column
CurrentLine.Columns.Add(LinePrice);
NOTE: The for loop can generate error (#o_weisman also mentioned this) while making use of i to get hold of the Orders.Rows[i] row. Further, it seems that you have a master try catch block which is suppressing the errors. Please review your code to ensure that you have implemented error traps accordingly.

Add new column at specified position programmatically in C# Datagridview

I have a datagridview with 5(0-5) columns. All the rows value I retrieve from the hashtable created.
Now I've set a condition that state if column 4 contain empty value from hashtable then add new column next to column 4 which makes the new added column index at position 5 and the value of hashtable previously for column 5 change to column 7.
I do the code like this:
int number = dataGridView1.Rows.Add();
dataGridView1.Rows[number].Cells[0].Value = result; //id
dataGridView1.Rows[number].Cells[1].Value = newAddress; //ip
dataGridView1.Rows[number].Cells[2].Value = (string)((Hashtable)ht[1])["value"]; //name
dataGridView1.Rows[number].Cells[3].Value = (string)((Hashtable)ht[2])["value"]; //description
if (!ht.ContainsValue(3))
{
// Create a Save button column
DataGridViewImageButtonSaveColumn columnSave = new DataGridViewImageButtonSaveColumn();
// Set column values
columnSave.Name = "SaveButton";
columnSave.HeaderText = "";
//Add the columns to the grid
dataGridView1.Rows[number].Cells[4].ReadOnly = false;
dataGridView1.Columns[5].Add(columnSave); //im not sure about this codes
dataGridView1.Rows[number].Cells[6].Value = (string)((Hashtable)ht[4])["value"]; //count
}
else
{
dataGridView1.Rows[number].Cells[4].Value = (string)((Hashtable)ht[3])["value"]; //location
dataGridView1.Rows[number].Cells[5].Value = (string)((Hashtable)ht[4])["value"]; //count
}
However, i'm not sure if I do this right because I receive error at the line commented
dataGridView1.Columns[5].Add(columnSave); //im not sure about this codes
Seems like this code is wrong. Can anyone please advise?
Try dataGridView1.Columns.Insert(5, columnSave); instead.
MSDN reference: DataGridViewColumnCollection.Insert Method
A simple way to insert a checkbox to certain column of Data grid:
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
dataGridView1.Columns.Insert(**certain column number**, chk);
for example if you want to add checkbox to column 1 you mus type
dataGridView1.Columns.Insert(0, chk);

C# DataGridView combobox add data programmatically

I have an application with a DataGridView. One of the columns is of the type Combobox. I want to add the items for this combobox programmatically. Here is the code I use for that:
this.dsStatussen = this.statussenMan.getAllStatussen();
DataGridViewComboBoxColumn cd = (DataGridViewComboBoxColumn)this.dgvEenheden.Columns[3];
cd.DataSource = dsStatussen;
cd.DisplayMember = "statussen";
cd.DataPropertyName = "sid";
cd.ValueMember = "status";
Then when I try to add a row I get the following error: "There is no field with the name status". I transelated the error to English because I have a Dutch error.
Here is the code I use for adding the rows:
Eenheden eenhedenMan = new Eenheden(objEvenement.eid);
DataSet EenhedenData = eenhedenMan.getAllEenheden();
foreach (DataRow dr in EenhedenData.Tables[0].Rows)
{
dgvEenheden.Rows.Add(
dr[0].ToString(),
dr[1].ToString(),
dr[2].ToString(),
Convert.ToInt32(dr[6]),
dr[3].ToString(),
dr[4].ToString(),
dr[5].ToString()
);
}
Could someone help me to figure out what I'm doeing wrong? I can't find it. This is the first time I use an DataGridView with comboboxes.
in my experience I found everything seemed to work better if you tied it in through a binding scource, then set the
bindingScource.dataScource.Rows.Add(
dr[0].ToString(),
dr[1].ToString(),
dr[2].ToString(),
Convert.ToInt32(dr[6]),
dr[3].ToString(),
dr[4].ToString(),
dr[5].ToString()
);
Select the correct row? you mean select from the dropdown to see the row inside the datagrid?
int index = dropdown.SelectedIndex();
for(int count = 0; count < dgvEenheden.Rows.Count; count ++)
{
if (dgvEenheden.Rows[count].Cells["<enter col name here>"].Value.ToString().equals(dropdown.Items[index].Text))
{
dgvEenheden.Rows[count].Selected = true; //to select the Row
dgvEenheden.Rows[count].Cells[<Cell Number>].Selected = true; //to select the specific Cell
}
}

Categories