How to load in data from database to listbox - c#

My program can load in the listbox headers, but not the actually data from the whole table.
(how I am connecting to the database):
const string connectionString = "Data Source=test;Initial Catalog=dbi391731;User ID=test;Password=test";
SqlConnection conn = new SqlConnection(connectionString);
I'm using a class to load in the data:
public List<ScoreMdw> GetScoreMdwList()
{
List<ScoreMdw> scoremdwList = new List<ScoreMdw>();
conn.Open();
string query = ("Select employeeid, questionid, score from contentment");
SqlCommand cmd = new SqlCommand(query, conn);
try
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
ScoreMdw sm = new ScoreMdw((int)dr["employeeid"], (int)dr["questionid"], (char)dr["score"]);
scoremdwList.Add(sm);
}
}
}
catch (Exception ex)
{
Exception error = new Exception("error", ex);
throw error;
}
finally
{
conn.Close();
}
return scoremdwList;
}
In the while loop I'm using an other class:
class ScoreMdw
{
private int employeeid;
private int questionid;
private char score;
public ScoreMdw(int nr, int id, char s)
{
this.employeeid= nr;
this.questionid= id;
this.score = s;
}
public int EmployeeId
{
get { return employeeid; }
}
public int QuestionId
{
get { return questionid; }
}
public char Score
{
get { return score; }
}
public override string ToString()
{
string s = string.Format("{0} \t{1} \t{2}", this.employeeid, this.questionid, this.score);
return s;
}
}
In my main window I'm doing this:
private void btnLoadScores_Click(object sender, RoutedEventArgs e)
{
scoremdwList = new List<ScoreMdw>();
try
{
conn.Open();
List<string> headers = so.GetContentmentHeaders();
foreach (string header in headers)
txtHeader.Text += header + "\t";
scoremdwList = so.GetScoreMdwList();
lbScores.ItemsSource = scoremdwList;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
I get the error that I made in the class ("error"). I don't know what I'm doing wrong? Maybe something with the connection? Am I opening and closing it the wrong way?

May i ask you, to show us the ex.Message? So we know what the possible error could be.
try
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
while(dr.read())
{
ScoreMdw sm = new ScoreMdw((int)dr["employeeid"], (int)dr["questionid"], (char)dr["score"]);
scoremdwList.Add(sm);
}
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message); // <= here you will get you errormessage that is important to fix your error.
Exception error = new Exception("error", ex);
throw error;
}

Related

Binding dropdownlist with generic list in 3-tier architecture

/*data access layer */
public DataSet getdata(string procedurename, SqlParameter[] param)
{
try
{
SqlCommand command;
command = new SqlCommand(procedurename, connection);
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet set = new DataSet();
if (param != null)
{
for (int i = 0; i < param.Length; i++)
{
command.Parameters.Add(param[i]);
}
}
adapter.Fill(set);
return set;
}
catch (Exception ex)
{
throw ex;
}
finally
{
closeConnection();
}
}
Middle Tier:
public class dropdownbind
{
private string _itemName;
private int _itemvalue;
public int Itemvalue
{
get { return _itemvalue; }
set { _itemvalue = value; }
}
public string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
public List<dropdownbind> getDepartment()
{
DBlist obj = new DBlist();
DataSet ds = obj.getdata("str_getdepartment",null);
List<dropdownbind> departments = new List<dropdownbind>();
foreach (DataRow orow in ds.Tables[0].Rows)
{
dropdownbind dlist = new dropdownbind();
dlist.ItemName = orow["deparment_name"].ToString();
dlist.Itemvalue = int.Parse(orow["id"].ToString());
departments.Add(dlist);
}
return departments;
}
}
UI:-
protected void BindDdlList()
{
dropdownbind dlist = new dropdownbind();
List<dropdownbind> departments = dlist.getDepartment();
ddlEmpDepatment.DataSource = departments;
ddlEmpDepatment.DataTextField = dlist.ItemName;
ddlEmpDepatment.DataValueField = dlist.Itemvalue.ToString();
ddlEmpDepatment.DataBind();
}
i am trying to bind departments to dropdownlist using 3-tier architecture.
but this code is not working, it shows middletier.dropdownbind in text field.
You need to correct the DataTextField & DataValueField properties like this:-
ddlEmpDepatment.DataValueField = "Itemvalue";
ddlEmpDepatment.DataTextField = "ItemName";
You are specifying the property name rather you need to specify the property name as string.

WCF Not implementing interface member

