Chiranjeevi Aripaka

Chiranjeevi Aripaka

  • NA
  • 133
  • 299.9k

inserting data into database by skipping duplicate values .

Apr 28 2015 4:45 AM
hai friends,
 
please let me know how to insert values into database with out repetition..  that means skipping the already entered values from datagridview..
 
 
here is my  code  
 
 
AD_ YEA R CAT BRANCH REGD_ NO STU DEN T YEA R GE NDE R CAS TE
2013 A CSE 132Z1A0501 VENU FIRST MALE BCB
2013 A CSE 132Z1A0502 NAVEEN FIRST MALE BCB
2013 A CSE 132Z1A0503 TANUSHREE FIRST FEMALE BCB
2013 A CSE 132Z1A0504 TANUSHKA FIRST FEMALE BCB
  the red color indicated in the table was already entered so while updating to database these entered values should not enter again.
i am uploading excel data into datagridview. from datagridview  inserting data to database 
 
 
con.Open();
int c = dataGridView1.Rows.Count;
int d = c - 1;
MessageBox.Show(dataGridView1.Rows.Count.ToString());
try
{
if (dataGridView1.Rows.Count >= 1)
{
for (int i = 0; i <= d; i++)
{
textBox3.Text = dataGridView1.Rows[i].Cells[0].Value.ToString();//ADMIT YEAR
textBox4.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();//CAT
textBox5.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();//COURSE
textBox6.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();//REG_NO
textBox7.Text = dataGridView1.Rows[i].Cells[4].Value.ToString();//NAME
textBox8.Text = dataGridView1.Rows[i].Cells[5].Value.ToString();//year
textBox9.Text = dataGridView1.Rows[i].Cells[6].Value.ToString();
textBox10.Text = dataGridView1.Rows[i].Cells[7].Value.ToString();
 
 
 
try
{
SqlCommand CMD = new SqlCommand("SELECT COUNT(YEAR) as Tot FROM ADD_STUDENT WHERE REGD_NO='" + textBox6.Text + "' AND YEAR='" + textBox8.Text + "' ", con);
SqlDataReader dr = CMD.ExecuteReader();
while (dr.Read())
{
int i1 = Convert.ToInt32(dr["Tot"]);
if (i1 > 0)
{
MessageBox.Show(textBox6.Text + "REGD NO ALREADY ENTERED");
}
else
{
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
sql = "insert into product (REGD_NO) values('"+ textBox6.Text +"')";
try
{
con.Open();
adapter.InsertCommand = new SqlCommand(sql, con );
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Row inserted !! ");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}// END OF TRY STATEMENT
catch (Exception ex)
{
MessageBox.Show(ex.Message, "error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
 
 
 am getting error message like 
 
executereader requires an open and available connection. the connection's current state is open 
 
 
 
 
 
 
 
 
 

Answers (2)