I want to call a method from a different form - c#

I want my TextBox to take information and run the code from a business object from a different form. I want it to run whenever the button is clicked.
I am having problems initializing the code. In theStudent.cs form it works fine I just want to pull the SelectDB() method into the 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("===================================");
}
/I think I am messing up in the StudentForm form. I'm sorry in advance because I feel like the answer is simple. Also for the messy layout, I don't usually post./

Okay, you're pretty close here, but you're missing a few steps
private void StudentButton_Click(object sender, EventArgs e)
{
Student s1;
s1 = new Student();
txtboxIDStu.Text = s1.SelectDB(int);
}
should be something like this
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.
}
You already have a constructor for student that takes an Id, which is exactly what we need.
public Student(int id)
{
SelectDB(id);
}

Related

Cannot implicitly convert type 'System.Collections.Generic.List<ValueObjectLayer.booksVAL>' to 'int'

I'm trying to make a 3 layered C# Library Management project.
I'm trying to select a book from bookDAL (dataacceslayer) through booksBLL(businesslogiclayer and show it on winforms.
i get this error message on BLL
error
DAL:
public static List<booksVAL> BookSelect(string x)
{
List<booksVAL> sonuc = new List<booksVAL>();
OleDbCommand cmdkitaplistele = new OleDbCommand("select * from books where id = " + Int32.Parse(x) + " ", dbConnection.conn); //
if (cmdkitaplistele.Connection.State != ConnectionState.Open) // bağlantı açık değise
{
cmdkitaplistele.Connection.Open(); // bağlantıyı aç
}
OleDbDataReader dr = cmdkitaplistele.ExecuteReader(); // sorgu sonuçlarını data reader ile oku
while (dr.Read())
{
booksVAL book = new booksVAL();
book.bookId = int.Parse(dr["id"].ToString());
book.bookName = dr["bookname"].ToString();
book.bookAuthor = dr["authorname"].ToString();
book.bookPagecount = dr["pagecount"].ToString();
book.bookDatepublished = dr["datepublished"].ToString();
book.bookIsavailable = dr["isavailable"].ToString();
book.bookCategory = dr["category"].ToString();
sonuc.Add(book);
}
dr.Close();
return sonuc;
}
BLL:
public static int BookSelect(string x)
{
return booksDAL.BookSelect(x);
Form:
public partial class bookupdateForm : Form
{
booksForm f1;
public bookupdateForm(booksForm frm1)
{
InitializeComponent();
this.f1 = frm1;
booksBLL.BookSelect(f1.selectedlabel.Text); // selectedlabel comes from another form, it works
}
}
Problem is here:
public static int BookSelect(string x)
{
return booksDAL.BookSelect(x);
}
Change return type int to List<booksVAL>:
public static List<booksVAL> BookSelect(string x)
{
return booksDAL.BookSelect(x);
}

How to get rid of namespace.Classname on call of display()?

Is there a way to get rid of practise.AcademicProgram in the output when the display() is called for an object initialized by the parameterized constructor. In my code below this occurs when s2.Display(); is executed.
Below is my working code for the same:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practise
{
public class AcademicProgram
{
//Memnber variables
private int programCode;
private string programName;
private int programCredits;
//Properties for reading and writting the values of private fields
public int ProgramCode { get => programCode; set => programCode = value; }
public string ProgramName { get => programName; set => programName = value; }
public int ProgramCredits { get => programCredits; set => programCredits = value; }
//Default Constructor
public AcademicProgram()
{
}
//Parameterized Constructor
public AcademicProgram (int programCode, string programName, int programCredits)
{
this.programCode = programCode;
this.programName = programName;
this.programCredits = programCredits;
}
public void DisplayResults()
{
Console.WriteLine("Program Code: {0}\nProgram Name: {1}\nProgram Credits: {2}\n", programCode, programName, programCredits);
Console.WriteLine();
}
}
public class Instructor
{
//Member variables
public string forename;
public string surname;
public int identificationNumber;
public AcademicProgram academicProgram;
//Default Constructor
public Instructor()
{
this.forename = string.Empty;
this.surname = string.Empty;
this.identificationNumber = 0;
this.academicProgram = null;
}
//Parameterized Constructor
public Instructor(string forename, string surname, int identificationNumber, AcademicProgram academicProgram)
{
this.forename = forename;
this.surname = surname;
this.identificationNumber = identificationNumber;
this.academicProgram = academicProgram;
}
// Member Function to display values of member variables on Console.
public void Display()
{
Console.WriteLine(this.forename + ", " + this.surname + ", " + this.identificationNumber + ", " + this.academicProgram);
Console.WriteLine();
}
//Driver function
static void Main(string[] args)
{
//Instantiating object to call non-static member method
Instructor p = new Instructor();
p.Go();
Console.ReadKey();
}
//Non-static Member function
public void Go()
{
//Instantiating object without passing any values on runtime.
Instructor s = new Instructor();
//Instantiating object of AcademicProgram class without passing any values on runtime.
AcademicProgram progName = new AcademicProgram ();
//Set the values of fields using properties
progName.ProgramCode = 8230;
progName.ProgramName = "Systems Development: Cocnepts and Analysis";
progName.ProgramCredits = 4;
// Instantiating object while providing values on runtime.
Instructor s2 = new Instructor("Eddie ", "Jessup", 2394589, progName);
//Call to display method
s.Display();
s2.Display();
progName.DisplayResults();
}
}
}
Which gives an output shown here
Aside from override ToString(), I was able to fix it by a simple fix in display() of Instructor class as below:
public void Display()
{
Console.WriteLine(this.forename + ", " + this.surname + ", " + this.identificationNumber + ", " + this.academicProgram.ProgramCode + ", " + this.academicProgram.ProgramName + ", " + this.academicProgram.ProgramCredits);
Console.WriteLine();
}

Index out of range with less than 6 rows of data

Small brief of what i need and what i currently have
I connect to a database and get my data from it and i get ( Name , LongNumber) and basically i have an event (action) that fires when the event occurs (this action gives me a LongNumber aswell).
I need to compare the LongNumbers between the one i got from the event (action) and the one from my database, and if they are similar i take the name and use it.
for example Hello, Alex ( alex is taken from the database)
Issue
I get Index out of range, and using my logic all texts will change what i'm trying to achieve is to change the text to the name of the person that got the Long number the same as the longNumber from the event
Code: Gettings Data from the database
using UnityEngine;
using System.Collections;
using MySql.Data.MySqlClient;
using System;
using System.Linq;
using System.Collections.Generic;
public class MySqlTestScript : MonoBehaviour
{
private static MySqlTestScript _instnace;
public static MySqlTestScript sharedInstance()
{
return _instnace;
}
string row = "";
public string host = "*****";
public string database = "*******";
public string usrename= "*******";
public string password = "******";
public List<Data> userData = new List<Data>();
Data data;
void Awake()
{
_instnace = this;
}
// Use this for initialization
public void Start()
{
GetDataFromDatabase();
}
public string GetDataFromDatabase()
{
string myConnectionString = "Server="+host+";Database="+database+";Uid="+usrename+ ";Pwd="+password+";";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Users";
MySqlDataReader Reader;
try
{
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
for (int i = 0; i < Reader.FieldCount; i++)
{
//rfid_tags.Add (Reader.GetString("UserName"));
//rfid_tags.Add(Reader.GetString("RFID_Tag"));
data = new Data(Reader.GetString("UserName"), Reader.GetString("RFID_Tag"));
userData.Add(data);
// ws.DomainUrl = reader.GetString("DomainUrl");
// rfid_tags.Add(Reader.GetValue(i).ToString() + ",");
// row += Reader.GetValue(i).ToString() + ", ";
}
Debug.Log(row);
}
}
catch (Exception x)
{
Debug.Log(x.Message);
return x.Message;
}
connection.Close();
return row;
}
}
public class Data {
public string username { get; set; }
public string rfid { get; set; }
public Data(string _name, string _rfid)
{
username = _name;
rfid = _rfid;
}
public void SetUserName(string _userName) { username = _userName; }
public void SetRFID(string _rfid) { rfid = _rfid; }
}
Code for Comparing the values from the event(action) and showing the text
void OnTagsReported(ImpinjReader sender, TagReport report)
{
Debug.Log("OnTagsReported");
// This event handler is called asynchronously
// when tag reports are available.
// Loop through each tag in the report
// and print the data.
foreach (Tag tag in report)
{
Debug.Log(tag.Epc);
// Debug.Log(MySqlTestScript.sharedInstance().rfid_tags[0]);
Debug.Log("STEP ONE");
for (int i = 0; i < MySqlTestScript.sharedInstance().userData.Count; i++)
{
Debug.Log("STEP TWO");
if (tag.Epc.ToString().Trim() == MySqlTestScript.sharedInstance().userData[i].rfid)
{
Debug.Log("STEP THREE");
// TODO References the Name
Loom.QueueOnMainThread(() => {
namesTxt[i].text = MySqlTestScript.sharedInstance().userData[i].username;
});
}
}
As you can see in the Event script it's so unflexible and it gives index out of range if my database has less than 6 rows. I need to make it more friendly and generic
Any help would be appreciated and i hope my question is clear Thank you :)!
This should make more sense:
Database:
using UnityEngine;
using System.Collections;
using MySql.Data.MySqlClient;
using System;
using System.Linq;
using System.Collections.Generic;
public class MySqlTestScript : MonoBehaviour
{
private static MySqlTestScript _instnace;
public static MySqlTestScript sharedInstance()
{
return _instnace;
}
string row = "";
public string host = "*****";
public string database = "*******";
public string usrename= "*******";
public string password = "******";
public List<AppUser> users = new List<AppUser>();
void Awake()
{
_instnace = this;
}
// Use this for initialization
public void Start()
{
GetDataFromDatabase();
}
public string GetDataFromDatabase()
{
string myConnectionString = "Server=" + host + ";Database=" + database + ";Uid=" + usrename + ";Pwd=" + password + ";";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM users";
MySqlDataReader Reader;
try
{
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
users.Add(new AppUser() {
username = Reader.GetString("UserName").Trim(),
rfid = Reader.GetString("longNumbers ").Trim()
});
}
}
catch (Exception x)
{
Debug.Log(x.Message);
return x.Message;
}
connection.Close();
return row;
}
}
Data object:
public Class AppUser
{
public string rfid { get; set; }
public string username { get; set; }
}
Event/data comparison:
void OnTagsReported(ImpinjReader sender, TagReport report)
{
Debug.Log("OnTagsReported");
// This event handler is called asynchronously
// when tag reports are available.
// Loop through each tag in the report
// and print the data.
foreach (Tag tag in report)
{
Debug.Log(tag.Epc);
List<AppUser> appUsers = MySqlTestScript.sharedInstance().users;
int numUsers = appUsers.Count;
Debug.Log(numUsers);
for (int i = 0; i < numUsers; i++)
{
if (tag.Epc.ToString().Trim() == appUsers[i].rfid)
{
// TODO References the Name
Loom.QueueOnMainThread(() => {
if (i < namesTxt.Count) namesTxt[i].Text = appUsers[i].username; //assumes textnames is a "List" of textboxes and is already populated with instances of text1, text2 text3 etc. The if is just to guard against there being more rows in the DB than textboxes
});
}
}
}
}
One way to get around this is to wrap each of your cases in another if statement to check if the database has that many rows
if (MySqlTestScript.sharedInstance().longNumbers.Length > 1) {
if (tag.Epc.ToString().Trim() == MySqlTestScript.sharedInstance().longNumbers[0].ToString()) {
if(MySqlTestScript.sharedInstance().userNames[0] != null)
txt1.text = "Hello "+ MySqlTestScript.sharedInstance().userNames[0];
}
}
}
else {
txt1.text = "";
}
This will avoid your index out of range exception. In each wrapping case you will need to increment the comparison to be 1, 2, 3, etc.
It is not the prettiest solution but will avoid the exception. Another option would be to wrap in a try-catch block. Again not the prettiest but would accomplish the task.

