WPF Enabling a button with SQL condition - c#

I want to make button enabled, depending on what data is in SQL table. I made table with boolean type column and now I want WPF to read it and make button enabled or disabled. I made class for connection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Windows;
using System.Data.SqlClient;
using System.Configuration;
namespace WpfCalendar.Classes
{
class SQLconnection
{
public static string GetConnectionStrings()
{
string strConString = ConfigurationManager.ConnectionStrings["conString"].ToString();
return strConString;
}
public static string sql;
public static SqlConnection con = new SqlConnection();
public static SqlCommand cmd = new SqlCommand("",con);
public static SqlDataReader rd;
public static DataTable dt;
public static SqlDataAdapter da;
public static void openConnection()
{
try
{
if (con.State == ConnectionState.Closed)
{
con.ConnectionString = GetConnectionStrings();
con.Open();
}
}
catch (Exception ex)
{
MessageBox.Show("Brak połaczenia" + Environment.NewLine + ex.Message.ToString(), "C# WPF connect to SQL server", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public static void closeConnection()
{
try
{
if(con.State == ConnectionState.Open)
{
con.Close();
}
}
catch(Exception)
{
}
}
}
}
And my window xaml.cs
public partial class Kalendarz : Window
{
public Kalendarz()
{
InitializeComponent();
}
private void Sprawdzanko1(object sender, RoutedEventArgs e)
{
DateTime dt = DateTime.Now;
bool klikniente;
SQLconnection.openConnection();
SQLconnection.cmd.CommandText = SQLconnection.sql;
SQLconnection.sql = "Select [Otwarte] FROM Okienka WHERE Dzien LIKE '1';";
SQLconnection.cmd.CommandType = CommandType.Text;
SQLconnection.da = new SqlDataAdapter(SQLconnection.cmd);
klikniente = (bool)SQLconnection.cmd.ExecuteScalar();
if (klikniente == true && dt.Day == 1 && dt.Month == 12)
{
b1.IsEnabled = true;
}
else
{
b1.IsEnabled = false;
}
SQLconnection.closeConnection();
}
I'm making a WPF advent calendar so the idea is to check if the button was clicked before and if date is correct. But the buttons don't react an I'm pretty sure the code isn't even executed...

Ok so I think I got it. It works so I'm fine with it :D
private void Sprawdzanko1()
{
bool klikniente;
using (SQLconnection.con)
{
SQLconnection.openConnection();
SqlCommand cmd = new SqlCommand("Select [Otwarte] FROM Okienka WHERE Dzien LIKE '1';", SQLconnection.con);
klikniente = (bool)cmd.ExecuteScalar();
SQLconnection.closeConnection();
}
if (klikniente == false && dt.Day == 1 && dt.Month == 12)
{
b1.IsEnabled = true;
}
else
{
b1.IsEnabled = false;
}
}
And then you call Sprawdzanko1();

Related

Mysql Windows Forms | Connection must be valid and open

Good day, friends, help to finalize this class, here's the thing:
I'm trying to make it so that if there is no connection to the database, one action will be performed in the form, there will be a connection to the database, we perform another action.
Now the problem is that if you do not connect to the database, there will be terrible lags of the application itself.
using System;
using MySql.Data.MySqlClient;
namespace Launcher.SupportClass
{
public class Web_MysqlDataBase : IDisposable
{
MySqlConnection connection = new MySqlConnection("server=127.0.0.1;port=3306;username=root;password=1234;database=test-test;");
public bool Connection_BD;
public void OpenConnect()
{
if (connection.State == System.Data.ConnectionState.Closed)
{
try
{
connection.Open();
CheckConnect();
}
catch
{
CheckConnect();
}
finally
{
CheckConnect();
closedConnection();
}
}
}
public void closedConnection()
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
public MySqlConnection getConnection()
{
return connection;
}
public void Dispose()
{
Dispose(true);
}
public void CheckConnect()
{
if (connection.State == System.Data.ConnectionState.Open)
{
Connection_BD = true;
}
if (connection.State == System.Data.ConnectionState.Closed)
{
Connection_BD = false;
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Close();
connection = null;
Dispose();
}
}
}
}
}
Next, I want to perform this simple construction, but there are already errors, what am I doing wrong?
Web_MysqlDataBase bd = new Web_MysqlDataBase();
bd.OpenConnect();
string query = "SELECT `text_update` FROM `launcher` WHERE `opened`='1'";
MySqlCommand command = new MySqlCommand(query, bd.getConnection());
if (bd.Connection_BD == true)
{
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
string name = command.ExecuteScalar().ToString();
ScrollingLeable.Text = name;
ScrollingLeable.position = 750;
ScrollsLeable.Visible = true;
ScrollingLeable.Visible = true;
}
else
{
ScrollsLeable.Visible = false;
ScrollingLeable.Visible = false;
}
}
else
{
ScrollsLeable.Visible = false;
ScrollingLeable.Visible = false;
}

Open Datareader causing error and not pulling correct information

I am not sure how to correct the error of having an open DataReader, if I close it then it throws a fits. I have tried changing the command names as well as other names to prevent this issue, but it seems to be persistent. That is the first issue, the second issue is I am not able to pull the correct data from my list. When I pass the information from the database to the list it should be in columns of FirstName to the First Name list, then Middle Initials and so on. I feel like that might be an issue with the command string q.
I have tried this in multiple different ways, but none of it seems to be working. I have changed reader names, tried to close and open as needed. As for the pulling data I have tried to change the command string q, I have tried to pass the information differently.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Windows.Forms;
namespace DEITO
{
/// <summary>
/// Interaction logic for Customers.xaml
/// </summary>
public partial class Customers : Window
{
public static List<String> CustomerFirstName = new List<string>();
List<String> CustomerMiddleInitial = new List<string>();
List<String> CustomerLastName = new List<string>();
List<String> CustomerTaxClass = new List<string>();
List<String> CustomerEmail = new List<string>();
public Customers()
{
InitializeComponent();
RetriveCustomerInfo();
}
public static string name;
private List<String> RetriveCustomerInfo()
{
DataTable dt = new DataTable();
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\SCook\Documents\LoginInformation.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
string q = "SELECT * FROM CustomerInfo";
SqlCommand Comm = new SqlCommand(q, con);
// SqlDataAdapter DAdapter = new SqlDataAdapter();
SqlDataReader ReadThis = Comm.ExecuteReader();
int Readerint = 0;
while (ReadThis.Read())
{
// int StringCount = 0;
name = ReadThis.GetString(1);
//string MN = Reader.GetString(StringCount);
//string LN = Reader.GetString(StringCount);
//string TC = Reader.GetString(StringCount);
//string EM = Reader.GetString(StringCount);
CustomerFirstName.Add(name);
//CustomerMiddleInitial.Add(MN);
//CustomerLastName.Add(LN);
//CustomerTaxClass.Add(TC);
//CustomerEmail.Add(EM);
// cmd..Parameters.Add(new SqlParameter("#FMT", name);
Comm.ExecuteNonQuery();
Comm.Parameters.Clear();
con.Close();
Readerint = Readerint + 1;
}
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
/*string output = string.Join("\n", CustomerFirstName);
string Out1 = string.Join("\n", CustomerMiddleInitial);
string Out2 = string.Join("\n", CustomerLastName);
string Out3 = string.Join("\n", CustomerTaxClass);
string Out4 = string.Join("\n", CustomerEmail);
System.Windows.Forms.MessageBox.Show(output); */
return CustomerFirstName;
}
private void Exit_Clicked(object sender, RoutedEventArgs e)
{
this.Close();
}
public class CustomerInformation
{
public string FirstName { get; set; }
public string MiddleInital { get; set; }
public string LastName { get; set; }
public string TaxClass { get; set; }
public string Email { get; set; }
}
public void FillDataGridWithCustInfo()
{
int ArrayNum = 0;
Int32 length = CustomerFirstName.Count;
while (length >= ArrayNum)
{
CustomerInformation TempCust = new CustomerInformation();
TempCust.FirstName = name;
CustomerDataGrid.Items.Add(TempCust);
ArrayNum = ArrayNum + 1;
}
}
private void AddnewCustomer_Click(object sender, RoutedEventArgs e)
{
CustomerInformation TempCust = new CustomerInformation();
TempCust.FirstName = FirstNameText.Text;
TempCust.MiddleInital = MiddleInitalText.Text;
TempCust.LastName = LastNameText.Text;
TempCust.TaxClass = TaxClassText.Text;
TempCust.Email = EmailText.Text;
CustomerDataGrid.Items.Add(TempCust);
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\SCook\Documents\LoginInformation.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
string q = "insert into CustomerInfo (FirstName, MiddleInital, LastName, TaxClass, Email) Values(#FMT, #MIT, #LNT, #TCT, #EMT)";
SqlCommand Comm = new SqlCommand(q, con);
Comm.Parameters.AddWithValue("#FMT", FirstNameText.Text);
Comm.Parameters.AddWithValue("#MIT", MiddleInitalText.Text);
Comm.Parameters.AddWithValue("#LNT", LastNameText.Text);
Comm.Parameters.AddWithValue("#TCT", TaxClassText.Text);
Comm.Parameters.AddWithValue("#EMT", EmailText.Text);
Comm.ExecuteNonQuery();
Comm.Parameters.Clear();
con.Close();
System.Windows.Forms.MessageBox.Show("You have successfully added to the database");
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//RetriveCustomerInfo();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
FillDataGridWithCustInfo();
}
}
}
I am trying to take the data from database CustomerInfo and fill it into CustomerDataGrid. This seems like it should be less complex than I am making it out to be, but SQL is not my favorite language to have to deal with. When I change the .getstring(some Number) from 0 to 1 it is only pulling from the first row of data. so instead of giving me the first name of the next person down it will give me the middle initial.
Exception message: There is already an open datareader associated with this command which must be closed first.

Int value not being passed with object even though get/set methods are used

I'm sorry if my headline is confusing, but I didn't know how to express my problem differently. I have 2 classes, both windows forms; one of them is a login interface, and the other is a shop interface that the user is taken to if his login is valid. Now, I'm trying to pass the username and password along to the shop interface class so I can subtract "purchases" from the correct row in the database, but for some reason this is not working. I have tested my method with just passing valid username and password strings directly through the code, and if I do that, the method works fine. Debug mode too shows that the value of the username and password is not passed along to the shop interface class through the get methods. Hope you can help, thanks in advance, and sorry for the quite big block of text :)
Here are the two classes in question, plus the class with the methods that I am using for the database:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShopshopFinalfinal
{
public partial class LoginInterface : Form
{
DatabaseConnection dbConnection = new DatabaseConnection();
private ShopInterface shop1Interface;
private RegisterInterface reg1Interface;
private string _username;
private string _password;
public void SetUsername(string username)
{
_username = username;
}
public void SetPassword(string password)
{
_password = password;
}
public string GetUsername()
{
return _username;
}
public string GetPassword()
{
return _password;
}
public LoginInterface()
{
InitializeComponent();
txt_password.PasswordChar = '*';
}
private void btn_login_Click(object sender, EventArgs e)
{
if (dbConnection.CheckUsername(txt_username.Text) == 1 && dbConnection.CheckPassword(txt_password.Text) == 1)
{
SetUsername(txt_username.Text);
SetPassword(txt_password.Text);
//txt_username.Clear();
//txt_password.Clear();
shop1Interface = new ShopInterface();
shop1Interface.Show();
}
}
private void btn_register_Click(object sender, EventArgs e)
{
reg1Interface = new RegisterInterface();
reg1Interface.Show();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShopshopFinalfinal
{
public partial class ShopInterface : Form
{
private DatabaseConnection dbConnection = new DatabaseConnection();
private LoginInterface login = new LoginInterface();
public ShopInterface()
{
InitializeComponent();
}
private void btn_buyapple_Click(object sender, EventArgs e)
{
//string username = login.GetUsername();
//string password = login.GetPassword();
dbConnection.Transaction(login.GetUsername(), login.GetPassword(), 10);
}
}
}
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShopshopFinalfinal
{
class DatabaseConnection
{
private SqlConnection conn;
private SqlDataReader rdr;
private SqlCommand cmd;
public DatabaseConnection()
{
conn = new SqlConnection(Properties.Settings.Default.connectionstring);
}
public int CheckUsername(string username)
{
int result = 0;
//Opret den ønskede SQL kommmando - her tjekker den om username fra textboxen er lig en i User table.
cmd = new SqlCommand("select * from dbo.Users where Username ='" + username + "'", conn);
//Åbn forbindelsen til databasen.
conn.Open();
//Udfører det ønskede SQL statement på databasen.
rdr = cmd.ExecuteReader();
//Tjek om den har læst og om det er rigtigt.
if (rdr.Read())
{
result = 1;
}
else
{
result = 0;
}
//Luk forbindelsen til databasen.
conn.Close();
return result;
}
public int CheckPassword(string password)
{
int result = 0;
//Opret SQL-kommando - tjek om password fra textbox er lig med et i databasen.
cmd = new SqlCommand("select * from dbo.Users where Password ='" + password + "'", conn);
//Åben forbindelsen.
conn.Open();
//Udfør det ønskede SQL statement på databasen.
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
result = 1;
}
else
{
result = 0;
}
conn.Close();
return result;
}
public void RegisterUser(string username, string password)
{
conn.Open();
cmd =
new SqlCommand("insert into dbo.Users (Username, Password, IsAdmin, Balance) values ('" +
username +
"', '" + password + "', '0', '0')", conn);
rdr = cmd.ExecuteReader();
rdr.Close();
conn.Close();
}
public void Transaction(string username, string password, int price)
{
conn.Open();
cmd = new SqlCommand("update dbo.Users set Balance = Balance - " + price + " where Username = '"+username+"' and Password = '"+password+"'", conn);
rdr = cmd.ExecuteReader();
rdr.Close();
conn.Close();
}
}
}
You are almost there but you are not passing the data to the other form. Change this in ShopInterface:
private LoginInterface login = new LoginInterface();
to this:
public LoginInterface Login {get; set;}
Then in your LoginInterface do this before you show the shop1Interface:
private void btn_login_Click(object sender, EventArgs e)
{
if (dbConnection.CheckUsername(txt_username.Text) == 1 && dbConnection.CheckPassword(txt_password.Text) == 1)
{
SetUsername(txt_username.Text);
SetPassword(txt_password.Text);
//txt_username.Clear();
//txt_password.Clear();
shop1Interface = new ShopInterface();
// This is the line you need
shop1Interface.Login = this;
shop1Interface.Show();
}
}
Now because you passed a reference to your LoginInterface to shop1Interface, you can now access it like this:
private void btn_buyapple_Click(object sender, EventArgs e)
{
// Now it will work
string username = this.Login.GetUsername();
string password = this.Login.GetPassword();
dbConnection.Transaction(login.GetUsername(), login.GetPassword(), 10);
}
The problem is that you have the ShopInterface creating a brand new instance of LoginInterface, which would have all of its properties in their default state. This is not the same instance as the one that actually has the values, hence why they are blank.
I think that rather than trying to find a way to get ShopInterface to take the values from a LoginInterface (which would mean a strong dependency from ShopInterface to LoginInterface), a better approach would be to provide a way to pass them in:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShopshopFinalfinal
{
public partial class ShopInterface : Form
{
private DatabaseConnection dbConnection = new DatabaseConnection();
private string Username { get; set; }
private string Password { get; set; }
public ShopInterface(string username, string password)
{
InitializeComponent();
Username = username;
Password = password;
}
private void btn_buyapple_Click(object sender, EventArgs e)
{
dbConnection.Transaction(username, password, 10);
}
}
}
Then you can have the LoginInterface do this:
shop1Interface = new ShopInterface(txt_username.Text, txt_password.Text);
shop1Interface.Show();

C# after login, redirect to another form with existing parameters

I'm trying to redirect a authenticated user to another c# form.
After the user is authenticated using his username and password he will be sent to another form. Sadly I can't access the old parameters from the old form element.
Here's a screenshot of both form elements:
My code looks like the following:
Form 1:
using MaterialSkin;
using MaterialSkin.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Helpful
{
public partial class Form1 : MaterialForm
{
public Form1()
{
InitializeComponent();
var materialSkinManager = MaterialSkinManager.Instance;
materialSkinManager.AddFormToManage(this);
materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
materialSkinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
private void materialRaisedButton1_Click(object sender, EventArgs e)
{
try
{
string username = materialSingleLineTextField1.Text;
string password = materialSingleLineTextField2.Text;
database_connector dbConnect = new database_connector();
bool db_response = dbConnect.user_check(username, password);
if (db_response == true)
{
MessageBox.Show("User authentificated.");
new Form2().Show();
this.Hide();
}
else
{
MessageBox.Show("Please try again, wrong user credentials.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Form 2:
using MaterialSkin;
using MaterialSkin.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Helpful
{
public partial class Form2 : MaterialForm
{
public Form2()
{
InitializeComponent();
var materialSkinManager = MaterialSkinManager.Instance;
materialSkinManager.AddFormToManage(this);
materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
materialSkinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
}
}
The database_connector class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Helpful
{
class database_connector
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
// Constructor
public database_connector()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "xxx";
database = "xxx";
uid = "xxx";
password = "xxx";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator.");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
// Select statement
public bool user_check(string username, string password)
{
string query = "SELECT username, password from swear_tool where username='" + username + "' and password = '" + password + "'";
bool hasRecords = false;
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
if (dataReader.HasRows)
{
while (dataReader.Read())
{
hasRecords = true;
}
}
dataReader.Close();
this.CloseConnection();
}
return hasRecords;
}
}
}
My question is, how could I use the variable username in the form 2 now without the user entering it again?
I would appreciate any kind of help.
To achieve what you want, following the POO and Layers programming, you must create an class which will save your data.
With the following example I made, you could in the first screen set the parameters and it would be accessible from any other form which can see this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models
{
public class User
{
static private string cdUser;
static private int cdAcess;
static private string nmUser;
public static string CdUser
{
get
{
return cdUser;
}
set
{
cdUser = value;
}
}
public static int CdAcess
{
get
{
return cdAcess;
}
set
{
cdAcess = value;
}
}
public static string NmUser
{
get
{
return nmUser;
}
set
{
nmUser = value;
}
}
}
}
To save your data, you could do something like that:
User.CdUser = _login;
User.CdAcess = Convert.ToInt32(rdr["acess"].ToString());
User.NmUser = rdr["name"].ToString();
Create a constructor for Form2 that well get the name, or create a field in Form2 that well contain it and set it.
//first approach
new Form2(username).show();
//second approach
var f2 = Form2();
f2.username = username;
f2.show()

Insert button is not inserting data into the Database and no errors are given at all [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
This is the class that contains the insert method first I filled the fields and then made properties then the insert method and went to another class and made the insert button please help and no errors are given at all
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataBaseConnection;
using System.Data.SqlClient;
namespace Students
{
public class Program
{
// Filling The Fields
private int StudentID = 0;
private string StudentName = "";
private int SudentAge = 0;
private SqlConnection Connection = new SqlConnection();
// Properties
// Student ID
public int StudentID1
{
get { return StudentID; }
set { StudentID = value; }
}
// Student Name
public string StudentName1
{
get { return StudentName; }
set { StudentName = value; }
}
// SudentAge
public int SudentAge1
{
get { return SudentAge; }
set { SudentAge = value; }
}
// Insert Method
public void Insert()
{
SqlConnection Connection = new SqlConnection(DBC.Constructor);
string Sql = "insert into Details (StudentID,StudentName,SudentAge) Values (#StudentID1,#StudentName1,#SudentAge1)";
SqlCommand Command = new SqlCommand(Sql, Connection);
Command.Parameters.AddWithValue("#StudentID1", StudentID);
Command.Parameters.AddWithValue("#StudentName1", StudentName);
Command.Parameters.AddWithValue("#StudentAge1", SudentAge);
try
{
Connection.Open();
Command.ExecuteNonQuery();
try
{
Console.WriteLine("Execute success");
}
catch
{
Console.WriteLine("Execute is not success");
}
}
catch
{
Console.WriteLine("Error saving Student");
}
finally
{
try
{
Connection.Close();
}
catch
{
}
}
}
this is my button class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Students;
using System.Data.SqlClient;
using DataBaseConnection;
using System.Data;
public partial class SignUp : System.Web.UI.Page
{
public static string Constructor = "Data Source=FOUAD-PC;Initial Catalog=Students;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void InsertButton_Click(object sender, EventArgs e)
{
Program X = new Program();
X.StudentName1 = NameTxt.Text;
X.SudentAge1 = int.Parse(AgeTxt.Text);
X.StudentID1 = int.Parse(IDTxt.Text);
X.Insert();
}
}
and no errors are given at all
I answer to that, you use the Console.WriteLine to show the error, or the success.
But you call this object from inside a web page that actually have no access to console, and not read that console writeline. So your errors will not been shown when you call it as it is from a web page, only when you call it from console application.
How to rewrite it.
Use a string inside your object for the errors and write there your error, eg
catch(Exception x)
{
// change that
// Console.WriteLine("Execute is not success");
// with
lastError = "Execute is not success - reason:" + x.ToString();
}
and lastError is a public string on your object, and check it after you make your calls.
You also have some "on the air" try/catch that not work at all if this is the correct code of you.
// Insert Method
public int Insert(Program program)
{
int resutl;
SqlConnection Connection = new SqlConnection(DBC.Constructor);
string Sql = "insert into Details (program.StudentID,program.StudentName,program.SudentAge) Values (#StudentID1,#StudentName1,#SudentAge1)";
SqlCommand Command = new SqlCommand(Sql, Connection);
Command.Parameters.AddWithValue("#StudentID1", program.StudentID);
Command.Parameters.AddWithValue("#StudentName1", program.StudentName);
Command.Parameters.AddWithValue("#StudentAge1", program.SudentAge);
try
{
Connection.Open();
resutl= Command.ExecuteNonQuery();
try
{
Console.WriteLine("Execute success");
}
catch
{
Console.WriteLine("Execute is not success");
}
Return resutl;
}
catch
{
Console.WriteLine("Error saving Student");
}
finally
{
try
{
Connection.Close();
}
catch
{
}
}

Categories

Resources