Bukhalifa
Bukhalifa

Reputation: 13

C# insert into details table with master details id

I am really new to C# and I have searched all over but I didn't find answer to problem.

in my application I have a table for example (employee details) second table is leaves.

what I want is to link employee details tables primary key to leaves table.

employee can have many leaves

So when I insert leaves record for employee it should store with employee details table id and when I search in leaves form with emid it shows all his leaves in datagridview.

employee details table

emid
empno
emname
emjoindate
emmobile
emaddress

leaves table

leaveid
emid
leavestartdate
leaveenddate

private void Save()
        {
                con = new SqlConnection(cs.DBConn);
                con.Open();
                string cb = "insert into leaves(leavestartdate,leaveenddate,notes) VALUES (@d1,@d2,@d3)";


                cmd = new SqlCommand(cb);

                cmd.Connection = con;

                cmd.Parameters.Add(new SqlParameter("@d1", SqlDbType.Date, 31, "leavestartdate"));
                cmd.Parameters.Add(new SqlParameter("@d2", SqlDbType.Date, 31, "leaveenddate"));
                cmd.Parameters.Add(new SqlParameter("@d3", SqlDbType.NVarChar, 500, "notes"));

                cmd.Parameters["@d1"].Value = txtstartdate.Text.Trim();
                cmd.Parameters["@d2"].Value = txtenddate.Text.Trim();
                cmd.Parameters["@d3"].Value = txtnotes.Text.Trim();
                con.Close();


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

Upvotes: 0

Views: 1123

Answers (2)

kgzdev
kgzdev

Reputation: 2885

You need to add emid parameter to insert query.

string cb = "insert into leaves(emid,leavestartdate,leaveenddate,notes) VALUES (@emid,@d1,@d2,@d3)";

and then set value of parameter @emid

then you can select leaves of any emid like this

string cb = "select * from leaves where emid = @emid";

EDIT: To get emname and emmobile from employee details table you can use this query

SELECT L.*, ED.emname , EM.emmobile 
FROM leaves L INNER JOIN
employee_details ED ON L.emid = ED.emid
WHERE L.emid = @emid

Upvotes: 1

s.k.Soni
s.k.Soni

Reputation: 1310

have you ever tried using select query. Because from select query also we can do this.

Upvotes: 1

Related Questions