blah blah blah is here! blah blah » Close

up1down
link

I'm trying to compile some code that will check if a date from a datetimepicker and text from a textbox match exisisting entries in a datagridview if so throw a message window.

Example:

on my form i have dateTimePicker1 and resIndexTextBox, i have a datagridview with coloumn [1] being a stored date entry and column [8] with a stored resIndex value.

Can dateTimePicker1 check through datagridview column 1 and resIndexTextBox check through column 8 at the same time, if both match the datagrid values throw up a message box?

last answered one year ago

2 answers

link

Try the following code (including EDIT):

foreach (DataGridViewRow row in calendarDataGridView.Rows)
{
if (row.IsNewRow) break; // now break instead of return
if (row.Cells[1].Value == null || row.Cells[8].Value == null) continue;
DateTime dt;
DateTime.TryParse(row.Cells[1].Value.ToString(), out dt);
if (dt.Date == dateTimePicker1.Value.Date && row.Cells[8].Value.ToString().Trim() == resIndexTextBox.Text.Trim())
{
MessageBox.Show("Matching items already exist");
return;
}
}

if (textText.Text.Trim() == "")
{

MessageBox.Show("Please enter Description");
// your text box empty
}
else
{
// my function code
}

up0down
link

That works spot on vulpes thanks, could i adapt it to perform a function if the dates don't match?, i've tried something like the below but somethings wrong with my attempt, basiclly this is stopping a double booking, so if the dates match it would stop the user saving, but if the dates dont match perform save function.

foreach (DataGridViewRow row in calendarDataGridView.Rows)
{
if (row.IsNewRow) return;
if (row.Cells[1].Value == null || row.Cells[8].Value == null) continue;
DateTime dt;
DateTime.TryParse(row.Cells[1].Value.ToString(), out dt);
if (dt.Date == dateTimePicker1.Value.Date && row.Cells[8].Value.ToString().Trim() == resIndexTextBox.Text.Trim())
{
MessageBox.Show("Matching items already exist");
return;
}
else if (textText.Text.Trim() == "")
{

MessageBox.Show("Please enter Desciption");
//your text box empty

}
else
{
//my function code
}
}

vulpes
17279

I think you need to move the 'else if' and 'else' blocks outside the foreach statement. See my edit.

Nice one - thanks vulpes

Feedback