Databinding in combo box - c#

I have two forms, and a class, queries return in Stored procedure.
-- Stored Procedure:
ALTER PROCEDURE [dbo].[Payment_Join]
#reference nvarchar(20)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT p.iPaymentID
, p.nvReference
, pt.nvPaymentType
, p.iAmount
, m.nvMethod
, u.nvUsers
, p.tUpdateTime
FROM Payment p
, tblPaymentType pt
, tblPaymentMethod m
, tblUsers u
WHERE p.nvReference = #reference
and p.iPaymentTypeID = pt.iPaymentTypeID
and p.iMethodID = m.iMethodID
and p.iUsersID = u.iUsersID
END
// payment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace Finance {
class payment {
string connection = global::Finance.Properties.Settings.Default.PaymentConnectionString;
#region Fields
int _paymentid = 0;
string _reference = string.Empty;
string _paymenttype;
double _amount = 0;
string _paymentmethod;
string _employeename;
DateTime _updatetime = DateTime.Now;
#endregion
#region Properties
public int paymentid
{
get { return _paymentid; }
set { _paymentid = value; }
}
public string reference
{
get { return _reference; }
set { _reference = value; }
}
public string paymenttype
{
get { return _paymenttype; }
set { _paymenttype = value; }
}
public string paymentmethod
{
get { return _paymentmethod; }
set { _paymentmethod = value; }
}
public double amount
{
get { return _amount;}
set { _amount = value; }
}
public string employeename
{
get { return _employeename; }
set { _employeename = value; }
}
public DateTime updatetime
{
get { return _updatetime; }
set { _updatetime = value; }
}
#endregion
#region Constructor
public payment()
{
}
public payment(string refer)
{
reference = refer;
}
public payment(int paymentID, string Reference, string Paymenttype, double Amount, string Paymentmethod, string Employeename, DateTime Time)
{
paymentid = paymentID;
reference = Reference;
paymenttype = Paymenttype;
amount = Amount;
paymentmethod = Paymentmethod;
employeename = Employeename;
updatetime = Time;
}
#endregion
#region Methods
public void Save()
{
try
{
SqlConnection connect = new SqlConnection(connection);
SqlCommand command = new SqlCommand("payment_create", connect);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#reference", reference));
command.Parameters.Add(new SqlParameter("#paymenttype", paymenttype));
command.Parameters.Add(new SqlParameter("#amount", amount));
command.Parameters.Add(new SqlParameter("#paymentmethod", paymentmethod));
command.Parameters.Add(new SqlParameter("#employeename", employeename));
command.Parameters.Add(new SqlParameter("#updatetime", updatetime));
connect.Open();
command.ExecuteScalar();
connect.Close();
}
catch
{
}
}
public void Load(string reference)
{
try
{
SqlConnection connect = new SqlConnection(connection);
SqlCommand command = new SqlCommand("Payment_Join", connect);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Reference", reference));
//MessageBox.Show("ref = " + reference);
connect.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
this.reference = Convert.ToString(reader["nvReference"]);
// MessageBox.Show(reference);
// MessageBox.Show("here");
// MessageBox.Show("payment type id = " + reader["nvPaymentType"]);
// MessageBox.Show("here1");
this.paymenttype = Convert.ToString(reader["nvPaymentType"]);
// MessageBox.Show(paymenttype.ToString());
this.amount = Convert.ToDouble(reader["iAmount"]);
this.paymentmethod = Convert.ToString(reader["nvMethod"]);
this.employeename = Convert.ToString(reader["nvUsers"]);
this.updatetime = Convert.ToDateTime(reader["tUpdateTime"]);
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Check it again" + ex);
}
}
#endregion
}
}
I have already binded the combo box items through designer,
When I run the application I just get the reference populated in form 2 and combo box just populated not the particular value which is fetched. New to c# so help me to get familiar