I am working on a wcf service that connects to database. I had debugged and tested my operation playerregistration and clubregistration. I then tried to test the get functions but i received the error:
Error 1 'WebApplication1.ADOService' does not implement interface member 'WebApplication1.IADOService.newMembership(WebApplication1.playerDetails, WebApplication1.playerDetails, WebApplication1.clubDetails, WebApplication1.memberDetails)' C:\Users\Daniel\Documents\Visual Studio 2013\Projects\Prac4\WebApplication1\ADOService.svc.cs 14 18 WebApplication1
following the error I attempted to remove the get functions however the error remains. Below is the service code
public class ADOService : IADOService
{
public string playerRegistration(playerDetails playerInfo)
{
string Message;
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT into Player(pid, pfname, plname, pphone, paddress, pdob) VALUES (#pid, #pfname, #plname, #pphone, #paddress, #pdob)", conn))
{
cmd.Parameters.AddWithValue("#pid", playerInfo.Pid);
cmd.Parameters.AddWithValue("#pfname", playerInfo.Pfname);
cmd.Parameters.AddWithValue("#plname", playerInfo.Plname);
cmd.Parameters.AddWithValue("#pphone", playerInfo.Pphone);
cmd.Parameters.AddWithValue("#paddress", playerInfo.Paddress);
cmd.Parameters.AddWithValue("#pdob", playerInfo.Pdob);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = playerInfo.Pid + " Details inserted successfully";
}
else
{
Message = playerInfo.Pid + " Details not inserted successfully";
}
conn.Close();
return Message;
}
}
}
public string clubRegistration(clubDetails clubInfo)
{
string Message;
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT into Club(cid, cname, cfounded, cworldranking) VALUES (#cid, #cname, #cfounded, #cworldranking)", conn))
{
cmd.Parameters.AddWithValue("#cid", clubInfo.Cid);
cmd.Parameters.AddWithValue("#cname", clubInfo.Cname);
cmd.Parameters.AddWithValue("#cfounded", clubInfo.Cfounded);
cmd.Parameters.AddWithValue("#cworldranking", clubInfo.Cworldranking);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = clubInfo.Cname + " Details inserted successfully";
}
else
{
Message = clubInfo.Cname + " Details not inserted successfully";
}
conn.Close();
return Message;
}
}
}
public List<playerDetails> getplayerInfo(string pfname, string plname)
{
List<playerDetails> playerDetails = new List<playerDetails>();
{
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Player WHERE pfname LIKE '%'+#pfname+'%' AND plname LIKE '%'+#plname+'%'", conn);
cmd.Parameters.AddWithValue("#pfname", pfname);
cmd.Parameters.AddWithValue("#plname", plname);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
playerDetails playerInfo = new playerDetails();
playerInfo.Pid = Convert.ToInt32(dt.Rows[i]["Pid"].ToString());
playerInfo.Pfname = dt.Rows[i]["Pfname"].ToString();
playerInfo.Plname = dt.Rows[i]["Plname"].ToString();
playerInfo.Pphone = Convert.ToInt32(dt.Rows[i]["Pphone"].ToString());
playerInfo.Paddress = dt.Rows[i]["Paddress"].ToString();
playerInfo.Pdob = DateTime.Parse(dt.Rows[i]["Pdob"].ToString());
playerDetails.Add(playerInfo);
}
}
conn.Close();
}
return playerDetails;
}
}
public List<clubDetails> getclubInfo(string cname)
{
List<clubDetails> clubDetails = new List<clubDetails>();
{
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Player WHERE cname LIKE '%'+#cname+'%'", conn);
cmd.Parameters.AddWithValue("#cname", cname);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
clubDetails clubInfo = new clubDetails();
clubInfo.Cid = Convert.ToInt32(dt.Rows[i]["Cid"].ToString());
clubInfo.Cname = dt.Rows[i]["Cname"].ToString();
clubInfo.Cfounded = DateTime.Parse(dt.Rows[i]["Cfounded"].ToString());
clubInfo.Cworldranking = Convert.ToInt32(dt.Rows[i]["Cworldranking"].ToString());
clubDetails.Add(clubInfo);
}
}
conn.Close();
}
return clubDetails;
}
}}}
And Iservice code
[ServiceContract]
public interface IADOService
{
[OperationContract]
string playerRegistration(playerDetails playerInfo);
[OperationContract]
string clubRegistration(clubDetails clubInfo);
[OperationContract]
List<playerDetails> getplayerInfo(string pfname, string plname);
[OperationContract]
List<clubDetails> getclubInfo(string cname);
[OperationContract]
string newMembership(playerDetails pfname, playerDetails plname, clubDetails cname, memberDetails memberstart);
}
[DataContract]
public class playerDetails
{
int pid;
string pfname;
string plname;
int pphone;
string paddress;
DateTime pdob;
[DataMember]
public int Pid
{
get { return pid; }
set { pid = value; }
}
[DataMember]
public string Pfname
{
get { return pfname; }
set { pfname = value; }
}
[DataMember]
public string Plname
{
get { return plname; }
set { plname = value; }
}
[DataMember]
public int Pphone
{
get { return pphone; }
set { pphone = value; }
}
[DataMember]
public string Paddress
{
get { return paddress; }
set { paddress = value; }
}
[DataMember]
public DateTime Pdob
{
get { return pdob; }
set { pdob = value; }
}
}
[DataContract]
public class clubDetails
{
int cid;
string cname;
DateTime cfounded;
int cworldranking;
[DataMember]
public int Cid
{
get { return cid; }
set { cid = value; }
}
[DataMember]
public string Cname
{
get { return cname; }
set { cname = value; }
}
[DataMember]
public DateTime Cfounded
{
get { return cfounded; }
set { cfounded = value; }
}
[DataMember]
public int Cworldranking
{
get { return cworldranking; }
set { cworldranking = value; }
}
}
[DataContract]
public class memberDetails
{
int mid;
DateTime memberstart;
DateTime memberend;
int gamesplayed;
[DataMember]
public int Mid
{
get { return mid; }
set { mid = value; }
}
[DataMember]
public DateTime Memberstart
{
get { return memberstart; }
set { memberstart = value; }
}
[DataMember]
public DateTime Memberend
{
get { return memberend; }
set { memberend = value; }
}
[DataMember]
public int Gamesplayed
{
get { return gamesplayed; }
set { gamesplayed = value; }
}
}
}
I am assuming that the get functions are the cause of the problem but not sure how to address the error.
You've defined the following methods in your interface:
string playerRegistration(playerDetails playerInfo);
string clubRegistration(clubDetails clubInfo);
List<playerDetails> getplayerInfo(string pfname, string plname);
List<clubDetails> getclubInfo(string cname);
string newMembership(playerDetails pfname, playerDetails plname, clubDetails cname, memberDetails memberstart);
But only implemented four of them:
playerRegistration
clubRegistration
getplayerInfo
getclubInfo
You haven't actually implemented newMembership in the ADOService class.

