Using C#.net how to..........

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hello Sir,
I am using sql server 2008 and MS Visual studio 2008. I am developing one banking project using asp.net and code behind file is C#.net.
I want to insert the data in sql server table if row does not exists , otherwise if row exists it has to update the column value (means if row exists i want to update or increase the column value).
I am trying this through C#.net only it is inserting the row on sql if row doesnt exists, but if row exists
it is not updating why i dont know and it is not showing any error also......... i wrote c# code like this,
SqlConnection con = new SqlConnection("Data Source=SQLSERVER; Initial Catalog=bankinfo; User id=sa; Password=admin@123");<br/>
SqlDataReader dr;<br/>
try<br/>
{<br/>
con.Open();<br/>
SqlCommand cmd = new SqlCommand("select * from dept", con);<br/>
dr = cmd.ExecuteReader();<br/>
//cmd.ExecuteNonQuery();<br/>
<br/>
if (dr.HasRows)<br/>
{<br/>
int a = System.Convert.ToInt32(TextBox1.Text);<br/>
int x = System.Convert.ToInt32(TextBox3.Text);<br/>
int k = 1;<br/>
SqlTransaction trans;<br/>
trans = con.BeginTransaction();<br/>
cmd.Connection = con;<br/>
<br/>
cmd.Transaction = trans;<br/>
cmd.CommandType = CommandType.Text;<br/>
cmd.CommandText = "UPDATE dept SET balanceamt=balanceamt + " + x + " WHERE accountno=" + a + "and name=" + TextBox2.Text + "";<br/>
cmd.ExecuteNonQuery();<br/>
if (k == 1)<br/>
{<br/>
trans.Commit();<br/>
MessageBox.Show("Amount is Debited....");<br/>
}<br/>
<br/>
else<br/>
{<br/>
trans.Rollback();<br/>
<br/>
}<br/>
con.Close();<br/>
}<br/>
else<br/>
{<br/>
<br/>
try<br/>
{<br/>
SqlConnection cn = new SqlConnection("Data Source=SQLSERVER; Initial Catalog=bankinfo; User id=sa; Password=admin@123");<br/>
<br/>
cn.Open();<br/>
SqlCommand cmd1 = new SqlCommand("insert into dept values (@accountno,@name,@balanceamt)", cn);<br/>
<br/>
cmd1.Parameters.AddWithValue("@accountno", TextBox1.Text);<br/>
cmd1.Parameters.AddWithValue("@name", TextBox2.Text);<br/>
cmd1.Parameters.AddWithValue("@balanceamt", TextBox3.Text);<br/>
<br/>
cmd1.CommandType = CommandType.Text;<br/>
cmd1.ExecuteNonQuery();<br/>
<br/>
Response.Write(MessageBox.Show("Amount Deposited Successfully"));<br/>
<br/>
<br/>
}<br/>
<br/>
catch (SqlException ex)<br/>
{<br/>
MessageBox.Show("Account Does not Exist");<br/>
//string msg = "Insert Error";<br/>
//msg += ex.Message;<br/>
//throw new Exception(msg);<br/>
}<br/>
finally<br/>
{<br/>
<br/>
TextBox1.Text = "";<br/>
TextBox2.Text = "";<br/>
TextBox3.Text = "";<br/>
<br/>
}<br/>
<br/>
}<br/>
<br/>
<br/>
}<br/>
catch<br/>
{<br/>
}<br/>
}
so, can any one help me how to do this updating and inserting.......
waiting for answer........
Thanks......


View the full article
 
Back
Top