简体   繁体   中英

ASP.NET - drop down list

i have 2 tables in my database:

Employee  (ID , NAME , SALARY , departmentNo)

ID is primary key and departmentNo foreign key from Department.ID

Department (ID , Name , Location)

ID is primary key

So I want to make drop down list that shows on a form names of departments, and when user press "add" button it should save departmentNo on table.

Here is the solution of your question. I have used some extra variables just to check values are coming or not you can replace them as per your need.

 db_connection();
        string id=null;
        string h = comboBox1.SelectedValue.ToString();
        string select = "select ID from Department where Name='" + h + "'";
        SqlCommand cmd=new SqlCommand(select,Cn);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            id = dr[0].ToString();
        }
        dr.Close();
        select = "insert into Employee (NAME,SALARY,departmentNo)values(@NAME,@SALARY,@departmentNo)";
        SqlCommand cmd1 = new SqlCommand(select, Cn);
        cmd1.Parameters.AddWithValue("@NAME", textBox1.Text);
        cmd1.Parameters.AddWithValue("@SALARY", textBox2.Text);
        cmd1.Parameters.AddWithValue("@departmentNo", id);
        cmd1.ExecuteNonQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM