Click here to Skip to main content
15,905,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI every body!
in my project i am adding union council and Village. Now i want to validate it. I mean that if i add viilage council first time. and if i add it 2 or three time it has adding to database. i want to to not add this it only add one time.

What I have tried:

This is my Code


public partial class VillageCouncil : Form
{
public VillageCouncil()
{
InitializeComponent();
}
Dataaccess da = new Dataaccess();
//SqlDataReader reader;
private void VillageCouncil_Load(object sender, EventArgs e)
{
string q = string.Format("Select ID,UCouncilName from UnionCouncil");
DataTable dt = new DataTable();
SqlDataAdapter sd = new SqlDataAdapter(q, da.open());
sd.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr[1].ToString());
}
//dt.Columns.Add("ID", typeof(string));
//dt.Columns.Add("UCouncilName", typeof(string));
//dt.Load(reader);

comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "UCouncilName";
comboBox1.DataSource = dt;


}

private void button1_Click(object sender, EventArgs e)
{
string q = string.Format("insert into VillageCouncil(VCouncilName,UCName) values ('{0}','{1}')",tbVCName.Text.Trim(),comboBox1.Text.Trim());//.SelectedItem.ToString());
SqlCommand sc = new SqlCommand(q, da.open());
sc.ExecuteNonQuery();
}
}
}
Posted
Updated 24-Jan-17 21:40pm
Comments
Philippe Mori 25-Jan-17 12:36pm    
Use a code block to format your code. If you are too lazy to write properly formatted and indented code, then you don't deserve much help.

1 solution

0) DO NOT use formatted strings to form queries. Use parameterized queries instead.

1) I fail to understand why people don't write stored procedures instead of hand-jamming the SQL in code like this.

2) A properly written query can Update existing data AND Insert new data. For example, the following code will attempt to insert data, and if it did not succeed, it will insert it instead.

SQL
UPDATE database.dbo.mytable
    SET field1 = @param1
    WHERE field2 = @param2
IF @@ROWCOUNT = 0
    INSERT INTO database.dbo.mytable
           (field1, field2) VALUES (@param1, @param2)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900