Error adding usercontrol to winform - c#

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!

Related

How get combobox text value with database in c#

I want to select an item from a combobox and it should show the item that has been selected.
When I use:
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedIndex);
it will only show the number of the item
if I use
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedItem);
or
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedItem.ToString());
It will only print a message like "System.Data.DataRowView"
Here's the whole Code:
private void GetCategory()
{
Con.Open();
SqlCommand cmd = new SqlCommand("Select * from CategoryTBL", Con);
SqlDataReader Rdr;
Rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("CategoryName", typeof(String));
dt.Load(Rdr);
categCB.ValueMember = "CategoryName";
categCB.DataSource = dt;
Con.Close();
}
private void addbtn_Click(object sender, EventArgs e)
{
if (itemIDtxt.Text == "" || itemnametxt.Text == "" || descriptiontxt.Text == "" || manufacturertxt.Text == "" || amounttxt.Text == "" || quantitytxt.Text == "")
{
MessageBox.Show("Missing Data");
}
else
{
int tAmount = Convert.ToInt32(amounttxt.Text) * Convert.ToInt32(quantitytxt.Text);
try
{
Con.Open();
SqlCommand cmd = new SqlCommand("insert into ItemDetailTBL values(#iID, #ItemNa, #ItemCateg, #ItemDesc, #ItemMan, #ItemAmoun, #ItemQua, #ItemExDate, #ItemtAmount)", Con);
cmd.CommandType = CommandType.Text;
Int32.Parse(itemIDtxt.Text);
cmd.Parameters.AddWithValue("#iID", itemIDtxt.Text);
cmd.Parameters.AddWithValue("#ItemNa", itemnametxt.Text);
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedIndex);
cmd.Parameters.AddWithValue("#ItemDesc", descriptiontxt.Text.ToString());
cmd.Parameters.AddWithValue("#ItemMan", manufacturertxt.Text);
cmd.Parameters.AddWithValue("#ItemAmoun", amounttxt.Text);
cmd.Parameters.AddWithValue("#ItemQua", quantitytxt.Text);
cmd.Parameters.AddWithValue("#ItemExDate", expdatepick.Text);
cmd.Parameters.AddWithValue("#ItemtAmount", tAmount);
cmd.ExecuteNonQuery();
MessageBox.Show("New Data Has been Added to the Inventory");
Con.Close();
Showitem();
addHis();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
Here is a pattern to following. Create a class representing the category table and override ToString with what should be shown in the ComboBox.
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public override string ToString() => CategoryName;
}
Rewrite you code to read data to this pattern
public static List<Category> Categories()
{
List<Category> list = new List<Category>() ;
using var cn = new SqlConnection(ConnectionString);
using var cmd = new SqlCommand { Connection = cn,
CommandText = "SELECT CategoryID ,CategoryName FROM dbo.Categories" };
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new Category() { CategoryID = reader.GetInt32(0), CategoryName = reader.GetString(1) });
}
return list;
}
The method above for this example resides in a class named SqlServerOperations.
Form code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
categCB.DataSource = SqlServerOperations.Categories();
}
private void GetCurrentCategoryButton_Click(object sender, EventArgs e)
{
var current = (Category)categCB.SelectedItem;
MessageBox.Show($"{current.CategoryID,-5}{current.CategoryName}");
}
}

How to load in data from database to listbox

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

How To Identify button click of a node in dataTreeListView1 in C#