C# Error: “Fill: SelectCommand.Connection property has not been initialized.”

I have problem with this error:
C# Error: “Fill: SelectCommand.Connection property has not been
initialized.”
I lloked ower others threads, but people have it built their clients little different and it didnt help.
I dont know, why this error showed. And I suppose its wrong somewhere at SelectOsoba.
I need to show data in DataGridView.
my code is :
class Vrstva
{
public static SqlConnection myConnection;
public static string connstr;
static DataTable t;
public static void createConnect1()
{
connstr = ConfigurationSettings.AppSettings["local1"];
Vrstva.myConnection = new SqlConnection(connstr);
}
public static void createConnect2()
{
connstr = ConfigurationSettings.AppSettings["local2"];
Vrstva.myConnection = new SqlConnection(connstr);
}
public static void createConnect3()
{
connstr = ConfigurationSettings.AppSettings["local3"];
Vrstva.myConnection = new SqlConnection(connstr);
}
public static void openConn()
{
Vrstva.myConnection.Open();
}
public static void closeConn()
{
Vrstva.myConnection.Close();
}
public static SqlDataAdapter Query(string command)
{
return new SqlDataAdapter(command, Vrstva.myConnection);
}
public static void NonQuery(string command)
{
SqlCommand Command = new SqlCommand(command, Vrstva.myConnection);
Command.ExecuteNonQuery();
}
public static bool login1(string login, string password)
{
string login1 = ConfigurationSettings.AppSettings["login1"];
string password1 = ConfigurationSettings.AppSettings["password1"];
if (login == login1 && password == password1)
{
return true;
}
return false;
}
public static bool login2(string login, string password)
{
string login1 = ConfigurationSettings.AppSettings["login2"];
string password1 = ConfigurationSettings.AppSettings["password2"];
if (login == login1 && password == password1)
{
return true;
}
return false;
}
public static bool login3(string login, string password)
{
string login1 = ConfigurationSettings.AppSettings["login3"];
string password1 = ConfigurationSettings.AppSettings["password3"];
if (login == login1 && password == password1)
{
return true;
}
return false;
}
////vypis tabulku prislusniku
public static DataTable SelectOsoba()
{
t = new DataTable();
Query("Select * from Osoba;").Fill(t);
return t;
}
//Insert
public static void PridejOsoba(string Jmeno, string Prijmeni, string Povolani, int Poc_Det)
{
NonQuery("Insert into Osoba(Jmeno,Prijmeni,Povolani,Poc_Det) values('" + Jmeno + "','" + Prijmeni + "','" + Povolani + "','" + Poc_Det + "');");
}
}
This error is most likely being thrown because your connection in this line:
return new SqlDataAdapter(command, Vrstva.myConnection);
has not been initialized.
You have to call one of your createConnectX() methods before trying to query.

