将数据插入一个表后,我也希望该数据自动出现在另一个表中

时间:2014-01-19 17:41:29

标签: c# sql database select

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

对于处方形式的字段药物名称,它原来是药物ID,但我使用左外部联接显示药物表中存在的药物名称。

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

处方和药物表格 output

处方表 prescriptiontable

药剂表 medicationtable

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

//处方表格代码

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());
            }
        }
    }
}

MEDICATION FORM代码。这是我在insertprescription触发器中的代码。

ALTER TRIGGER insertPrescriptions ON dbo.MEDICATION INSERT INSERT IN INSERT INTO处方(prescriptionID,药物ID)选择MedicationID,MedicationName来自插入的GO

    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);
        }

    }
}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

在您的情况下,如果我理解正确,您需要:

  • 添加Medication行时(未编辑,仅添加)
    • 创建链接到该“药物”的处方行
    • 更新/刷新处方表单以显示新行

您可以加入一些活动,如果您愿意,可以自己举办活动。

这是否足以帮助您解决问题,或者您希望获得更多帮助?