I have dataTreeListView named dataTreeListView1 i wish to get the name of the node which i clicked can any one please help me to do this
in the above picture if i click yes i wish to get yes on messagebox
what i tried to do is
private void dataTreeListView1_AfterSelect(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
and the node are loaded dynamically means they are from database.
List<Class3> list = new List<Class3>();
list = Class3.GetList(startDate, endDate, con);
this.dataTreeListView1.ParentKeyAspectName = "ParentId";
this.dataTreeListView1.RootKeyValueString = "NUll";
BrightIdeasSoftware.OLVColumn col = new BrightIdeasSoftware.OLVColumn();
col.Width = 10;
dataTreeListView1.DataSource = list;
foreach (ColumnHeader column in this.dataTreeListView1.Columns)
{
column.Width = 140 + 140 + this.dataTreeListView1.SmallImageSize.Width;
}
this.dataTreeListView1.Columns.RemoveByKey("Id");
this.dataTreeListView1.Columns.RemoveByKey("ParentId");
this is how i show data in datatreelist view
public Class3()
{
this.xName = "";
this.xId = "";
this.xParentId = "";
this.xcredit = 0.0M;
this.xdebit = 0.0M;
this.xx = 0.0M;
this.xy = 0.0M;
}
public String Ledger
{
get { return this.xName; }
set { this.xName = value; }
}
public String Id
{
get { return this.xId; }
set { this.xId = value; }
}
public String ParentId
{
get { return this.xParentId; }
set { this.xParentId = value; }
}
public Decimal Credit
{
get { return this.xcredit; }
set { this.xcredit = value; }
}
public Decimal Debit
{
get { return this.xdebit; }
set { this.xdebit = value; }
}
public decimal x
{
get { return this.xx; }
set { this.xx = value; }
}
public decimal y
{
get { return this.xy; }
set { this.xy = value; }
}
public static List<Class3> GetList(DateTime startDate, DateTime endDate, SqlConnection con)
{
List<Class3> oList = new List<Class3>();
Buisiness b = new Buisiness();
try
{
decimal totalcredit = 0;
decimal totaldebit = 0;
con.Open();
// // Make sql readable
DataTable dt = new DataTable();
string sql = #"Select Ledger.LedId,Ledger.LedName,Ledger.MasterLedger from Ledger where Ledger.Date >= #prmStartDate and Ledger.Date <= #prmEndDate group by Ledger.MasterLedger,Ledger.LedId,Ledger.LedName";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
Class3 oClass = new Class3();
oClass.Ledger = da["LedName"].ToString();
oClass.Id = da["LedId"].ToString();
oClass.ParentId = da["MasterLedger"].ToString();
Dictionary<string, decimal> d = b.findclosingbalanceofledger(da["LedId"].ToString());
/* if (da["MasterLedger"].ToString() == "NUll")
{
oClass.Debit = findsumofallchilds(da["LedId"].ToString(), con, startDate, endDate);
}
else
{*/
if (d.FirstOrDefault().Key == "debit")
{
d.FirstOrDefault().Value.ToString();
d.FirstOrDefault().Value.ToString();
totaldebit = totaldebit + d.FirstOrDefault().Value;
oClass.Debit = d.FirstOrDefault().Value;
}
else if (d.FirstOrDefault().Key == "credit")
{
d.FirstOrDefault().Value.ToString();
totalcredit = totalcredit + d.FirstOrDefault().Value;
oClass.Credit = d.FirstOrDefault().Value;
}
/* }*/
oList.Add(oClass);
}
}
con.Close();
}
catch (Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
con.Close();
}
return oList;
}
i have changed my code this
private void dataTreeListView1_AfterSelect(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
to
private void dataTreeListView1_CellClick(object sender, CellClickEventArgs e)
{
MessageBox.Show("helo");
}
but no change

Insert null datetime from sql table into datagridview silverlight

I have problem with null values, I want to insert from sql table nulls ( from datetime column) into datagridview, and datagridview return error.
Communication Exception was unhandled by user code
Code:
public class Pismo
{
public int Id { get; set; }
public string PW { get; set; }
public DateTime? Data_Wysylki { get; set; }
}
public ObservableCollection<Pismo> ReadPisma(int id_pismo)
{
ObservableCollection<Pismo> result = new ObservableCollection<Pismo>();
string nwConn = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlDataReader dr;
SqlConnection conn = new SqlConnection(nwConn);
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = "INSERT";
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
Pismo wiersz = new Pismo();
wi.Id = dr.GetInt32(0);
wi.PW = dr.GetString(1);
wi.Data_Wysylki = dr.GetDateTime(2);
result.Add(wi);
}
dr.Close();
return result;
}
catch (SqlException e)
{
Pismo wi = new Pismo();
wi.Id = e.Message;
result.Add(wi);
return result;
}
finally
{
conn.Close();
};
}
<sdk:DataGridTextColumn Header="Data WysyƂki" Binding="{Binding Data_Wysylki, StringFormat='yyyy/MM/dd'}"/>
I try to add this below
if (wi.Data_Wysylki.HasValue) wi.Data_Wysylki = dr.GetDateTime(16);
after that error didnt show but in datagridview all column (even with some dates) was null

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.

Categories