Я хочу вызвать метод из другой формы - PullRequest
0 голосов
/ 31 октября 2019

Я хочу, чтобы мой TextBox брал информацию и запускал код из бизнес-объекта из другой формы. Я хочу, чтобы он запускался при каждом нажатии кнопки.

У меня проблемы с инициализацией кода. В форме theStudent.cs все работает нормально, я просто хочу добавить метод SelectDB () в StudentForm.

namespace SchoolReg{

public partial class StudentForm : Form
{

    public StudentForm()
    {

        InitializeComponent();


    }

    private void StudentForm_Load(object sender, EventArgs e)
    {
        //ignore
    }



    private void StudentButton_Click(object sender, EventArgs e)
    {

        Student s1;
        s1 = new Student();
        txtboxIDStu.Text = s1.SelectDB(int);

    }

    private void txtboxIDStu_TextChanged(object sender, EventArgs e)
    {
        //ignore
    }
}


 namespace SchoolReg{


class Student : person
{


    private double gpa;




    //constructors 
    public Student():base()
    {

        gpa = 0;

    }

    public Student(int id, string fn, string ln,  Address a1, string em, double gp) : base(id,fn,ln,a1,em)
    {

        gpa = gp;

    }

    //behaviors
    public void setgpa(double gp) { gpa = gp; }
    public double getgpa() { return gpa; }




    //display 
    public void Display()
    {
        base.display();
        Console.WriteLine("===================================");
        Console.WriteLine("Gpa = " + gpa);
        Console.WriteLine("===================================");

    }


    public System.Data.OleDb.OleDbDataAdapter OleDbDataAdapter2;
    public System.Data.OleDb.OleDbCommand OleDbSelectCommand2;
    public System.Data.OleDb.OleDbCommand OleDbInsertCommand2;
    public System.Data.OleDb.OleDbCommand OleDbUpdateCommand2;
    public System.Data.OleDb.OleDbCommand OleDbDeleteCommand2;
    public System.Data.OleDb.OleDbConnection OleDbConnection2;
    public string cmd;

    public Student(int id)
    {
        SelectDB(id);
    }

    public void DBSetup()
    {
        OleDbDataAdapter2 = new System.Data.OleDb.OleDbDataAdapter();
        OleDbSelectCommand2 = new System.Data.OleDb.OleDbCommand();
        OleDbInsertCommand2 = new System.Data.OleDb.OleDbCommand();
        OleDbUpdateCommand2 = new System.Data.OleDb.OleDbCommand();
        OleDbDeleteCommand2 = new System.Data.OleDb.OleDbCommand();
        OleDbConnection2 = new System.Data.OleDb.OleDbConnection();


        OleDbDataAdapter2.DeleteCommand = OleDbDeleteCommand2;
        OleDbDataAdapter2.InsertCommand = OleDbInsertCommand2;
        OleDbDataAdapter2.SelectCommand = OleDbSelectCommand2;
        OleDbDataAdapter2.UpdateCommand = OleDbUpdateCommand2;

        OleDbConnection2.ConnectionString = "Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database L" +
        "ocking Mode=1;Data Source=C:\\Users\\nicho\\OneDrive\\Desktop\\Database c#\\RegistrationMDB.mdb;J" +
        "et OLEDB:Engine Type=5;Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:System datab" +
        "ase=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Mode=S" +
        "hare Deny None;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet " +
        "OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repai" +
        "r=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1";   



    }

    public void SelectDB(int id)
    {
        DBSetup();
        cmd = "Select * from Students where ID =" + id;
        OleDbDataAdapter2.SelectCommand.CommandText = cmd;
        OleDbDataAdapter2.SelectCommand.Connection = OleDbConnection2;
        Console.WriteLine(cmd);

        try
        {
            OleDbConnection2.Open();
            System.Data.OleDb.OleDbDataReader dr;
            dr = OleDbDataAdapter2.SelectCommand.ExecuteReader();

            dr.Read();

            Id = id;
            setfname(dr.GetValue(1) + "");
            setlname(dr.GetValue(2) + "");
            Address a1 = new Address(dr.GetValue(3) + "", dr.GetValue(4) + "", dr.GetValue(5) + "", long.Parse(dr.GetValue(6)+""));
            setAddr(a1);
            setemail(dr.GetValue(7) + "");
            setgpa(Double.Parse(dr.GetValue(8) + ""));

        }
        catch(Exception ex)
        {
            Console.WriteLine(ex);
        }
        finally
        {
            OleDbConnection2.Close();
        }
        Console.WriteLine("===================================");
        getSchedule();
        Console.WriteLine("===================================");

    }

/ Я думаю, что запутался в форме StudentForm. Я заранее извиняюсь, потому что чувствую, что ответ прост. Также из-за грязного макета я обычно не публикую. /

1 Ответ

2 голосов
/ 31 октября 2019

Хорошо, вы здесь довольно близко, но вам не хватает нескольких шагов

    private void StudentButton_Click(object sender, EventArgs e)
    {

    Student s1;
    s1 = new Student();
    txtboxIDStu.Text = s1.SelectDB(int);

    }

должно быть примерно так

    private void StudentButton_Click(object sender, EventArgs e)
    {
        string studentIdString = this.TEXTBOXNAME.Text; // This fetches the string from the input box and stores it. Replace TEXTBOXNAME with the name of your textbox that holds the ID.
        bool inputIsNumber = Int32.TryParse(studentIdString , out studentIdInt); //Int32 TryParse tries to convert a given string into an integer. If it works inputIsNumber will be true, and the studentIdInt will be available as a variable. 
        if(inputIsNumber == false){
            txtboxIDStu.Text = "Please enter a valid number";
            return; //Bail out if we can't turn the string into a number
        }
        Student s1 = new Student(studentIdInt); //We're going to use the ID we created to build the student using the constructor

        txtboxIDStu.Text = s1.fname + " " + s1.lastname; // By the time we've gotten here the constructor has fired, which also fired SelectDB() on that student. This just prints the name of the student, but if you want to improve this look up "Overrides" and create a ToString() override on your Student class.

    }

У вас уже есть конструктор для ученикаэто берет Id, который именно то, что нам нужно.

    public Student(int id)
    {
       SelectDB(id); 
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...