Error adding usercontrol to winform

I am trying to add a usercontrol to my winform. When I try to do this I get an error:
I have tried to recreate both the form and usercontrol, but the error keeps showing up.
Really bothered with this because I can not continue my project this way..
How can I fix this?
Edit: I have used various different names for both the usercontrol and form. Also restarting Visual Studio did not help.
Edit2:
UcLeed Contains the following code:
public partial class ucLeed : UserControl
{
ErrorProvider error = new ErrorProvider();
DBLid DBlid = new DBLid();
public ucLeed()
{
InitializeComponent();
error.BlinkStyle = ErrorBlinkStyle.NeverBlink;
}
string lidID;
public string LidID
{
get { return lidID; }
set { lidID = value; }
}
public string Achternaam
{
get { return tbAchternaam.Text; }
set { tbAchternaam.Text = value; }
}
public string Adres
{
get { return tbStraat.Text; }
set { tbStraat.Text = value; }
}
public string Email
{
get { return tbEmail.Text; }
set { tbEmail.Text = value; }
}
public string Geboortedatum
{
get { return tbGeboortedatum.Text; }
set { tbGeboortedatum.Text = value; }
}
public string Gebruikersnaam
{
get { return tbGebruikersnaam.Text; }
set { tbGebruikersnaam.Text = value; }
}
public string Voornaam
{
get { return tbVoornaam.Text; }
set { tbVoornaam.Text = value; }
}
public string Wachtwoord
{
get { return tbPassword.Text; }
set { tbPassword.Text = value; }
}
public string BevWachtwoord
{
get { return tbPassBev.Text; }
set { tbPassBev.Text = value; }
}
public string Woonplaats
{
get { return tbWoonplaats.Text; }
set { tbWoonplaats.Text = value; }
}
public string Postcode
{
get { return tbPostcode.Text; }
set { tbPostcode.Text = value; }
}
private void CheckInput(CancelEventArgs e, TextBox tb)
{
if (string.IsNullOrEmpty(tb.Text))
{
error.SetError(tb, "*");
e.Cancel = true;
}
if (!string.IsNullOrEmpty(tb.Text))
{
error.SetError(tb, String.Empty);
error.Clear();
error.Dispose();
}
}
private void CheckIntInput(CancelEventArgs e, TextBox tb)
{
int integer;
if (int.TryParse(tb.Text, out integer))
{
error.SetError(tb, String.Empty);
error.Clear();
error.Dispose();
}
else
{
MessageBox.Show("Je moet een getal invullen!");
tb.Focus();
error.SetError(tb, "*");
}
}
private void CheckDateInput(CancelEventArgs e, TextBox tb)
{
string date = tb.Text;
DateTime fromDateValue;
var formats = new[] { "dd/MM/yyyy", "dd-MM-yyyy" };
if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
{
error.SetError(tb, String.Empty);
error.Clear();
error.Dispose();
}
else
{
MessageBox.Show("Je moet wel een datum invullen!");
tb.Focus();
error.SetError(tb, "*");
}
}
private void ComparePasswords(CancelEventArgs e, MaskedTextBox tb, MaskedTextBox tb2)
{
if (tb.Text != tb2.Text)
{
MessageBox.Show("Je hebt niet het juiste wachtwoord bevestigd!");
error.SetError(tb2, "*");
}
else
{
error.SetError(tb2, String.Empty);
error.Clear();
error.Dispose();
}
}
private void tbVoornaam_Validating(object sender, CancelEventArgs e)
{
CheckInput(e, (TextBox)sender);
}
private void tbPassBev_Validating(object sender, CancelEventArgs e)
{
ComparePasswords(e, (MaskedTextBox)tbPassword, (MaskedTextBox)sender);
}
private void tbEmail_Validating(object sender, CancelEventArgs e)
{
try
{
var email = new MailAddress(tbEmail.Text);
error.SetError(tbEmail, String.Empty);
error.Clear();
error.Dispose();
}
catch
{
MessageBox.Show("Verkeerde formaat email adres!");
error.SetError(tbEmail, "*");
}
}
private void tbGeboortedatum_Validating(object sender, CancelEventArgs e)
{
CheckDateInput(e, (TextBox)sender);
}
private void tbGebruikersnaam_Validating(object sender, CancelEventArgs e)
{
if (DBlid.CheckLid(tbGebruikersnaam.Text))
{
MessageBox.Show("Gebruikersnaam al in gebruik!");
this.Focus();
error.SetError(tbGebruikersnaam, "*");
}
}
}
Edit3: The code of class DBLid.
class DBLid
{
DBChecks DBChecks = new DBChecks();
bool querystatus = false;
public bool Querystatus
{
get { return querystatus; }
set { querystatus = value; }
}
string connectionString = ConfigurationManager.ConnectionStrings["Insomnia.Properties.Settings.dbInsomniaConnectionString"].ConnectionString;
public DataTable GetLeden()
{
DataTable DT = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
cmd.Connection = conn;
cmd.CommandText = "SELECT Lid.Id, Lid.Achternaam, Lid.Voornaam, Lid.Email, Lid.Adres, Lid.Woonplaats, Lid.Postcode, convert(varchar, Lid.Geboortedatum, 101) AS 'Geboorte Datum', Lid.GebruikersNaam AS Gebruikersnaam FROM Lid";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(DT);
return DT;
}
public bool CheckLid(string gebruikersnaam)
{
bool inUse = false;
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("gebruikersnaam", gebruikersnaam);
cmd.CommandText = "SELECT COUNT(Lid.ID) FROM Lid WHERE GebruikersNaam = #gebruikersnaam";
try
{
conn.Open();
if ((int)cmd.ExecuteScalar() == 1)
{
inUse = true;
}
else
{
inUse = false;
}
}
catch
{
}
finally
{
conn.Close();
}
return inUse;
}
public void AddLid(string achternaam, string adres, string email, string geboortedatum, string gebruikersnaam, string voornaam, string wachtwoord, string woonplaats, string postcode)
{
// Encrypt password
string encryptedPassword = DBChecks.encryptPassword(wachtwoord);
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("achternaam", achternaam);
cmd.Parameters.AddWithValue("adres", adres);
cmd.Parameters.AddWithValue("email", email);
cmd.Parameters.AddWithValue("geboortedatum", geboortedatum);
cmd.Parameters.AddWithValue("gebruikersnaam", gebruikersnaam);
cmd.Parameters.AddWithValue("voornaam", voornaam);
cmd.Parameters.AddWithValue("woonplaats", woonplaats);
cmd.Parameters.AddWithValue("postcode", postcode);
cmd.Parameters.AddWithValue("wachtwoord", encryptedPassword);
cmd.CommandText = "INSERT INTO Lid (Achternaam, Adres, Email, GeboorteDatum, GebruikersNaam, Voornaam, Wachtwoord, Woonplaats, Postcode) VALUES (#achternaam, #adres, #email, #geboortedatum, #gebruikersnaam, #voornaam, #wachtwoord, #woonplaats, #postcode); SELECT CONVERT(int, SCOPE_IDENTITY());";
try
{
conn.Open();
int lidID = (int)cmd.ExecuteScalar();
MessageBox.Show("Het lid is toegevoegd met LidID: " + lidID);
querystatus = true;
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
querystatus = false;
}
finally {
conn.Close();
}
}
}
Edit4: Added DBChecks for Reference.
class DBChecks
{
bool reserveerStatus;
public bool ReserveerStatus
{
get { return reserveerStatus; }
set { reserveerStatus = value; }
}
bool querystatus = false;
public bool QueryStatus
{
get { return querystatus; }
set { querystatus = value; }
}
int gameID;
public int GameID
{
get { return gameID; }
set { gameID = value; }
}
int boekID;
public int BoekID
{
get { return boekID; }
set { boekID = value; }
}
private int itemsoort;
public int Itemsoort
{
get { return itemsoort; }
set { itemsoort = value; }
}
string connectionString = ConfigurationManager.ConnectionStrings["Insomnia.Properties.Settings.dbInsomniaConnectionString"].ConnectionString;
public string encryptPassword(string uncryptedPassword)
{
HashAlgorithm hash = new SHA256Managed();
string salt = "UserName";
// compute hash of the password prefixing password with the salt
byte[] plainTextBytes = Encoding.UTF8.GetBytes(salt + uncryptedPassword);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
string hashValue = Convert.ToBase64String(hashBytes);
return hashValue;
}
public bool ReserveringStatus(int itemID)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("itemID", itemID);
cmd.Connection = conn;
cmd.CommandText = "SELECT ReserveerStatus FROM Item WHERE Id = #itemID";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
reserveerStatus = (bool)sdr["ReserveerStatus"];
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return reserveerStatus;
}
public int CheckLid(int lidID)
{
int aantal = 0;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("lidID", lidID);
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT(*) AS Aantal FROM Lid WHERE Id = #lidID";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
aantal = (int)sdr["Aantal"];
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return aantal;
}
public int CheckPas(int pasID)
{
int aantal = 0;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("pasID", pasID);
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT(*) AS Aantal FROM Pas WHERE Id = #pasID";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
aantal = (int)sdr["Aantal"];
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return aantal;
}
public void CheckSoort(int itemID)
{
// Variable declaration
string soort = "";
List<Boek> boek = new List<Boek>();
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
// Check if ItemID is boek or game
cmd.Parameters.AddWithValue("itemID", itemID);
cmd.Connection = conn;
cmd.CommandText = "SELECT Soort FROM Item WHERE ID = #itemID;";
// Retrieve data
// Try-catch-final to catch wrong itemID error
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
soort = sdr["Soort"].ToString();
}
if (soort == "Boek")
{
itemsoort = 1;
}
if (soort == "Game")
{
itemsoort = 2;
}
if (soort == "")
{
itemsoort = 3;
MessageBox.Show("Dit ID bestaat niet!");
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
}
public bool CheckStatus(int itemID)
{
// Variables
bool itemStatus = true;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("itemID", itemID);
// Method
cmd.Connection = conn;
cmd.CommandText = "SELECT Status FROM Item WHERE Item.Id = #itemID;";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
itemStatus = (bool)sdr["Status"];
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return itemStatus;
}
public List<Game> ShowGame(int itemID)
{
// Variable declaration
List<Game> gameList = new List<Game>();
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("itemID", itemID);
// Retrieve data
cmd.Connection = conn;
cmd.CommandText = "SELECT Game.*, Item.*, convert(varchar, Item.DvU, 101) AS DatumVUitgave, Platform.Soort as Platform, Media.soort as Media, GameGenre.Genre AS Genre FROM Game LEFT JOIN ITEM ON Item.ID = Game.itemID LEFT JOIN Media ON Game.MediaID = Media.Id LEFT JOIN Platform ON Game.PlatformID = Platform.Id LEFT JOIN GameGenre ON Game.GameGenreID = GameGenre.Id WHERE Game.itemID = #itemID;";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
gameList.Add(new Game() { Titel = sdr["Titel"].ToString(), Dvu = sdr["DatumVUitgave"].ToString(), Genre = sdr["Genre"].ToString(), Media = sdr["Media"].ToString(), Pegi = sdr["PEGI"].ToString(), Platform = sdr["Platform"].ToString(), EAN = sdr["EAN"].ToString(), Uitgever = sdr["Uitgever"].ToString() });
}
}
catch (FormatException e)
{
MessageBox.Show(e.Message);
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return gameList;
}
public List<Boek> ShowBoek(int itemID)
{
// Variable declaration
List<Boek> boekList = new List<Boek>();
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("itemID", itemID);
// Retrieve data
cmd.Connection = conn;
cmd.CommandText = "SELECT Boek.*, Item.*, convert(varchar, Item.DvU, 101) AS DatumVUitgave, Auteur.Auteur AS Auteur, BoekGenre.Genre AS Genre, Bindwijze.Soort as Bindwijze, Taal.Taal AS Taal FROM Boek LEFT JOIN Item ON Boek.ItemID = Item.Id LEFT JOIN Bindwijze ON Boek.BindwijzeID = Bindwijze.ID LEFT JOIN BoekGenre ON Boek.BoekGenreID = BoekGenre.Id LEFT JOIN Auteur on Boek.AuteurID = Auteur.Id LEFT JOIN Taal ON Boek.TaalID = Taal.Id WHERE Boek.ItemID = #itemID;";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
// Fill boek with retrieved item(s)
boekList.Add(new Boek() { Auteur = sdr["Auteur"].ToString(), Genre = sdr["Genre"].ToString(), Dvu = sdr["DatumVUitgave"].ToString(), ISBN101 = sdr["ISBN10"].ToString(), ISBN131 = sdr["ISBN13"].ToString(), Paginas = sdr["AantalPagina"].ToString(), Taal = sdr["Taal"].ToString(), Titel = sdr["Titel"].ToString(), Bindwijze = sdr["Bindwijze"].ToString(), Uitgever = sdr["Uitgever"].ToString() });
}
}
catch (FormatException e)
{
MessageBox.Show(e.Message);
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return boekList;
}
}
Try changing string lidID; to string lidID = ""; and probably bool reserveerStatus; to bool reserveerStatus = false;
Ok, I still do not know how or why; but if I remove the code from ucLeed, I can drag and drop the control onto my form.
Not sure how or why, but that is something I will try to figure out!

