Turning a database into a physical view using wpf xaml - c#

So, I'm trying to connect to my database in a DataGrid view
In DatabaseDisplay.xaml.cs:
DataBaseConnection _dbView;
DataSet _dataSet;
DataRow _data;
public DatabaseDisplay()
{
InitializeComponent();
DataContext = new DataBaseConnection();
}
In DataBaseConnection.cs:
class DataBaseConnection
{
private string _dbConnector;
System.Data.SqlClient.SqlConnection _connectionToDb;
private System.Data.SqlClient.SqlDataAdapter _dataAdapter;
public DataBaseConnection(string dbConnector)
{
this._dbConnector = dbConnector;
}
// Get the data set generated by the sqlStatement
public DataSet GetDataSet(string sqlStatement)
{
_dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlStatement, _connectionToDb);
var dataSet = new DataSet();
_dataAdapter.Fill(dataSet);
return dataSet;
}
public void AddValues()
{
OpenConnection();
_dbConnector.Insert(1, "abc");
}
}
I am trying to connect to my database, and then populate the values in DataBaseDisplay.xaml which is pretty much a DataGrid and a Binding - nothing too fancy.
My issue is that when I try and pull DataContext = new DataBaseConnection(); it is giving me the error of: there is no argument given that corresponds to the required formal parameter 'dbConnector' of 'DataBaseConnection.DataBaseConnection'
Can anyone help me here?

Related

How to update data from child class variables using parent class function?

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.

Insert data in comboBox from database

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

bind data on dropdownlist

I'm trying run this code
private void LoadProdName()
{
con.Open();
cmd = new SqlCommand(#"SELECT productName
FROM Products3
WHERE productType = #Type",con);
cmd.Parameters.AddWithValue("#Type",ddlProducts.SelectedItem.Value.ToString());
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
ddlProdName.DataSource = dt;
ddlProdName.DataBind();
con.Close();
}
my selectedIndesChange codes:
protected void ddlProducts_SelectedIndexChanged(object sender, EventArgs e)
{
LoadProdName();
}
which uses the value of my first dropdownlist.My problem is whenever I select a ProductType on my dropdownlist it will fill my second DDL with the select query but I am not getting any data at all from my second dropdownlist.
Now I'm getting some progress.
This is what I get now:
For cascade drowdownlist you must do a postback in your dropdownlist event "OnSelectedIndexChanged" or use an AJAX call to your method
try this guide: http://www.aspsnippets.com/Articles/Creating-Cascading-DropDownLists-in-ASP.Net.aspx
try this code after your query
ddlProdName.DataSource = cmd.ExecuteReader();
ddlProdName.DataTextField = "productName";
ddlProdName.DataValueField = "productName"; //or productId
ddlProdName.DataBind();
In your case, you will want to do:
ddlProdName.DataTextField = "productName"; //this is the name of column that's in your datatable.
ddlProdName.DataValueField = "productName";
If you are specifying anything other than collection of simple data type as the data source, you will need to specify the DisplayMember and ValueMember (in winforms) and DataTextField and DataValueField (in webforms, from Sergio's answer) property of the combobox so that it knows which property to display and which should be used as value.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
DataColumn prodName = new DataColumn("Products");
dt.Columns.Add(prodName);
dt.Rows.Add("a");
dt.Rows.Add("b");
dt.Rows.Add("c");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Products";
comboBox1.ValueMember = "Products";
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

C# access List after return

I'm a noob with C# but I'm trying to create a simple code for connecting to my mysql database (most of the code I got from google). So I have this part where something from the database is selected and stored in a list. Now I want to access this from another class but I have no idea how to do that and I couldn't find the answer on google either (this thread also didn't worked for me: Access List from another class) so can anyone please help me?
Here's the particular code:
public List<string>[] Select()
{
string query = "SELECT * FROM users";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["test"] + "");
list[2].Add(dataReader["balance"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
Class containing your original method:
public class YourClass
{
public List<string>[] Select()
{
string query = "SELECT * FROM users";
//Create a list to store the result
List<string>[] list = new List<string>[3];
///
/// you original implementation here
///
}
}
Here Class where you use your method:
public class UsingClass
{
private YourClass _yourClass;
public UsingClass()
{
_yourClass = new YourClass();
}
private void SomeUsingMethod()
{
List<string>[] list = _yourClass.Select();
}
}
Seriously I think the way you've structured the data here, is strange.
You're creating an array of a objects, where the object is a List of string:
List<string>[] list = new List<string>[3];
You want to be thinking in objects; create a class that represents the data; in this case User. Something like this:
public class User
{
public string Id { get; set; }
public string Test { get; set; }
public string Balance { get; set; }
}
So personally I'd do the following:
Create a class that represents each user record.
Create a variable to hold a list of users.
Read from MySql and assign each record to a new User object.
Add the user to the list.
Return the list.
Change the return type of your Select method to be List<User> like this:
public List<User> Select() {
Then amend the rest of the method to create and return list of users.
public List<User> Select() {
List<User> list = new List<User>();
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
User user = new User();
user.Id = dataReader["id"].toString();
user.Test = dataReader["test"].toString();
user.Balance = dataReader["balance"].toString();
list.Add(user);
}
dataReader.Close();
this.CloseConnection();
}
return list;
}
Then you can use your list something like this:
ClassThatContainsSelectMethod yourDBObject = new ClassThatContainsSelectMethod();
List<User> users = yourDBObject.Select();
foreach (User user in users)
{
Console.WriteLine(user.Id, user.Test, user.Balance);
}
This code of course could be better structured with factories and error/null checks but it should get you going in the right direction.
There are multiple ways to share data from classes.One of them is defining a property for the desired list and then accsess it. Lets say you have class data
class DataString
{
private string data = "data";
public string Data
{
get { return data}
set { data = value }
}
}
and
class Program
{
static void Main()
{
DataString dataStr = new DataString();
// Assigning the dataStr property causes the 'set' accessor to be called.
dataStr.Data = "some string";
// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine(dataStr.Data); //this will display "some string"
}
}
You could the same way create a list class with your desired functions and variables and modiffy them with methods and access them with properties.

Trouble with my property using C#

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.

Categories

Resources