How can I pass my getters and setters parameters to connection class?

I assigned the textbox inputs to getters and setters also created one connection class. How can I pass my getters and setters parameters to connection class so I can use it inside my mainform.
MemberClass
private string srDatabase = "";
private string srID = "";
private string srPass = "";
public string SDB
{
get
{
return srDatabase;
}
set
{
srDatabase= value;
}
}
public string SID
{
get
{
return srID ;
}
set
{
srID = value;
}
}
public string SPassword
{
get
{
return srPass ;
}
set
{
srPass = value;
}
}
ConnectionClass
class Connection
{
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(dataSource) && !string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
con = new OracleConnection("Data Source=" + dataSource + ";User Id=" + userName.ToUpper() + ";Password=" + password + ";");
return con;
}
return con;
}
}
MainForm
UserMembers = new UserMembers();
txtSrcUserDatabase.Text = src.srDatabase ;
txtSrcUserID.Text=src.srID.ToUpper();
txtSrcUserPassword.Text = src.srPass;
OracleConnection conn1 = Connection.GetConnection() // **here error**
conn1.Open();
using (OracleCommand Names = new OracleCommand("SELECT TABLE_NAME FROM USER_TABLES ORDER BY TABLE_NAME", conn1))
{
using (OracleDataReader reader = Names.ExecuteReader())
{
while (reader.Read())
{
//Do something
}
}
}
Your method GetConnection requires three parameters. You need to pass them to the method.
UserMembers src = new UserMembers();
src.srDatabase =txtSrcUserDatabase.Text;
src.srID = txtSrcUserID.Text.ToUpper();
src.srPass = txtSrcUserPassword.Text;
OracleConnection conn1 = Connection.GetConnection(src.srDatabase, src.srID, src.srPass)
conn1.Open();
......
Or you could pass the instance of UserMembers to the GetConnection method creating an overload of GetConnection like this
class Connection
{
// the first overload that takes 3 string parameters
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
....
}
// The second overload that takes an instance of UserMembers
public static OracleConnection GetConnection(UserMembers src )
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(sr.srDatabase) && !string.IsNullOrWhiteSpace(sr.srID) && !string.IsNullOrWhiteSpace(sr.srPass))
{
con = new OracleConnection("Data Source=" + sr.srDatabase + ";User Id=" + sr.srID.ToUpper() + ";Password=" + sr.Pass + ";");
}
return con;
}
}
As a side note. If you need the srID member to be always in upper case then move this logic in the setter property, and you could stop to worry about the proper formatting of this member when you try to read it back
public string SID
{
get { return srID ; }
set { srID = value.ToUpper(); }
}

Categories