Assuming WinForms...
The ComboBox control has three properties to be used while using DataBinding.
DataSource;
DisplayMember;
ValueMember.
DataSource
A data source can be a database, a Web service, or an object that can later be used to generate data-bound controls. When the DataSource property is set, the items collection cannot be modified.
DisplayMember
The controls that inherit from ListControl can display diverse types of objects. If the specified property does not exist on the object or the value of DisplayMember is an empty string (""), the results of the object's ToString method are displayed instead.
If the new display member cannot be set, the previous display member setting is maintained.
ValueMember
Specify the contents of the ValueMember property in cases where you bind data.
You can clear the ValueMember property by setting the property to an empty string ("") or a null reference (Nothing in Visual Basic).
Setting a new ValueMember property raises the ValueMemberChanged and SelectedValueChanged events.
Now, the result of your stored procedure shall get stored in memory in an IList, BindingList<T> or any other bindable collection.
This collection should be set as the DataSource of your ComboBox. The best approach, in my opinion, is through a BindingSource.
Here's an example:
public partial class Form1 : Form {
private BindingSource bindingSource1;
public Form1() {
InitializeComponent();
bindingSource1 = new BindingSource();
comboBox1.DataSource = bindingSource1;
comboBox1.DisplayMember = "PaymentMethod";
comboBox1.ValueMember = "PaymentId";
bindingSource1.DataSource = GetPayments(); // GetPayments() shall return one of the above-mentioned bindable collections of payments.
}
}

Check if this helps you.

Related

How to get a specific string out of a database with C# using a parameter that can change in layer model

I need to make a helpdesk form for my end of year task and I'm stuck.
The task requires me to load the solution of a specific problem that the user selects via a combobox. My implementation needs to separated into layers like business persist and so on.
The code that I wrote to solve this didn't work (EXPLAIN WHY HERE). I have made a few attempts at it and have included them below.
First Attempt:
For my first attempt, I have written the following code to load the solution to the selected problem from the database:
public List<HelpDesk> getOplossing()
{
List<HelpDesk> lijst = new List<HelpDesk>();
MySqlConnection conn = new MySqlConnection(_connectionstring);
MySqlCommand cmd = new MySqlCommand("SELECT Oplosing from tblhelpdesk where Probleem = #probleem" , conn);
cmd.Parameters.Add(new MySqlParameter("#probleem",
getProbleem().ToString()));
conn.Open();
MySqlDataReader datareader = cmd.ExecuteReader();
while (datareader.Read())
{
HelpDesk hlpdsk = new HelpDesk(
datareader["Oplosing"].ToString());
lijst.Add(hlpdsk);
}
conn.Close();
return lijst;
}
And in the controller I called it like this:
public List<HelpDesk> getOplossing()
{
return _persistcode.getOplossing();
}
Attempt 2:
This is what I wrote for my second attempt.
public string getOplossing()
{
MySqlConnection conn = new MySqlConnection(_connectionstring);
MySqlCommand cmd = new MySqlCommand("SELECT Oplosing from tblhelpdesk", conn);
conn.Open();
string oplossing;
oplossing = cmd.ExecuteScalar().ToString();
conn.Close();
return oplossing;
}
Again in the controller:
public string getOplossing()
{
return _persistcode.getOplossing();
}
My entire HelpDesk class:
And the class HelpDesk looks like this: (I provided the whole class so you guys can have a gander at all the problem :/ )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GPDeBruykerSander_Domain.Business
{
public class HelpDesk
{
private int _id;
private Boolean _categorie; //Hardware= True en Software= False
private DateTime _datumProbleem;
private string _probleem;
private DateTime _datumOplossing;
private string _oplossing;
public int ID
{
get { return _id; }
set { _id = value; }
}
public override string ToString()
{
return Probleem;
}
public Boolean Categorie
{
get { return _categorie; }
set { _categorie = value; }
}
public DateTime DatumProbleem
{
get { return _datumProbleem; }
set { _datumProbleem = value; }
}
public string Probleem
{
get { return _probleem; }
set { _probleem = value; }
}
public DateTime DatumOplossing
{
get { return _datumOplossing; }
set { _datumOplossing = value; }
}
public string Oplossing
{
get { return _oplossing; }
set { _oplossing = value; }
}
public HelpDesk (int id, Boolean categorie, DateTime datumProbleem, string probleem, DateTime datumOplossing, string oplossing)
{
_id = id;
_categorie = categorie;
_datumProbleem = datumProbleem;
_probleem = probleem;
_datumOplossing = datumOplossing;
_oplossing = oplossing;
}
public HelpDesk(Boolean categorie, DateTime datumProbleem, string probleem, DateTime datumOplossing, string oplossing)
{
_categorie = categorie;
_datumProbleem = datumProbleem;
_probleem = probleem;
_datumOplossing = datumOplossing;
_oplossing = oplossing;
}
public HelpDesk(DateTime datumProbleem, Boolean categorie, string probleem)
{
_datumProbleem = datumProbleem;
_categorie = categorie;
_probleem = probleem;
}
public HelpDesk(DateTime datumOplossing, string oplossing)
{
_datumOplossing = datumOplossing;
_oplossing = oplossing;
}
public HelpDesk(string probleem)
{
_probleem = probleem;
}
}
}
I hope somebody can help me find the solution because I'm stuck :/
You were closer to solving your problem in your first attempt, so I will help you with that. But since you haven't actually provided any reasons as to why your code doesn't work (errors thrown by the application, etc.), I can only take a stab at potential issues I see in your code.
Looking at your MySQL query: SELECT Oplosing from tblhelpdesk where Probleem = #probleem, I would say that you are missing quotes around #probleem. So this query should look like this:
SELECT Oplosing from tblhelpdesk where Probleem = '#probleem'
I would also make the following suggestions:
Suggestion 1: Make getProbleem() method actually return a string, so you don't have to call ToString() on it. You haven't provided the implementation of this method so I can only assume the return type is not a string. If the return type is a string the ToString() is completely redundant here.
Suggestion 2:
I would also suggestion is that you pass the problem string as a parameter to getOplossing(), so that the database code is encapsulated better. For example:
public List<HelpDesk> getOplossing(string probleem)
{
...
cmd.Parameters.Add(new MySqlParameter("#probleem", probleem));
...
}
And your controller will call it like so:
public List<HelpDesk> getOplossing()
{
string probleem = getProbleem().ToString();
return _persistcode.getOplossing(probleem);
}

