简体   繁体   English

从主键asp.net C#获取SQL外键列值

[英]Get SQL Foreign key columns values from Primary Key asp.net c#

I have two tables one is Teacher and the other one is Scheduling. 我有两张桌子,一张是教师,另一张是计划。 The teacher table has Primary key TID and other columns. 教师表具有主键TID和其他列。 The Scheduling table has primary key, other columns and Foreign Key TID. 计划表具有主键,其他列和外键TID。

Now, I insert teachers data in one page. 现在,我将教师数据插入一页。 It inserts successfully. 成功插入。 I have to insert data in other page to schedule the class of the teacher with the student. 我必须在其他页面中插入数据以安排与学生一起上课的时间。 My problem is this, I cannot insert the pk values of teachers in the fk column of Scheduling Table. 我的问题是,我无法在“计划表”的fk列中插入教师的pk值。

Here's what I have done so far. 到目前为止,这是我所做的。

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace E_Tutor_Manager
{
    public partial class ScheduleClass : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            {
                string connc = @"Data Source=KHAWAR-PC.\SQLEXPRESS;Initial Catalog=ETManager;Integrated Security=True";
                SqlConnection con = new SqlConnection(connc);
                string query = "SELECT Username FROM Teachers";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Connection.Open();
                SqlDataReader ddlValues;
                ddlValues = cmd.ExecuteReader();
                TUName.DataSource = ddlValues;
                TUName.DataValueField = "Username";
                TUName.DataTextField = "Username";
                TUName.DataBind();
                cmd.Connection.Close();
                cmd.Connection.Dispose();
            }

            if (!IsPostBack)
            {
                if (Session["New"] != null)
                {
                    welcome.Text += Session["New"].ToString();
                }
                else
                    Response.Redirect("Login.aspx");
            }
        }

        protected void Button1_Schedule_Click(object sender, EventArgs e)
        {

            try
            {
                {
                    string connc = @"Data Source=KHAWAR-PC.\SQLEXPRESS;Initial Catalog=ETManager;Integrated Security=True";
                    SqlConnection con = new SqlConnection(connc);
                    con.Open();

                    string query = "SELECT * FROM Teachers WHERE StartTime = @StartTime";
                    string query1 = "INSERT INTO Schedules(Grade,Subjects,STime,TID) VALUES ('" + txtGrd.Text + "','" + Sbj.SelectedValue + "','" + txtTime.Value + "')";
                    SqlCommand sql = new SqlCommand(query1, con);
                    SqlCommand sql1 = new SqlCommand(query, con);
                    sql.ExecuteNonQuery();
                    var cmd = new SqlCommand(query, con);
                    cmd.Parameters.AddWithValue("@StartTime", txtTime.Value);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    if (dt.Rows.Count > 0)
                    {
                        labelmsg.Text = "Sorry!!! This teacher is not available at this time. Please select the other teacher";
                    }
                    else
                    {
                        labelmsg.Text = "Class Scheduled Succesfully!!!";
                    }
                    con.Close();
                }        
            }
            catch (Exception ee)
            {
                throw (ee);
            }
        }

    }
}

So can anybody help me? 有人可以帮我吗?

Try this. 尝试这个。 This will work only if the select query returns only one value. 仅当选择查询仅返回一个值时,这才起作用。

string query1 = "INSERT INTO Schedules(Grade,Subjects,STime,TID) VALUES ('" + txtGrd.Text + "','" + Sbj.SelectedValue + "','" + txtTime.Value + "',(SELECT TID FROM Teachers WHERE StartTime = @StartTime))";
string query1 = "INSERT INTO Schedules(Grade,Subjects,STime,TID) VALUES ('" + txtGrd.Text + "','" + Sbj.SelectedValue + "','" + txtTime.Value + "')";

This is the line where you want to insert the FK. 这是您要插入FK的行。 First you must retrieve it like so: 首先,您必须像这样检索它:

int FK_ID; // This is where we store the foreign key
using(SqlReader reader = query.ExecuteReader())
{
    while(reader.Read())
    {
         FK_ID = (int)reader["ID"]; // where supposingly ID is the field name
         //But this FK_ID will be the one you want 
         //only if the query returns a single result, otherwise it will set FK_ID 
         //to the last returned row
    }
}

Then you can use the ID to set it in the query1 values 然后您可以使用ID在query1值中进行设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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