【问题标题】:After inserting data into one table, I also want that data to auto appear in another table将数据插入一个表后,我还希望该数据自动出现在另一个表中
【发布时间】:2014-02-08 19:30:26
【问题描述】:

我有两个按钮,一个点击进入药物表格,另一个点击进入处方表格。我想要实现的是,如果我在药物表格中输入了一条记录,处方表格将自动生成一个处方 ID,并根据我在药物表格上输入的药物名称弹出药物名称。

对于处方表单中的字段 drugName,它最初是一个 drugID,但我使用左外连接显示为药物表中存在的 drugName。

对于附加的第一张图片,处方表有 panadol 记录的原因是因为我在处方数据库中输入了数字 3 的药物 ID。我不想在数据库中手动输入它,我希望它在我以药物形式插入记录时自动弹出。看,当我用强效的 panadol 插入记录时,它没有出现在处方表中!!!!!

处方和药物表格

处方表

药物治疗台

键入值并单击药物表单中的提交按钮后出错。 将 nvarchar 值“panadol3”转换为数据类型 int 时转换失败。

//处方格式代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace GRP_02_03_SACP
{
    public partial class prescription : Form
    {

        // Data Table to store employee data
        DataTable Prescription = new DataTable();

        // Keeps track of which row in Gridview
        // is selected
        DataGridViewRow currentRow = null;

        SqlDataAdapter PrescriptionAdapter;

        public prescription()
        {
            InitializeComponent();
        }

        private void prescription_Load(object sender, EventArgs e)
        {
            LoadPrescriptionRecords();
        }

        private void LoadPrescriptionRecords()
        {

            //retrieve connection information info from App.config
            string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
            //STEP 1: Create connection
            SqlConnection myConnect = new SqlConnection(strConnectionString);
            //STEP 2: Create command
            string strCommandText = "SELECT prescriptionID, med.medicationName FROM PRESCRIPTION AS pres";
            strCommandText += " LEFT OUTER JOIN medication as med on pres.medicationid = med.medicationid";

            PrescriptionAdapter = new SqlDataAdapter(strCommandText, myConnect);

            //command builder generates Select, update, delete and insert SQL
            // statements for MedicalCentreAdapter
            SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(PrescriptionAdapter);
            // Empty Employee Table first
            Prescription.Clear();
            // Fill Employee Table with data retrieved by data adapter
            // using SELECT statement
            PrescriptionAdapter.Fill(Prescription);

            // if there are records, bind to Grid view & display
            if (Prescription.Rows.Count > 0)
                grdPrescription.DataSource = Prescription;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (printDialog1.ShowDialog() == DialogResult.OK) // this displays the dialog box and performs actions dependant on which option chosen.
            {
                printDocument1.Print();
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            int columnPosition = 0;
            int rowPosition = 25;

            // run function to draw headers
            DrawHeader(new Font(this.Font, FontStyle.Bold), e.Graphics, ref columnPosition, ref rowPosition); // runs the DrawHeader function

            rowPosition += 35; // sets the distance below the header text and the next black line (ruler)

            // run function to draw each row
            DrawGridBody(e.Graphics, ref columnPosition, ref rowPosition);
        }

        // DrawHeader will draw the column title, move over, draw the next column title, move over, and continue.
        private int DrawHeader(Font boldFont, Graphics g, ref int columnPosition, ref int rowPosition)
        {
            foreach (DataGridViewColumn dc in grdPrescription.Columns)
            {

                //MessageBox.Show("dc = " + dc);

                g.DrawString(dc.HeaderText, boldFont, Brushes.Black, (float)columnPosition, (float)rowPosition);
                columnPosition += dc.Width + 5; // adds to colPos. value the width value of the column + 5. 
            }

            return columnPosition;
        }

        /* DrawGridBody will loop though each row and draw it on the screen. It starts by drawing a solid line on the screen, 
         * then it moves down a row and draws the data from the first grid column, then it moves over, then draws the data from the next column,
         * moves over, draws the data from the next column, and continus this pattern. When the entire row is drawn it starts over and draws
         * a solid line then the row data, then the next solid line and then row data, etc.
        */
        private void DrawGridBody(Graphics g, ref int columnPosition, ref int rowPosition)
        {
            // loop through each row and draw the data to the graphics surface.
            foreach (DataRow dr in ((DataTable)grdPrescription.DataSource).Rows)
            {
                columnPosition = 0;

                // draw a line to separate the rows 
                g.DrawLine(Pens.Black, new Point(0, rowPosition), new Point(this.Width, rowPosition));

                // loop through each column in the row, and draw the individual data item
                foreach (DataGridViewColumn dc in grdPrescription.Columns)
                {
                    // draw string in the column
                    string text = dr[dc.DataPropertyName].ToString();
                    g.DrawString(text, this.Font, Brushes.Black, (float)columnPosition, (float)rowPosition + 10f); // the last number (10f) sets the space between the black line (ruler) and the text below it.

                    // go to the next column position
                    columnPosition += dc.Width + 5;
                }

                // go to the next row position
                rowPosition = rowPosition + 60; // this sets the space between the row text and the black line below it (ruler).
            }
        }

        private void btnPrintPreview_Click(object sender, EventArgs e)
        {
            try
            {
                // PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog(); // instantiate new print preview dialog
                printPreviewDialog1.Document = this.printDocument1;
                if (printPreviewDialog1.ShowDialog() == DialogResult.OK) // Show the print preview dialog, uses printPage event to draw preview screen
                {
                    printDocument1.Print();
                }
            }
            catch (Exception exp)
            {
                System.Console.WriteLine(exp.Message.ToString());
            }
        }
    }
}

药物表格代码。这是我在 insertprescription 触发器中的代码。

ALTER TRIGGER insertPrescriptions ON dbo.MEDICATION AFTER INSERT AS INSERT INTO drug(prescriptionID, drugID) 从插入的 GO 中选择 MedicationID, MedicationName

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace GRP_02_03_SACP
{
    public partial class medication : Form
    {
        // Data Table to store employee data
        DataTable Medication = new DataTable();

        // Keeps track of which row in Gridview
        // is selected
        DataGridViewRow currentRow = null;

        SqlDataAdapter MedicationAdapter;

        public medication()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (btnSubmit.Text == "Clear")
            {
                btnSubmit.Text = "Submit";
                ClearTextBoxes();
                txtmedicationType.Focus();
            }
            else
            {
                btnSubmit.Text = "Clear";
                int result = AddMedicationRecord();
                if (result > 0)
                    MessageBox.Show("Insert Successful");
                else
                    MessageBox.Show("Insert Fail");

            }
        }
        private void ClearTextBoxes()
        {
            txtmedicationType.Clear();
            txtmedicationName.Clear();
            txtexpiryDate.Clear();
            txtmedicationPrice.Clear();
        }

        private int AddMedicationRecord()
        {
            int result = 0;
            // TO DO: Codes to insert customer record
            //retrieve connection information info from App.config
            string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
            //STEP 1: Create connection
            SqlConnection myConnect = new SqlConnection(strConnectionString);
                //STEP 2: Create command
 String strCommandText = "INSERT MEDICATION(medicationType, medicationName, expiryDate, medicationPrice) "
                + " VALUES (@NewmedicationType, @NewmedicationName,@NewexpiryDate, @NewmedicationPrice)";

            SqlCommand updateCmd = new SqlCommand(strCommandText, myConnect);


            updateCmd.Parameters.AddWithValue("@NewmedicationName", txtmedicationName.Text);
            //updateCmd.Parameters["@clientid"].Direction = ParameterDirection.Output; 
            // STEP 3 open connection and retrieve data by calling ExecuteReader
            myConnect.Open();
            // STEP 4: execute command
            // indicates number of record updated.
            result = updateCmd.ExecuteNonQuery();

            // STEP 5: Close
            myConnect.Close();
            return result;

        }

        private void medication_Load(object sender, EventArgs e)
        {
            LoadMedicationRecords();
        }

        private void LoadMedicationRecords()
        {

            //retrieve connection information info from App.config
            string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
            //STEP 1: Create connection
            SqlConnection myConnect = new SqlConnection(strConnectionString);
            //STEP 2: Create command
            string strCommandText = "SELECT medicationID, medicationType, medicationName, expiryDate, medicationPrice FROM MEDICATION";

            MedicationAdapter = new SqlDataAdapter(strCommandText, myConnect);

            //command builder generates Select, update, delete and insert SQL
            // statements for MedicalCentreAdapter
            SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(MedicationAdapter);
            // Empty Employee Table first
            Medication.Clear();
            // Fill Employee Table with data retrieved by data adapter
            // using SELECT statement
            MedicationAdapter.Fill(Medication);

            // if there are records, bind to Grid view & display
            if (Medication.Rows.Count > 0)
                grdMedication.DataSource = Medication;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            int modifiedRows = 0;
            // Get changes
            DataTable UpdatedTable = Medication.GetChanges();
            if (UpdatedTable != null)
            {
                // there are changes
                // Write modified data to database 
                modifiedRows = MedicationAdapter.Update(UpdatedTable);
                // accept changes
                Medication.AcceptChanges();
            }
            else
                MessageBox.Show("there are no changes to update");

            if (modifiedRows > 0)
            {
                MessageBox.Show("There are " + modifiedRows + " records updated");
                LoadMedicationRecords();
            }
        }

        private void grdMedication_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            MedicationAdapter.Update(Medication);
        }

    }
}