get/set Accessors the correct scope

i created a class called ProfileHelper, and I can't seem to get my get/set accessors correct; instead, I'm getting red lines on both get and set. Here is the code I am trying to use:
public static String UserName(string columnName)
{
get
{
using (SqlConnection cn = new SqlConnection(SiteConfig.ConnectionString))
{
string sSql = ("SELECT UserName , LoweredUserName FROM aspnet_Users WHERE UserId = #UserId");
using (SqlCommand cm = new SqlCommand(sSql, cn))
{
cm.Parameters.AddWithValue("#UserId", Membership.GetUser().ProviderUserKey.ToString());
cn.Open();
using (SqlDataReader rd = cm.ExecuteReader())
{
while (rd.Read())
{
return columnName;
}
rd.Close();
}
cn.Close();
}
}
return columnName;
}
set
{
using (SqlConnection cn = new SqlConnection(SiteConfig.ConnectionString))
{
string sSql = ("UPDATE [aspnet_ Users] SET UserName = #UserName, LoweredUserName = #LoweredUserName WHERE UserId = #UserId");
using (SqlCommand cm = new SqlCommand(sSql, cn))
{
cm.Parameters.AddWithValue("#UserId", Membership.GetUser ().ProviderUserKey.ToString());
cn.Open();
cm.ExecuteNonQuery();
cn.Close();
}
}
}
}
That's a method, not a property. Only properties have get and set accessors. Pick one.
public static String UserName(string columnName) // this implies a method
{
get // this implies a property
{
Syntax is basically:
private string userName;
public string UserName // no parameter here!
{
get { return this.userName; }
set { this.userName = value; } // value is a keyword
}
Alternatively, auto-property do the backing field for you:
public string UserName { get; set; } // equivalent
public string MyExternallyReadOnly { get; private set; } // setter is private
You should not fiddle around with SQL connections in properties. Access to properties should be fast and reliable. Consider replacing it by methods to make it clear that this is actually a longer-enduring action with external dependencies (which is more likely to fail):
public string GetUserName() { }
public void UpdateUserName() {}
You should make a pair of methods, GetUserName(string columnName) and SetUserName(string columnName, string value). This is the preferred approach when it will probably take a while, e.g. because you're making a DB connection, and lets you easily have a parameter.
public static String UserName(string columnName) is the signature for a method. public static String UserName would be a property. Properties have get/set accessors, methods do not. You need to change this. Properties do not allow arguments, except for indexed properties, which can't be static (e.g. used like myObj[someColumnName], declared like public string this[string columnName]). If you're expecting to access the property like var something = ProfileHelper.UserName;, just use a property.

populate dropdown list from a list of objects

In an attempt of building a 3-tier architecture c# asp.net application, I've started building a class that is database which is used for the connecting to the database, another class that is City which has a method for each column in the table cities, and a Cities class in which I have the GetCities method that creates a list of City objects and then use the DataSource wizard to set the control to use the data from GetCities().
All I get is blanks in the dropdown list. Any idea why?
public List<City> GetCities()
{
List<City> cities = new List<City>();
Database db = new Database();
SqlConnection conn = db.GetConnection();
String sql = "SELECT * FROM CITIES";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
City c = new City(reader.GetInt32(0), reader.GetString(1).ToString());
cities.Add(c);
}
db.CloseConnection();
return cities;
}
thanks
Did you set the DataTextField, DataValueField properties, and call DataBind?
At this point I would try to get the concept working as simply as possible, and then start adding things back in until you locate the problem. Start with a brand new page, add a DropDownList but don't touch the data source or change any properties, go directly into the codebehind and add this in Page_Load:
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataSource = new[] {
new { ID = 1, Name = "Alice" },
new { ID = 2, Name = "Mike" },
new { ID = 3, Name = "John" }
};
DropDownList1.DataBind();
Does it work? It does for me. Then try to change DataValueField, DataTextField, and DataSource to work with your customer list. Is it broken now? Then you know the problem is in the customer list somewhere, not with the way you're binding the data.
Have you called DataBind() method on the object you want to be populated ?
The issue resided in the City class which after a close inspection I've realised that the constructor was assigning the parameter received incorrectly. It's now working. Thanks!
public class City
{
int id;
string name;
public City(int id, string name)
{
this.id = id;
this.name = name;
}
public int Id
{
get { return id; }
set { id = value; }
}
public String Name
{
get { return name; }
set { name = value; }
}
}

"Object reference not set to an instance of an object." in C#, SQL 2005, VS 2008

I am trying to select "food_ItemName" and "food_UnitPrice" from "t_Food" table in SQL Server 2005.
I have the following code:
private void GetDatabaseConnection()
{
string connectionString = #"Server = RZS-F839AD139AA\SQLEXPRESS; Integrated Security = SSPI; Database = HotelCustomerManagementDatabase";
connection = new SqlConnection(connectionString);
connection.Open();
}
and.....
public Food PopulateFoodItemListview()
{
GetDatabaseConnection();
string selectFoodItemQuery = #"SELECT food_ItemName, food_UnitPrice FROM t_Food";
SqlCommand command = new SqlCommand(selectFoodItemQuery, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
food.ItemName.Add(reader.GetString(0)); // Exception is generated in this line
food.UnitPrice.Add(reader.GetDouble(1));
}
connection.Close();
return food;
}
In food class I have the following code:
public class Food
{
private List<string> itemName;
private List<double> unitPrice;
private double itemUnit;
private Customer foodCustomer = new Customer();
public Food ()
{
}
public Food(List<string> itemName, List<double> unitPrice) : this()
{
this.itemName = itemName;
this.unitPrice = unitPrice;
}
public List<string> ItemName
{
get { return itemName; }
set { itemName = value ; }
}
public List<double> UnitPrice
{
get { return unitPrice; }
set { unitPrice = value; }
}
public double ItemUnit
{
get { return itemUnit; }
set { itemUnit = value; }
}
}
but it generating following exception. Why?
"Object reference not set to an instance of an object."
You need to create an instance of the 'itemName' and 'unitPrice' variables before you can add to either of them. You can go ahead and do that when you are declaring them.
private List<string> itemName = new List<string>();
private List<double> unitPrice = new List<string>();
Well to start:
ConnectionStrings should go into the app.config/web.config.
ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString
Use the following code to open/close connection:
using(SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
}
And try to avoid having nulls in the reader...
SELECT ISNULL(food_ItemName, ''), ISNULL(food_UnitPrice, 0.0)
EDIT:
You forgot to initialize the private member of the class Food
Edit to those lines:
private List<string> itemName = new List<string>;
private List<double> unitPrice = new List<double>;
Or do it like this
public List<string> ItemName
{
get
{
if (itemName == null) itemName = new List<string>;
return itemName;
}
}
public List<double> UnitPrice
{
get
{
if (unitPrice== null) unitPrice= new List<double>;
return unitPrice;
}
}
On which variable does it complain?
It looks like the problematic one (well, maybe there are more problems but this one is for sure can cause the exception) is ItemName which is not initiated.
Have you looked at your stack trace to figure out which line the error is occurring on or which function?
From what I could see it look like it may be referring to your food object in the PopulateFoodItemListview() method. The food object is never created.

Get output from Stored Procedure using Console

Hi I'm trying to produce an output from console but keep getting the error message
Procedure or function 'p_Date_sel'
expects parameter '#DateID', which was
not supplied
Suppose to get the DateID and display all the data,please tell me what I'm doing wrong.
Below is my stored procedure
ALTER procedure [dbo].[p_Date_sel]
#DateID int
AS
BEGIN
SELECT DateTypeID , Date , Name, Notes
FROM dbo.Dates
WHERE DateID= #DateID
END
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
namespace ExecuteStoredProcedure
{
class Program
{
private int _dateID;
private int _dateTypeID;
private DateTime _date;
private string _name;
private string _notes;
public Program()
{
_dateID = 0;
}
public Program(int dateID) {
_dateID = dateID;
}
public Program(int datetypeID,DateTime date,string name,string notes){
_dateTypeID = datetypeID;
_date = date;
_name = name;
_notes = notes;
}
public int dateID
{
get {return _dateID;}
}
public int dateTypeID
{
get { return _dateTypeID; }
set { _dateTypeID = value; }
}
public DateTime date
{
get {return _date ;}
set { _date = value;}
}
public string name
{
get { return _name;}
set { _name = value; }
}
public string notes
{
get { return _notes;}
set { _notes = value; }
}
public void LoadData()
{
SqlConnection conn = new SqlConnection("Data Source=mycbj01psql03\\sandbox01;Initial Catalog=DBRMS;Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("p_Date_sel", conn);
command.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
_dateTypeID = Convert.ToInt16(reader["DateTypeID"]);
_date = Convert.ToDateTime(reader["Date"]);
_name = reader["Name"].ToString();
_notes = reader["Notes"].ToString();
}
reader.Close();
conn.Close();
}
}
}
My Main Program
namespace ExecuteStoredProcedure
{
class TestClass
{
public static void Main(string[] args)
{
Program p = new Program(5);
p.LoadData();
Console.WriteLine("DateID = " + "" + p.dateID);
Console.WriteLine("DateTypeID = " + "" + p.dateTypeID);
Console.WriteLine("Date = " + "" + p.date);
Console.WriteLine("Name = " + "" + p.name);
Console.WriteLine("Notes = " + "" + p.notes);
Console.ReadLine();
}
}
}
Well, you need to supply a value for #DateID!
Your stored proc requires a parameter called #DateID or type INT:
ALTER procedure [dbo].[p_Date_sel]
#DateID int
but in your call, you never ever do supply such a value!
What you need to do is create a SqlParameter and pass in that value to the stored proc. Also, I would strongly recommend to make use of the using() {...} constructs for your sql client code. And as a last recommendation: why not make the DateID a parameter of the LoadData() method?? The way you have it now, you have to create an instance of your class for each value you want to retrieve - not very efficient and useful....
public void LoadData(int dateID)
{
using(SqlConnection conn = new SqlConnection("Data Source=mycbj01psql03\\sandbox01;Initial Catalog=DBRMS;Integrated Security=True"))
{
using(SqlCommand command = new SqlCommand("p_Date_sel", conn))
{
command.CommandType = CommandType.StoredProcedure;
// define the parameter and give it a value!
command.Parameters.Add("#DateID", SqlDbType.Int);
command.Parameters["#DateID"].Value = dateID;
conn.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
_dateTypeID = Convert.ToInt16(reader["DateTypeID"]);
_date = Convert.ToDateTime(reader["Date"]);
_name = reader["Name"].ToString();
_notes = reader["Notes"].ToString();
}
reader.Close();
}
conn.Close();
}
}
That way, you should get your stored proc to work properly. Call it from your main app like this:
Program p = new Program();
p.LoadData(5);

Categories

Resources