i have a simple c# application in which you have to enter data in a DataGridView
. I have implemented some validators for the columns, like null values or non-numeric input. I do the checks after a button has been presses by foreach (DataGridViewRow row in dataGridView1.Rows) {...}
i am facing the problem that it also tries to validate the last row of the DataGridView
, although this one is added automatically and is empty. So i am stuck in a loop here...
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string inputItemNr;
string inputMHD;
string inputCharge;
string inputSupplNr;
string inputPrnCnt;
UInt32 itemnr;
DateTime mhd;
string mhdFormat = "yyMMdd";
string batch;
byte prncnt;
if (row.Cells[0].Value == null)
{
MessageBox.Show("Enter item number");
return;
}
else
{
inputItemNr = row.Cells[0].Value.ToString();
}
if (!UInt32.TryParse(inputItemNr, out itemnr))
{
MessageBox.Show("Incorrect item number: " + inputItemNr);
return;
}
if (row.Cells[1].Value == null)
{
MessageBox.Show("Enter MHD");
return;
}
else
{
inputMHD = row.Cells[1].Value.ToString();
}
if (!DateTime.TryParseExact(inputMHD, mhdFormat, CultureInfo.InvariantCulture,
DateTimeStyles.None, out mhd))
{
MessageBox.Show("Incorrect MHD: " + inputMHD);
return;
}
if (row.Cells[2].Value == null)
{
inputCharge = DateTime.Now.ToString("yyMMdd");
}
else
{
inputCharge = row.Cells[2].Value.ToString();
}
if (row.Cells[3].Value == null)
{
batch = inputCharge;
}
else
{
inputSupplNr = row.Cells[3].Value.ToString();
batch = inputCharge + " " + inputSupplNr;
}
if (row.Cells[4].Value == null)
{
inputPrnCnt = "1";
}
else
{
inputPrnCnt = row.Cells[4].Value.ToString();
}
if (!byte.TryParse(inputPrnCnt, out prncnt))
{
MessageBox.Show("Incorrect print count: " + inputPrnCnt);
return;
}
}
}
Please help.
Thanks,
There are two ways to remove the Remove (Delete) Last Blank (Empty) Row from DataGridView. The first way is to right click the DataGridView and then click Properties item from the Context menu. Now from the Properties window, look for AllowUserToAddRows property and set it False.
This can be hidden by setting the AllowUserToAddRows property to false. Alternatively you can uncheck the 'Enable Adding' tick box in the DataGridView Tasks dialog. Show activity on this post. Disable AllowUserToAddRows property.
When you remove the record from the collection, set the datasource property on your datagridview to null, and then rebind it to your list. That should do the trick. Alternatively, you can handle the DataError event on your dataGridview and in the method you can say e.
You could use the IsNewRow
property of the row:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) continue;
// rest of your loop body ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With