In the name the owner of a procedure must be specified - sql

I wrote C# code which returns a DataTable. All parameters i.e. Connection, sQuery have proper values.
Still I am getting an error:
In the name the owner of a procedure must be specified, this improves performance
I googled it but found nothing.
This is my code:
public static DataTable getATM(ref SqlConnection Connection)
{
DataTable dtReturn;
string sQuery = "";
try
{
sQuery = "Select ATM From ATM Where Bank=1";
using (SqlStoredProcedure sspObj = new SqlStoredProcedure(sQuery, Connection, CommandType.Text))
{
dtReturn = sspObj.ExecuteDataTable();
sspObj.Dispose();
}
}
catch (Exception xObj)
{
dtReturn = new DataTable();
}
return dtReturn;
}
SqlStoredProcedure.cs:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Diagnostics;
namespace ReflectionIT.Common.Data.SqlClient {
public class SqlStoredProcedure : IDisposable {
public static readonly TraceSource TraceSource = new TraceSource("SqlStoredProcedure");
private static int _eventId = 0;
private const string _returnValue = "ReturnValue";
private SqlCommand _command;
private bool _connectionOpened = false;
public SqlStoredProcedure(string name, SqlConnection connection, CommandType comtype)
: this(name, connection, null, comtype) {
}
public SqlStoredProcedure(string name, SqlConnection connection, SqlTransaction transaction, CommandType comtype) {
if (name.IndexOf('.') == -1) {
throw new ArithmeticException("In the name the owner of a procedure must be specified, this improves performance");
}
_command = new SqlCommand(name, connection, transaction);
_command.CommandTimeout = 0;
_command.CommandType = comtype;
AddReturnValue();
}
public void Dispose() {
if (_command != null) {
_command.Dispose();
_command = null;
}
}
virtual public string Name {
get { return _command.CommandText; }
set { _command.CommandText = value; }
}
virtual public int Timeout {
get { return _command.CommandTimeout; }
set { _command.CommandTimeout = value; }
}
virtual public SqlCommand Command {
get { return _command; }
}
virtual public SqlConnection Connection {
get { return _command.Connection; }
set { _command.Connection = value; }
}
virtual public SqlTransaction Transaction {
get { return _command.Transaction; }
set { _command.Transaction = value; }
}
virtual public SqlParameterCollection Parameters {
get { return _command.Parameters; }
}
virtual public int ReturnValue {
get { return (int)_command.Parameters[_returnValue].Value; }
}
virtual public SqlParameter AddParameter(string parameterName,
SqlDbType dbType,
int size,
ParameterDirection direction) {
SqlParameter p;
if (size > 0) {
p = new SqlParameter(parameterName, dbType, size);
} else {
// size is automacally detected using dbType
p = new SqlParameter(parameterName, dbType);
}
p.Direction = direction;
Parameters.Add(p);
return p;
}
virtual public SqlParameter AddParameterWithValue(string parameterName,
SqlDbType dbType,
int size,
ParameterDirection direction,
object value) {
SqlParameter p = this.AddParameter(parameterName, dbType, size, direction);
if (value == null) {
value = DBNull.Value;
}
p.Value = value;
return p;
}
virtual public SqlParameter AddParameterWithStringValue(string parameterName,
SqlDbType dbType,
int size,
ParameterDirection direction,
string value,
bool emptyIsDBNull) {
SqlParameter p = this.AddParameter(parameterName, dbType, size, direction);
if (value == null) {
p.Value = DBNull.Value;
} else {
value = value.TrimEnd(' ');
if (emptyIsDBNull && value.Length == 0) {
p.Value = DBNull.Value;
} else {
p.Value = value;
}
}
return p;
}
virtual protected SqlParameter AddReturnValue() {
SqlParameter p = Parameters.Add(
new SqlParameter(_returnValue,
SqlDbType.Int,
/* int size */ 4,
ParameterDirection.ReturnValue,
/* bool isNullable */ false,
/* byte precision */ 0,
/* byte scale */ 0,
/* string srcColumn */ string.Empty,
DataRowVersion.Default,
/* value */ null));
return p;
}
virtual public int ExecuteNonQuery() {
int rowsAffected = -1;
try {
Prepare("ExecuteNonQuery");
rowsAffected = _command.ExecuteNonQuery();
TraceResult("RowsAffected = " + rowsAffected.ToString());
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return rowsAffected;
}
virtual public SqlDataReader ExecuteReader() {
SqlDataReader reader;
try {
Prepare("ExecuteReader");
reader = _command.ExecuteReader();
TraceResult(null);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return reader;
}
virtual public SqlDataReader ExecuteReader(CommandBehavior behavior) {
SqlDataReader reader;
try {
Prepare("ExecuteReader");
reader = _command.ExecuteReader(behavior);
TraceResult(null);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return reader;
}
virtual public object ExecuteScalar() {
object val = null;
try {
Prepare("ExecuteScalar");
val = _command.ExecuteScalar();
TraceResult("Scalar Value = " + Convert.ToString(val));
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return val;
}
virtual public XmlReader ExecuteXmlReader() {
XmlReader reader;
try {
Prepare("ExecuteXmlReader");
reader = _command.ExecuteXmlReader();
TraceResult(null);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return reader;
}
virtual public DataSet ExecuteDataSet() {
DataSet dataset = new DataSet();
this.ExecuteDataSet(dataset);
return dataset;
}
virtual public DataSet ExecuteDataSet(DataSet dataSet) {
try {
Prepare("ExecuteDataSet");
SqlDataAdapter a = new SqlDataAdapter(this.Command);
a.Fill(dataSet);
TraceResult("# Tables in DataSet = " + dataSet.Tables.Count);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return dataSet;
}
virtual public DataTable ExecuteDataTable() {
DataTable dt = null;
try {
Prepare("ExecuteDataTable");
SqlDataAdapter a = new SqlDataAdapter(this.Command);
dt = new DataTable();
a.Fill(dt);
TraceResult("# Rows in DataTable = " + dt.Rows.Count);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return dt;
}
protected Exception TranslateException(SqlException ex) {
Exception dalException = null;
SqlStoredProcedure.TraceSource.TraceEvent(TraceEventType.Error, _eventId, "{0} throwed exception: {1}", this.Name, ex.ToString());
foreach (SqlError error in ex.Errors) {
if (error.Number >= 50000) {
dalException = new DalException(error.Message, ex);
}
}
if (dalException == null) {
switch (ex.Number) {
case 17:
case 4060:
case 18456:
dalException = new DalLoginException(ex.Message, ex);
break;
case 547:
dalException = new DalForeignKeyException(ex.Message, ex);
break;
case 1205:
dalException = new DalDeadLockException(ex.Message, ex);
break;
case 2627:
case 2601:
dalException = new DalUniqueConstraintException(ex.Message, ex);
break;
default:
dalException = new DalException(ex.Message, ex);
break;
}
}
return dalException;
}
protected void Prepare(string executeType) {
_eventId++;
if (_eventId > ushort.MaxValue) {
_eventId = 0;
}
SqlStoredProcedure.TraceSource.TraceEvent(TraceEventType.Information, _eventId, "{0}: {1}", executeType, this.Name);
TraceParameters(true);
if (_command.Connection.State != ConnectionState.Open) {
_command.Connection.Open();
_connectionOpened = true;
}
}
private void TraceParameters(bool input) {
if (SqlStoredProcedure.TraceSource.Switch.ShouldTrace(TraceEventType.Verbose) && this.Parameters.Count > 0) {
foreach (SqlParameter p in this.Parameters) {
bool isInput = p.Direction != ParameterDirection.ReturnValue && p.Direction != ParameterDirection.Output;
bool isOutput = p.Direction != ParameterDirection.Input;
if ((input && isInput) || (!input && isOutput)) {
SqlStoredProcedure.TraceSource.TraceEvent(TraceEventType.Verbose, _eventId, "SqlParamter: Name = {0}, Value = '{1}', Type = {2}, Size = {3}", p.ParameterName, p.Value, p.DbType, p.Size);
}
}
}
}
protected void CloseOpenedConnection() {
if ((_command.Connection.State == ConnectionState.Open) & _connectionOpened)
_command.Connection.Close();
}
protected void TraceResult(string result) {
if (result != null) {
SqlStoredProcedure.TraceSource.TraceEvent(TraceEventType.Verbose, _eventId, "Result: {0}", result);
}
TraceParameters(false);
}
}
}
SqlStoredProcedure() is checking that there is a dot in your stored procedure name and if there isn't throwing that exception, so prefix your stored procedure name with "dbo." or whatever it is e.g.:
dbo.myProcedureName
It improves performance in the sense that SQL doesn't have to search all the users to find the proc first.

I make a 3-tier application i want to insert the data in table it show me a error...it show me a null exception

DataBase Layer...................
public static void AddEnrollment(StudentScore enrollment)
{
SqlConnection conn = MyDB.GetConnection();
string insertStm = "insert into EnrollmentTable (StudentID,CourseID,DateEnrolled,Score) values (#StudentID,#CourseID,#DateEnrolled,#Score)";
SqlCommand insertComm = new SqlCommand(insertStm, conn);
insertComm.Parameters.AddWithValue("#StudentID", enrollment.EnrollmentData.StudentData.StudentID);
insertComm.Parameters.AddWithValue("#CourseID", enrollment.EnrollmentData.CourseData.CourseID);
insertComm.Parameters.AddWithValue("#DateEnrolled", enrollment.EnrollmentData.DOE);
insertComm.Parameters.AddWithValue("#Score", enrollment.Score);
try
{
conn.Open();
insertComm.ExecuteNonQuery();
}
catch (SqlException sqlex)
{
throw sqlex;
}
finally
{
conn.Close();
}
Business Layer...............
public class StudentScore
{
public Enrollment EnrollmentData { get; set; }
public int Score { get; set; }
public StudentScore()
{
}
public StudentScore(Enrollment aEnrollmentData, int aScore)
{
EnrollmentData = aEnrollmentData;
Score = aScore;
}
}
Presentation Layer..................
private void button5_Click(object sender, EventArgs e)
{
StudentScore enrollment = new StudentScore();
enrollment.EnrollmentData.StudentData.StudentID = comboBox1.SelectedValue.ToString();
enrollment.EnrollmentData.CourseData.CourseID = comboBox2.SelectedValue.ToString();
enrollment.EnrollmentData.DOE = DateTime.Now;
EnrollmentDB.AddEnrollment(enrollment);
MessageBox.Show("Student is enrolled this course.");
}
It show me this error
Exception : enrollment.EnrollmentData.StudentData.StudentID =
comboBox1.SelectedValue.ToString();
Please help me how do I fix it?
enrollment.EnrollmentData has not been initialized. In the absence of further details, change
StudentScore enrollment = new StudentScore();
to
StudentScore enrollment = new StudentScore(new Enrollment(), 0);

Categories