Prevent Duplicate value entering into the Database

CS1401
Posted by CS1401 under ASP.NET category on | Points: 40 | Views : 4262
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;

string pword = textBox2.Text;
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();

conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\data1\jana.mdb";
conn.Open();
System.Data.OleDb.OleDbDataAdapter dr = new System.Data.OleDb.OleDbDataAdapter("select * from mans1", conn);

DataSet s = new DataSet();
//dr.SelectCommand = comm;
dr.Fill(s);

foreach (DataRow dar in s.Tables[0].Rows)
{
textBox3.Text = dar[1].ToString();
}
int k = 0;
foreach (DataRow darr in s.Tables[0].Rows)
{
if (name == darr[1].ToString())
{
MessageBox.Show("code already exist");
k = 1;
break;
}
}
if (k == 0)
{
string insertstatement = "INSERT INTO mans1(name,pword) VALUES( '" + textBox1.Text + "','" + textBox2.Text + "')";

System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(insertstatement, conn);

int n = cmd.ExecuteNonQuery();

if (n > 0)
{
MessageBox.Show("code saved");
}
}
else
{
MessageBox.Show("error");
}

conn.Close();

Form1.ActiveForm.Hide();
Form2 a = new Form2();
a.Show();
}

private void button2_Click(object sender, EventArgs e)
{

}
}
}

Comments or Responses

Posted by: T.saravanan on: 7/5/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi CS1401,

foreach (DataRow dar in s.Tables[0].Rows)

{
textBox3.Text = dar[1].ToString();
}

what is the use of the above code? Could you explain about your code?



Posted by: CS1401 on: 7/6/2011 Level:Starter | Status: [Member] | Points: 10
Here it is checking all the rows if that data is available or not. Thats why i used foreach..
Posted by: T.saravanan on: 7/6/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Ok.
I am understand. what is the use of below code...
foreach (DataRow dar in s.Tables[0].Rows)

{
textBox3.Text = dar[1].ToString();
}

In this code final row value only set in your textbox control..then only i ask...So change your code...
Posted by: CS1401 on: 7/7/2011 Level:Starter | Status: [Member] | Points: 10
That code just for checking if i get the value correctly or not..
thats all. I didn't edit that code properly. if i submit the article means i will edit all and submit. pls refer it.
Posted by: T.saravanan on: 7/10/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi cs1401,

I am not expecting your code for my reference just verify your code then only gave my suggestion.
Just go and edit, change the correction in your code.

Login to post response