-1

This is my code for when button is clicked:

private void button1_Click(object sender, EventArgs e)
{
    conn.Open();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "insert into Table1 values('" + textBox1.Text+"','" + textBox2.Text +"','" + textBox3.Text +"')";
    int atpos = textBox3.Text.IndexOf("@");
    int dotpos = textBox3.Text.LastIndexOf(".");

    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= textBox3.Text.Length)
    {
        MessageBox.Show("not a valid email address");                
    }
    else
    {    
    }

    cmd.ExecuteNonQuery();  
    conn.Close();

    textBox1.Text = "";
    textBox2.Text = "";
    textBox3.Text = "";
    displayData();

    MessageBox.Show("data inserted successfully");    
}

I want that, when if condition is true, the data should not be inserted in table.

Thanks in advance.

krlzlx
  • 5,752
  • 14
  • 47
  • 55

1 Answers1

0

not really sure if this is what you are looking for but here goes:

private void button1_Click(object sender, EventArgs e)
{        
   int atpos = textBox3.Text.IndexOf("@"); 
   int dotpos = textBox3.Text.LastIndexOf(".");

    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= textBox3.Text.Length)
    {
        MessageBox.Show("not a valid email address");

    }
    else
    {
      conn.Open(); 
      SqlCommand cmd = conn.CreateCommand(); 
      cmd.CommandType = CommandType.Text; 
      cmd.CommandText = "insert into Table1 values('" + textBox1.Text+"','" +   textBox2.Text +"','" + textBox3.Text +"')"; 

      cmd.ExecuteNonQuery();
      conn.Close();

      textBox1.Text = "";
      textBox2.Text = "";
      textBox3.Text = "";
      displayData();

      MessageBox.Show("data inserted successfully");
    }      

}

I would suggest that you look at using Regex to validate the email address, her is a link to how to use regex for email in c#: Regex Email validation

private void button1_Click(object sender, EventArgs e)
{       
   Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); 
   Match match = regex.Match(textBox3.Text);

   if (match.Success)
   {
      MessageBox.Show("not a valid email address");
   }
   else
   {
     conn.Open(); 
     SqlCommand cmd = conn.CreateCommand(); 
     cmd.CommandType = CommandType.Text; 
     cmd.CommandText = "insert into Table1 values('" + textBox1.Text+"','" +   textBox2.Text +"','" + textBox3.Text +"')"; 

     cmd.ExecuteNonQuery();
     conn.Close();

     textBox1.Text = "";
     textBox2.Text = "";
     textBox3.Text = "";
     displayData();

     MessageBox.Show("data inserted successfully");
  }       
}

Also I am not sure what you progject parameters are but I would also suggest using some sort of ORM. Look at Entity Framework if you are interested.

Community
  • 1
  • 1
Van
  • 600
  • 4
  • 12