【问题讨论】:

  • 用drugform的event valuechanged刷新处方表怎么样!
  • 如何创建那个事件值改变了?和要输入的代码? @FeliceM
  • 我不知道你在用什么。但是,假设您使用的是 dagridview,请查找 DataGridView.CellValueChanged,然后在此类事件中编写代码以刷新/更新第二个网格。类似 MedicationAdapter.Update(Medication)
  • 所以通过这样做,每次我使用药物表格在药物表中插入一条记录时,它都会在处方表数据库中插入一条记录? @FeliceM
  • 是的,我使用数据网格视图。我想你有错误的想法。我的意思是它甚至没有插入到我的处方表数据库中。我希望每当我使用表格在药物中插入记录时,也会在处方表数据库中输入一条记录,其中只有一个自动递增的处方 ID 和我使用药物表格插入的药物名称。 @FeliceM

标签: c# sql database select


【解决方案1】:

如果您知道 100% 的时间都想要第二个表中的行,一个真正简单的方法是插入后触发器。如果需要,您还可以添加更新和删除触发器。如果您需要有条件地插入它,那么您可能会在代码中对其进行排序。

http://technet.microsoft.com/en-us/library/aa258254(v=SQL.80).aspx

【讨论】:

  • 天哪,对我来说太复杂了。我正在为我的 sch 项目做这个。 @drewlander
  • 哦,还不错。如果它是一项作业,它可能对你不起作用,因为教师可能正在寻找一个特定的解决方案,但它的要点是,如果你在药物表上添加这个触发器,它应该每次都在处方表中插入一条记录。您可以为更新和删除创建类似的触发器。 CREATE TRIGGER insertPrescriptions ON Medications AFTER INSERT AS INSERT INTO prescriptions(MedicationID, MedicationName) select MedicationID, MedicationName from inserted GO
  • 谢谢,哦,没关系,我想我只需要它工作,那么它已经很好了。我试图遵循你的代码,我在药物表格上发布了我更新的代码。当我输入药物名称并按下提交按钮时出现错误。怎么了?关键字“TRIGGER”附近的语法不正确。关键字“VALUES”附近的语法不正确。 @drewlander
  • 您在数据库中创建触发器,而不是在您的代码中。 ;-) 我直接把它写到stackoverflow。我会尝试打开 ssms 来创建你的表并验证语法以确保。
  • 谢谢伙计。但是我发现在哪里输入触发代码,右键单击药物表并单击添加新触发器对吗?我得到了错误。我在上面添加了一个新图像,并在上面显示了我的触发语句,我编辑了你给我的触发代码。我认为这是因为处方表,药物 ID 在 int 中,药物表中的药物名称在 nvachar 中。因为我需要使用左外连接来显示药物表中的药物名称。从药物 ID 更改为处方形式的药物名称。那么人呢。 @drewlander
【解决方案2】:

Windows 窗体是基于事件的,因此请尝试将您的问题设置为“当 XXX 发生时,我想做 YYY”。

在你的情况下,如果我理解正确,你想要:

  • 添加药物行时(未编辑,仅添加)
    • 创建与该药物关联的处方行
    • 更新/刷新处方表单以显示新行

您可以参与一些活动,如果您愿意,也可以自己举办活动。

这是否足以让您解决问题,还是需要更多帮助?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2014-09-09
    • 2014-10-11
    相关资源
    最近更新 更多