Click here to Skip to main content
16,011,868 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi :) ,i connect datagridview to sql to show data on datagridview. i have add a checkbox,and change color of row to red when is check. and when is check automatic next row.
my problem is here when is the last row that give me a error. what i want is when is the last row , check and dont try to add a new row.

What I have tried:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

//Fill Datagrid
this.uSR_ProdMonitorTableAdapter.FillBy(this.iso_OldDataSet.USR_ProdMonitor);

}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
bool selected = !Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["check"].Value);
dataGridView1.Rows[1].Selected = true;

if (selected)
{
//if is check automatic nex row
int next = this.dataGridView1.CurrentRow.Index +1;
//change color to red if check
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[next].Cells[this.dataGridView1.CurrentCell.ColumnIndex];
}
else
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGreen;
dataGridView1.Rows[e.RowIndex].Cells["check"].Value = !Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["check"].Value);

}
}


}

}
Posted
Updated 7-Mar-19 11:41am

You need to check your "row count" instead of arbitrarily indexing to the "next row" (which may not exist).
int next = this.dataGridView1.CurrentRow.Index +1;

DataRowCollection.Count Property (System.Data) | Microsoft Docs[^]
 
Share this answer
 
thank you Gerry, yes is the correct way :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900