Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# WPF
hai..
For example i have 2 tables person1,data the id of person1 is set as autoincremented and there is another column named description when description is added to table desc id should be inserted to the second table data.whose value is same as id in person1.can u please help me...Here am attaching the code..
Thanks in advance..
 
namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=book;User ID=sa;Password=nest123@!");
            con.Open();
 

            string query = "insert into person1(description) values('" + textBox3.Text + "')";
            
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
 
            try
            {
                SqlCommand cm = new SqlCommand("select Id from person1 where description='" + textBox3.Text + "'",con);
                SqlDataReader rd = cm.ExecuteReader();
 
                while (rd.Read())
                {
                    string str = rd["Id"].ToString();
 
                }
                SqlCommand cmd2 = new SqlCommand("insert into data (name,age,desc_id) values('" + textBox1.Text + "','" + textBox2.Text + "','+str+')");
            }
 
            catch (SqlException ex)
            {
            }
        }
        
    }
}
Posted 14-Jan-13 0:17am
Edited 14-Jan-13 0:24am
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

In C#, right after your SQL Statement write "SELECT SCOPE_IDENTITY();" so your code would be:
 
Insert into TABLE (...) values (...); SELECT SCOPE_IDENTITY();
Instead of ExecuteNonQuery() use ExecuteScalar().
i.e.,
Decimal id = (Decimal)cmd.ExecuteScalar(); // You can now use Id for your further insert statements.
See if it works.
  Permalink  
v3
Comments
OriginalGriff at 14-Jan-13 5:38am
   
Um. Our solutions are very similar, but yours will give an InvalidCastException - the return value will be a decimal, not an int. Try it. See if it works... :laugh:
Vani Kulkarni at 14-Jan-13 6:51am
   
Just tried it. My bad. But this works on 1.1 version. Is it a bug?
OriginalGriff at 14-Jan-13 7:17am
   
Probably a tightening up of the rules (or a more rigid interpretation of the rules) rather than a bug - I haven't used .NET V1 for a very long time so I can't really check easily! :laugh:
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Please, do not do it like that! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
 
Secondly, the easiest way to do that is to use a single command:
 
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO MyTable (myColumn1, myColumn2) VALUES ('XXX', 666) SELECT SCOPE_IDENTITY()", con))
        {
        decimal d = (decimal) com.ExecuteScalar();
        }
    }
d will contain the ID you just assigned.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 277
1 Maciej Los 210
2 BillWoodruff 195
3 DamithSL 195
4 Richard MacCutchan 178
0 OriginalGriff 5,130
1 DamithSL 4,197
2 Maciej Los 3,670
3 Kornfeld Eliyahu Peter 3,470
4 Sergey Alexandrovich Kryukov 2,821


Advertise | Privacy | Mobile
Web03 | 2.8.141216.1 | Last Updated 14 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100