This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I am writting a programme, which imports data from data base. I want to place all these tables in my own object propeties. All these DataTable properties are filled until Base examBase = Base() is beeing executed, but after this line, the exam.Base.Tests doesnt's exist anymore. What causes the problem?
class Base
{
MySqlConnection myConnection;
MySqlDataAdapter testsDataAdapter;
DataTable testsDataTable;
MySqlDataAdapter questionsDataAdapter;
DataTable questionsDataTable;
MySqlDataAdapter answersDataAdapter;
DataTable answersDataTable;
public Base()
{
string myConnectionString = "Database=Exams;Data Source=localhost;User Id=root;Password=";
myConnection = new MySqlConnection(myConnectionString);
myConnection.Open();
GetTests();
GetQuestions();
GetAnswers();
}
private void GetTests()
{
string testQuery = "SELECT * FROM tests";
testsDataAdapter = new MySqlDataAdapter(testQuery, myConnection);
testsDataTable = new DataTable();
testsDataAdapter.Fill(testsDataTable);
testsDataTable.PrimaryKey = new DataColumn[] { testsDataTable.Columns["TestID"] };
this.Tests = testsDataTable;
}
private void GetQuestions()
{
string questionQuery = "SELECT * FROM questions";
questionsDataAdapter = new MySqlDataAdapter(questionQuery, myConnection);
questionsDataTable = new DataTable();
questionsDataAdapter.Fill(questionsDataTable);
this.Questions = questionsDataTable;
}
private void GetAnswers()
{
string answerQuery = "SELECT * FROM answers";
answersDataAdapter = new MySqlDataAdapter(answerQuery, myConnection);
answersDataTable = new DataTable();
answersDataAdapter.Fill(answersDataTable);
this.Answers = answersDataTable;
}
public DataTable Tests { get; set; }
public DataTable Questions { get; set; }
public DataTable Answers { get; set; }
}
and the exception is firstly seen in GetName() method:
class Test
{
Base examBase;
private List<Question> questions;
public Test(int testID)
{
examBase = new Base();
this.TestID = testID;
GetName();
GetDescription();
GetAuthor();
GetQuestions();
}
private void GetName()
{
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
}
edit
Ok, the object examBase.Tests exists, but there's something with whis Find() method. In my base, in the table "Tests" I have a primary key (column TestID), but I get the KeyMissing exception. Meybe I use this Find() incorrectly?
I think the "Name" field is null. Do a null check before converting to a string:
Change
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
To
if(examBase.Tests.Rows.Find(this.TestID)["Name"] != null)
{
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
}
Failing that
if(examBase.Tests.Rows.Find(this.TestID) != null)
{
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
}
Related
Trying to return value from GetStage_details() methods and bind it to ViewBag.Stage_details but getting error at var result.
Error msg is :
can't implicitly convert type oracle.ManagedDtaAccessclient.oracledatareader to System.Collection.generic.List<Models.Stage_Details."
Any idea how to resolve it show that correct value return from table and bind to ViewBag.Stage_details will be appreciated.
public class Stage_details
{
public int Stage_Cd { get; set; }
public string Stage_Desc { get; set; }
}
public ActionResult Index_shift()
{
ViewBag.Stage_details = new SelectList(GetStage_details(), "Stage_Cd", "Stage_Desc");
}
private List<Stage_details> GetStage_details()
{
List<Stage_details> Stage_detail = new List<Stage_details>();
OracleConnection conn = new
OracleConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());
conn.Open();
string cmdText= "select a.stage_cd,a.stage_desc from Stage_Mst a";
OracleCommand command = new OracleCommand(cmdText,conn);
command.CommandType = CommandType.Text;
var result = command.ExecuteReader();
return result;
}
According to Microsoft documentation, You could read each element from reader and build Stage_detail object inside loop, like the following code :
private List<Stage_details> GetStage_details()
{
List<Stage_details> Stage_detail = new List<Stage_details>();
OracleConnection conn = new
OracleConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());
conn.Open();
string cmdText = "select a.stage_cd,a.stage_desc from Stage_Mst a";
OracleCommand command = new OracleCommand(cmdText, conn)
{
CommandType = CommandType.Text
};
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Stage_detail.Add(new Stage_details { Stage_Cd = (int)reader["stage_cd"], Stage_Desc = reader["stage_desc"].ToString() });
}
}
return Stage_detail;
}
I hope you find this helpful.
i'm trying to practise my c# by doing a little exercise creating a basic ORM.
So i have 3 files, my Main program calling my Model:
public Form1()
{
InitializeComponent();
Pessoa mPessoa = new Pessoa();
mPessoa.First();
MessageBox.Show(mPessoa.nome);
}
My child model class:
class Pessoa:Model
{
public int id;
public string nome;
public string telefone;
public Pessoa()
{
Table = "Pessoa";
Conn = "Principal";
}
}
And my parent Model Class:
class Model:Conn
{
protected string Table;
protected string Conn;
public void First()
{
OpenConnection();
string query = "SELECT * from " + Table + " Where id = 1 limit 1";
DataTable oDT = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(query, connection);
da.Fill(oDT);
foreach (var column in oDT.Columns)
{
}
}
The question is: How can i update the child class variables (id, nome and telefone) based on the results from my parent class funcion?
As you can see, i've tried to use dynamic variable names using that foreach with the columns from the result, but i'm stuck because i dont know how to properly set the values.
I want to add all Id from customer table in combobox using class and this is my connection class connectionClass in which I made a function for selecting data from databse.
The second is my Customer form(this is customer form coding customerForm) in which i call a function which i made in connection class .
but it only showing the last id in customer form and i want all id in combobox
In the select() method you are returning a string,instead of that you need to populate
dataset and bind the data to combobox.
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("customerid", typeof(string));
dt.Columns.Add("contactname", typeof(string));
dt.Load(reader);
regards
chandra
Instead of string return a List of strings as follows:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Fill_Combo();
}
public void Fill_Combo()
{
Connection2DB cst = new Connection2DB();
cmbBoxId.Items.AddRange(cst.Select().ToArray());
}
}
class Connection2DB
{
public List<string> Select()
{
var ids = new List<string>();
try
{
string sqlqry = "select ID from Customer";
SqlCommand cmds = new SqlCommand(sqlqry, _con);
SqlDataReader dr = cmds.ExecuteReader();
while (dr.Read())
{
ids.Add(dr["ID"].ToString());
}
}
catch (Exception ex)
{
// Handle exception here
}
return ids;
}
}
this function only returning only ID from Customer table. I want to multiple data from Customer table using same method. Can you help me in this one??
Normally, this is not how this site works. First, you should ask a specific question, and show what you have done. Then we may help you.
Here I will try to give you two general solutions for working with a database.
Solution 1:
Let`s say you want to display everything retrieved from the database to your windows form.
First, create the DataGridView object let's call it dataGridView1. You can create it using the designer as any other control. then use the codes below:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = GetData();
}
public DataTable GetData()
{
string ConStr = " your connection string "; // Write here your connection string
string query = #"SELECT * FROM Customer"; // or write your specific query
DataTable dataTable = new DataTable();
SqlConnection conn = new SqlConnection(ConStr);
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = null;
try
{
conn.Open();
// create data adapter
da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
}
catch (Exception ex)
{
MessageBox.Show($"Cannot read database: {ex.Message}");
}
finally
{
conn.Close();
if (da != null)
da.Dispose();
}
return dataTable;
}
public void FillDataGrid()
{
Connection2DB cst = new Connection2DB();
dataGridView1.DataSource = cst.GetData();
}
}
Solution 2:
Let's say from your database table you want to extract 3 columns: ID (INT), Name (VARCHAR(100)) and Value (VARCHAR(MAX).
First, create a class:
public class Customer
{
public int ID { get; set; }
public string Nmae { get; set; }
public string Value { get; set; }
}
Create the function which returns the list of Customers:
public List<Customer> GetCustomers()
{
var customers = new List<Customer>();
try
{
string sqlqry = "SELECT ID, Name, Value FROM Customer";
SqlCommand cmds = new SqlCommand(sqlqry, _con); // here _con is your predefined SqlConnection object
SqlDataReader dr = cmds.ExecuteReader();
while (dr.Read())
{
customers.Add(new Customer
{
ID = (int)dr["ID"],
Nmae = dr["Name"].ToString(),
Value = dr["Value"].ToString(),
});
}
}
catch (Exception ex)
{
// Handle exception here
}
return customers;
}
Then you can use this data as you want. For example, to fill your ComboBox with IDs you can use this:
public void Fill_Combo()
{
var customers = GetCustomers();
var ids = customers.Select(x => x.ID.ToString());
cmbBoxId.Items.AddRange(ids.ToArray());
}
I have created a database with 1 table "emp" and have some data in it. Now every time i start the app, i want a list to fetch the data from db and save it in list because i want to perform some calculations like tax and Gross-Salary on data at runtime for display only(don't want to save it in db ). I have tried many times but i am unable to understand how this can be done. This is my code:
Main Class:
static void Main(string[] args)
{
empDB empDB1 = new empDB();
List<emplyee> empLST1 = new List<emplyee>();
if (empLST1 == null)
{
empDB1.loadLST(out empLST1);
}
}
empDB Class:
class empDB
{
private string ConnectionString = #"server=localhost;DATABASE=hris;uid=root;Password=123456;";
internal void loadLST(out List<emplyee> loadedLST)
{
string query = "select name, grade from emp";
try
{
MySqlConnection con = new MySqlConnection(ConnectionString);
con.Open();
MySqlDataReader rdr = null;
MySqlCommand cmd = new MySqlCommand(query, con);
rdr = cmd.ExecuteReader();
while(rdr.Read())
{
List<employee> returnedLst = new List<employee>();
returnedLst.Add(rdr["name"].ToString(), rdr["grade"].ToString());
}
loadedLst = returnedLst;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
I have no idea even if my approach is right or not. I have googled it a few times but i just started working in .net a few days ago so i don't understand how to do it.
Okay i tried this and it also dosn't work:
internal void GetDatabaseList()
{
List<employee> databases = new List<employee>();
MySqlConnection con = new MySqlConnection(ConnectionString);
{
con.Open();
DataTable tbl = con.GetSchema("Databases");
con.Close();
foreach (DataRow row in tbl.Rows)
{
databases.Add(row["hris"].ToString());
}
}
}
static void Main(string[] args)
{
empDB empDB1 = new empDB();
List<emplyee> empLST1 = new List<emplyee>();
**if (empLST1 == null)
{
empDB1.loadLST(out empLST1);
}**
}
this will always be false because you defined empLST1 as a new List, meaning its not null
try this
public class Employee
{
public string Name { get; set; }
public string Grade { get; set; }
}
static void Main(string[] args)
{
empDB empDB1 = new empDB();
List<Employee> empLST1 = new List<Employee>();
empDB1.loadLST(ref empLST1);
}
public class empDB
{
public void loadLst(ref List<Employee> loadedLST)
{
string query = "select name, grade from emp";
try
{
MySqlConnection con = new MySqlConnection(ConnectionString);
con.Open();
MySqlDataReader rdr = null;
MySqlCommand cmd = new MySqlCommand(query, con);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee emp = new Employee();
emp.Name = rdr["name"].ToString();
emp.Grade = rdr["grade"].ToString();
loadedLST.Add(emp);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Assuming, that that employee class looks like this:
class employee
{
public string Name { get; set; }
public string Grade { get; set; }
}
I'd rewrite loadLST like this:
internal List<employee> loadLST()
{
string query = "select name, grade from emp";
// we should dispose IDisposable implementations:
// connection, command and data reader
using (var con = new MySqlConnection(ConnectionString))
{
con.Open();
using (var cmd = new MySqlCommand(query, con))
using (var rdr = cmd.ExecuteReader())
{
// it is hard to maintain manual mapping
// between query results and objects;
// let's use helper like Automapper to make this easier
Mapper.CreateMap<IDataReader, employee>();
Mapper.AssertConfigurationIsValid();
return Mapper.Map<List<employee>>(rdr);
}
}
}
Improvements:
IDisposable implementations must be disposed explicitly (see this and this)
to avoid manual mapping code, which maps the result from data reader and object (employee instance in your case), the code uses Automapper package
exception handling and out parameter are thrown away. There's no need for exception handling and out parameter here, unless you're writing method like TryToDoSomething (and even in that case your method must return bool to indicate the state of operation, and catch only specific exceptions instead of Exception).
Also note, that your code doesn't match naming guidelines (e.g., employee should be Employee).
I am having trouble with my property always being null in my app, but I believe that the problem may be deeper than that. The requirement is to have a data layer class that contains my connection string to my access database. This calls another class which pulls the database information and sets it back to the data layer class. I must then use ONLY the data layer class to get my records. The problem is that my property is always null. Here is the code for the data layer class:
{
class CustomerDL
{
OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CIS3341.accdb;");
string names;
public void initializeConnection()
{
Customer.initializeConnection(aConnection);
}
public string getNames
{
get { return names; }
set { names = value; }
}
}
}
And here is the other class:
class Customer
{
static OleDbConnection aConnection = null;
string names;
public static void initializeConnection(OleDbConnection aDbConnection)
{
aConnection = aDbConnection;
aConnection.Open();
getNames();
}
public static void getNames()
{
CustomerDL aCustomer = new CustomerDL();
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
if (aConnection.State == ConnectionState.Closed)
{
aConnection.Open();
}
OleDbCommand cmd = aConnection.CreateCommand();
OleDbDataReader dbReader = null;
cmd.CommandText = "SELECT CustomerName FROM Customer";
dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
aCustomer.getNames += (string)dbReader["CustomerName"].ToString() + "\r\n";
}
dbReader.Close();
//return aCustomer ;
}
}
Now when i use this code on my form:
public partial class Form1 : Form
{
CustomerDL customer = new CustomerDL();
public Form1()
{
InitializeComponent();
customer.initializeConnection();
string fast = customer.getNames;
richTextBox1.Text = fast;
}
customer.getNames; is always null. Any ideas?
You aren't assigning anything to the proper instance of CustomerDL.
customer.getNames never gets accessed whatsoever. You are initializing your connection, but in that method you use a new CustomerDL: CustomerDL aCustomer = new CustomerDL();. You have to provide that instance to the static method for it to do something.
in CustomerDL the member names has the default value null, you can initialize it with string names = string.Empty;
You really should consolidate the Customer and CustomerDL classes into one class. There is too much duplication. So instead of having CustomerDL call Customer, just put the getnames() code in your CustomerDL class. And scrap all the static modifiers. By your form example, you are instantiating CustomerDL and calling methods on it. Make the class and its methods non-static, and this will work much better for you.
One of the problems that is preventing you from figuring this one out is your naming conventions...
You have both properties and methods named the same (I would leave the word "get" off of properties).
You have a "CustomerDL" object that you named "customer". The problem is you also have a "Customer" class.
You have a static method coded to do what you want, but you are never calling it.
IMHO if you take a little more care in your naming conventions, it will be a lot easier to troubleshoot these kinds of issues....There are a few things wrong with the code, but I quickly gave fixing it a shot. Hope it helps:
class CustomerDL
{
OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CIS3341.accdb;");
public string GetNames()
{
string NamesToReturn = "";
try
{
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
if (aConnection.State == ConnectionState.Closed)
{
aConnection.Open();
}
OleDbCommand cmd = aConnection.CreateCommand();
OleDbDataReader dbReader = null;
cmd.CommandText = "SELECT CustomerName FROM Customer";
dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
NamesToReturn += (string)dbReader["CustomerName"].ToString() + "\r\n";
}
dbReader.Close();
catch(Exception ex)
{
}
finally
{
aConnection.Close(); //makes sure it closes...
}
return NamesToReturn;
}
}
Then you can do this:
class Customer
{
private CustomerDL customerData = new CustomerDL();
public string Names { get; set; }
public string FillNames()
{
this.Names = customerData.GetNames();
}
}
public partial class Form1 : Form
{
Customer customer = new Customer();
public Form1()
{
InitializeComponent();
customer.FillNames();
richTextBox1.Text = customer.Names;
}
}
Note: This code is very crude and I have not double checked it, but I beleive it will get you pointed in the right direction.