adros adros - 3 months ago 41
ASP.NET (C#) Question

How to check if value from TextBox exists in DataSet?

Here's the sample of code from my project. DataSet is storing values of

authors first name and last name
, depending on particular book id. However, one book can have many authors. When user types some values in TextBoxes and press save button, one of two methods should be launched. First method update existing author record in the database, if values from textboxes and dataset are the same. If not - second method should be triggered and new author record should be added to the database.

DataSet ds = GetData(queryString);
Autor autor = new Autor();

foreach (DataTable dt in ds.Tables)
{
foreach (DataRow dr in dt.Rows)
{
string firstName = dr["First_name"].ToString();
string lastName = dr["Last_name"].ToString();
if (firstName.Trim().ToUpper() == txtFirstName.Text.Trim().ToUpper() && lastName.Trim().ToUpper() == txtLastName.Text.Trim().ToUpper())
{
//updating existing author record in the database
Autor.UpdateInDatabase(autor);
}
else
{
//adding new author record in the database
Autor.AddToDatabase(autor);
break;
}
}
}


This code works only if matching values are in first dataset row - which is obviously wrong. Could anyone help me to understand how to loop through dataset, compare all results and depending on the result - choose correct method?

Answer

Just add a boolean flag.

bool itemFound = false;
foreach (DataTable dt in ds.Tables)
{
   foreach (DataRow dr in dt.Rows)
   {
      string firstName = dr["First_name"].ToString();
      string lastName = dr["Last_name"].ToString();
      if (firstName.Trim().ToUpper() == txtFirstName.Text.Trim().ToUpper() && lastName.Trim().ToUpper() == txtLastName.Text.Trim().ToUpper())
      {  
        itemFound = true;
        break;                                        
      }              
   }
 }

if(itemFound)
    Autor.UpdateInDatabase(autor); 
else
    Autor.AddToDatabase(autor); 
Comments