How to transfer Image from one form to another form? - c#

I have inserted an image on the 1st form namely Add_Staff and want to get that image on the 2nd form namely Staff_Detail's data gridview. how I can pass reference of add_staff images to staff_detail form's data gridview. Here is the code.
Insertion Code: -
private void BTNSTAFF_Click(object sender, EventArgs e)
{
if (staffid.Text == "")
{
if (teachername.Text == "" || saddress.Text == "" || semail.Text == "" || contact.Text == "" || jobspeciality.Text == "")
{
MessageBox.Show("All Fields Required");
}
else
{
Image pimg = pictureBox1.Image;
ImageConverter converter = new ImageConverter();
var ImageConvert = converter.ConvertTo(pimg, typeof(byte[]));
conn.Open();
//Values Inserted into Course
SqlCommand cmd = new SqlCommand("insert into staff values (#a,#b,#c,#d,#e,#g)", conn);
cmd.Parameters.AddWithValue("#a", teachername.Text);
cmd.Parameters.AddWithValue("#b", saddress.Text);
cmd.Parameters.AddWithValue("#c", semail.Text);
cmd.Parameters.AddWithValue("#d", contact.Text);
cmd.Parameters.AddWithValue("#e", jobspeciality.Text);
cmd.Parameters.AddWithValue("#g", ImageConvert);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
frm1.RefreshGrid();
conn.Close();
Staff_Clear();
this.Hide();
}
}}
Staff Detail Code for View Deatil: -
public partial class Staff_Detail : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\mudas\source\repos\WindowsFormsApp1\WindowsFormsApp1\WindowsFormsApp1\Database1.mdf;Integrated Security=True");
public static string column_id = "";
public static string column_name = "";
public static string column_address = "";
public static string column_email = "";
public static string column_contact = "";
public static string column_job = "";
public Staff_Detail()
{
InitializeComponent();
View();
}
public void View()
{
try
{
dataGridView4.Rows.Clear();
// if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From staff", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String column_getid = dr["id"].ToString();
String column_getname = dr["name"].ToString();
String column_getaddress = dr["address"].ToString();
String column_getemail = dr["email"].ToString();
String column_getcontact = dr["contact"].ToString();
String column_getjob = dr["job"].ToString();
dataGridView4.Rows.Add(column_getid, column_getname, column_getaddress, column_getemail, column_getcontact, column_getjob, "Edit/Delet");
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = dataGridView4.CurrentCell.RowIndex;
String Column_id = dataGridView4.Rows[rowIndex].Cells[0].Value.ToString();
String Column_name = dataGridView4.Rows[rowIndex].Cells[1].Value.ToString();
String Column_address = dataGridView4.Rows[rowIndex].Cells[2].Value.ToString();
String Column_email = dataGridView4.Rows[rowIndex].Cells[3].Value.ToString();
String Column_contact = dataGridView4.Rows[rowIndex].Cells[4].Value.ToString();
String Column_job = dataGridView4.Rows[rowIndex].Cells[5].Value.ToString();
column_id = Column_id;
column_name = Column_name;
column_address = Column_address;
column_email = Column_email;
column_contact = Column_contact;
column_job = Column_job;
Add_Staff ad = new Add_Staff(this);
ad.Show();
ad.BringToFront();
}
}

Related

LOGIN FORM using class

I have button1_click in Form1.. and i want string usernamebox.text and passwordbox.text to login class i created it before.. and I got stuck here.. Login class work but button code not how Get textBox value in from1 to login class
private void button1_Click(object sender, EventArgs e)
{
String c1 = new String();
c1 = UsernameBox.Text;
Login.Validation_user(c1.ToString());
String c2 = new String();
c2 = PasswordBox.Text;
Login.Validation_pass(c2.ToString());
}
this my string
static string connectionClient = ConfigurationManager.ConnectionStrings["Sample2"].ConnectionString;
private static bool Validation { get; set; }
this my login class "Password"
public static void Validation_pass (string password)
{
if (!Validation)
{
using (MySqlConnection sqlConn = new MySqlConnection(connectionClient))
{
string checkForLogQuery = "SELECT * FROM Login WHERE Password=#pass";
MySqlCommand cmd = new MySqlCommand(checkForLogQuery, sqlConn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pass", password);
sqlConn.Open();
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result == 1)
{
MessageBox.Show("wellcome");
Form9 f9 = new Form9();
f9.Close();
f9.DialogResult = System.Windows.Forms.DialogResult.Cancel;
Form10 f10 = new Form10();
f10.Show();
Validation = true;
}
else
{
MessageBox.Show("Your Key was incorrect");
Validation = false;
}
}
}
else
{
}
}
and "username" it same what is above
You need to validate both password and username together
Here is an example
private void button1_Click(object sender, EventArgs e) {
var res = Login.Validate(PasswordBox.Text, UsernameBox.Text);
if (res)
MessageBox.Show("wellcome");
else
MessageBox.Show("UserName or Password dose not match.");
}
public static bool Validate(string password, string userName) {
if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(userName))
return false;
using(MySqlConnection sqlConn = new MySqlConnection(connectionClient)) {
string checkForLogQuery = "SELECT 1 FROM Login WHERE Password=#pass and LOWER(UserName) = LOWER(#userName)";
MySqlCommand cmd = new MySqlCommand(checkForLogQuery, sqlConn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pass", password);
cmd.Parameters.AddWithValue("#userName", userName);
sqlConn.Open();
var value = Convert.ToBoolean(cmd.ExecuteScalar());
sqlConn.Close();
return value;
}
}

How to refresh the login window when I'm closing the main window

I'm creating a small admin application using WPF. It has two windows; login window and main window. The login window is, of course, just username and password. And the main window shows data from the DB. The problem is; when I log in, the main window opens, and because of animations on the log in window, both the username and the password disappears. How can I refresh the log in window when I close the main window? Thanks!
The code for the login screen;
public partial class LoginScreen : Window
{
public LoginScreen()
{
InitializeComponent();
}
// Verify hashed password
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] buffer4;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != 0x31) || (src[0] != 0))
{
return false;
}
byte[] dst = new byte[0x10];
Buffer.BlockCopy(src, 1, dst, 0, 0x10);
byte[] buffer3 = new byte[0x20];
Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
{
buffer4 = bytes.GetBytes(0x20);
}
return ByteArraysEqual(buffer3, buffer4);
}
private static bool ByteArraysEqual(byte[] buffer3, byte[] buffer4)
{
bool areEqual = buffer3.SequenceEqual(buffer4);
return areEqual;
}
private void Button_Click_1(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection
{
ConnectionString = "server=db.***.**;database=***;uid=***;pwd=***;"
};
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT brukernavn, passord FROM admin_user WHERE brukernavn = '" + txtUsername.Text + "' AND passord ='" + txtPassword.Password + "'";
conn.Open();
cmd.ExecuteNonQuery();
MySqlDataReader reader = cmd.ExecuteReader();
String dbUsername = string.Empty;
String dbPassword = string.Empty;
while (reader.Read())
{
dbUsername += reader.GetString("brukernavn");
dbPassword += reader.GetString("passord");
}
if (dbUsername == "" || dbPassword == "")
{
Debug.WriteLine("Wrong username and Password");
string message = "Wrong username or password";
string title = "Error";
MessageBox.Show(message, title);
this.Show();
LoginScreen mm = new LoginScreen();
mm.Show();
}
else
{
Debug.WriteLine("Success");
this.Show();
MainWindow mm = new MainWindow();
mm.Show();
}
}
}
}
And this is the code for the main window;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e) { }
private void Show_Users_Click(object sender, RoutedEventArgs e)
{
MySqlConnection conn = new MySqlConnection
{
ConnectionString = "server=db.****.**;database=***;uid=***;pwd=***;"
}; try
{
conn.Open();
string Query = "SELECT accountId, level, email, name FROM account";
MySqlCommand createCommand = new MySqlCommand(Query, conn);
createCommand.ExecuteNonQuery();
MySqlDataAdapter dataAdp = new MySqlDataAdapter(createCommand);
DataTable dt = new DataTable("account");
dataAdp.Fill(dt);
EditUsers.ItemsSource = dt.DefaultView;
dataAdp.Update(dt);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Edit_Data_Click(object sender, RoutedEventArgs e)
{
MySqlConnection conn = new MySqlConnection
{
ConnectionString = "server=db.****.**;database=***;uid=***;pwd=***;"
}; try
{
conn.Open();
string Query = "SELECT accountId, level, email, name FROM account ";
MySqlCommand createCommand = new MySqlCommand(Query, conn);
createCommand.ExecuteNonQuery();
MySqlDataAdapter dataAdp = new MySqlDataAdapter(createCommand);
DataTable dt = new DataTable("account");
dataAdp.Fill(dt);
EditUsers.ItemsSource = dt.DefaultView;
dataAdp.Update(dt);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
LoginScreen in this you need to close LoginScreen screen
else
{
Debug.WriteLine("Success");
this.Close();
MainWindow mm = new MainWindow();
mm.Show();
}

Not able to insert. Doesn't show any errors but doesn't insert as well

This is my insert statement. Records are not inserting but no errors showing also. Please help
protected void btn_Add_Click(object sender, EventArgs e)
{
if (btn_Add.Text == "Submit")
{
string Height = txtHeight.Text;
string TopDia = Convert.ToString(txtTopDiaMeter.Text);
string BottomDia = Convert.ToString(txtBottomDiaMeter.Text);
string ShaftThick = Convert.ToString(txtShaftThick.Text);
string BlackWt = Convert.ToString(txtBlackWeight.Text);
string TotManHrPerPole = Convert.ToString(txtTotManHrPoleData.Text);
string Plate_Length = Convert.ToString(txtPlateLength.Text);
string PLATE_DIA = Convert.ToString(txtPlateDia.Text);
string PLATE_THICKNESS = Convert.ToString(txtPlateThick.Text);
System.Collections.Hashtable ht = (System.Collections.Hashtable)Session["UserDetails"];
Int64 UsrId = (Int64)ht["UserID"];
string CreatedBy = Convert.ToString(UsrId);
string FoundBoltId = Convert.ToString(ddlFoundationBolt.SelectedValue);
string PoleTypeId = Convert.ToString(ddlPoltype.SelectedValue);
string ProductTypeID = Convert.ToString(ddlPdtType.SelectedValue);
string Status = chkActive.Checked ? "True" : "False";
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
fileuploadimages.SaveAs(Server.MapPath("~/Images/Pole Data/" + filename));
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["valmont"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("Insert into DEF_POLE_DATA_MST(Height,TopDia,BottomDia,ShaftThick,BlackWt,TotManHrPerPole,Plate_Length,PLATE_DIA,PLATE_THICKNESS,CreatedBy,FoundBoltId,PoleTypeID,ProductTypeID,Status,ImagePath) values(#Height,#TopDia,#BottomDia,#ShaftThick,#BlackWt,#TotManHrPerPole,#Plate_Length,#PLATE_DIA,#PLATE_THICKNESS,#CreatedBy,#FoundBoltId,#PoleTypeId,#ProductTypeID,#Status,#ImagePath)", con);
cmd.Parameters.AddWithValue("#Height", Height);
cmd.Parameters.AddWithValue("#TopDia", TopDia);
cmd.Parameters.AddWithValue("#BottomDia", BottomDia);
cmd.Parameters.AddWithValue("#ShaftThick", ShaftThick);
cmd.Parameters.AddWithValue("#BlackWt", BlackWt);
cmd.Parameters.AddWithValue("#TotManHrPerPole", TotManHrPerPole);
cmd.Parameters.AddWithValue("#Plate_Length", Plate_Length);
cmd.Parameters.AddWithValue("#PLATE_DIA", PLATE_DIA);
cmd.Parameters.AddWithValue("#PLATE_THICKNESS", PLATE_THICKNESS);
cmd.Parameters.AddWithValue("#CreatedBy", CreatedBy);
cmd.Parameters.AddWithValue("#FoundBoltId", FoundBoltId);
cmd.Parameters.AddWithValue("#PoleTypeId", PoleTypeId);
cmd.Parameters.AddWithValue("#ProductTypeID", ProductTypeID);
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#ImagePath", "~/Images/Pole Data/" + filename);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
Accordian.SelectedIndex = 1;
JQUERYDisplay.ShowAlertMessage("Record Inserted Successfully");
CleraFields();
}
catch (Exception ex)
{
JQUERYDisplay.ShowAlertMessage(ex.Message);
}
finally
{
}
}
Here's the table:

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.

I am getting this error
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
I read this question and it states that the exception is caused because of not closing the connection. However, i close all the connection in my code
This is my code, it is simple
public partial class index : System.Web.UI.Page
{
private static string defaultReason = "reason not selected";
protected override object SaveViewState()
{
//save view state right after the dynamic controlss added
var viewState = new object[1];
viewState[0] = base.SaveViewState();
return viewState;
}
protected override void LoadViewState(object savedState)
{
//load data frm saved viewstate
if (savedState is object[] && ((object[])savedState).Length == 1)
{
var viewState = (object[])savedState;
fillReasons();
base.LoadViewState(viewState[0]);
}
else
{
base.LoadViewState(savedState);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (!String.IsNullOrEmpty(callerIDValue))
{
callerID.Value = callerIDValue;
if (!String.IsNullOrEmpty(callIDValue))
{
string query = "INSERT INTO Reason (callerID, callID, reason, timestamp) VALUES (#callerID, #callID, #reason, #timestamp)";
SqlConnection con = getConnection();
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callerID", callerIDValue);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", defaultReason);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerHtml = ee.Message;
}
}
else
{
message.InnerHtml = "Call ID is empty";
}
}
else
{
callerID.Value = "Undefined";
message.InnerHtml = "Caller ID is empty";
}
fillReasons();
}
else
{
}
}
private void fillReasons()
{
string query = "SELECT * FROM wrapuplist WHERE isEnabled = #isEnabled";
SqlConnection con = new SqlConnection(getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("isEnabled", true);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable results = new DataTable();
da.Fill(results);
int numberOfReasons = 0; // a integer variable to know if the number of the reasons becomes able to be divided by four
HtmlGenericControl div = null;
foreach (DataRow row in results.Rows)
{
numberOfReasons++;
if ((numberOfReasons % 4) == 1)
{
div = new HtmlGenericControl("div");
div.Attributes.Add("class", "oneLine");
}
RadioButton radioButton = new RadioButton();
radioButton.ID = "reason_" + row["reasonName"].ToString();
radioButton.GroupName = "reason";
radioButton.Text = row["reasonName"].ToString();
div.Controls.Add(radioButton);
if (numberOfReasons % 4 == 0)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
else if (numberOfReasons == results.Rows.Count)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
}
cmd.Dispose();
da.Dispose();
con.Close();
}
private SqlConnection getConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["vmpcon"].ConnectionString);
}
private string getConnectionString()
{
return ConfigurationManager.ConnectionStrings["wrapupconnection"].ConnectionString.ToString();
}
protected void buttonSaveClose_Click(object sender, EventArgs e)
{
var divcontrols = myValueDiv.Controls.OfType<HtmlGenericControl>();
bool isFound = false;
RadioButton checkedRadioButton = null;
foreach (HtmlGenericControl loHTML in divcontrols)
{
var checkedRadioButtons = loHTML.Controls.OfType<RadioButton>().Where(radButton => radButton.Checked).ToList();
foreach (RadioButton lobtn in checkedRadioButtons)
{
if (lobtn.Checked)
{
isFound = true;
checkedRadioButton = lobtn;
}
}
}
if (isFound)
{
sReasonError.InnerText = "";
string reason = "";
reason = checkedRadioButton.Text;
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (String.IsNullOrEmpty(callIDValue))
{
message.InnerText = "Call ID is empty";
}
else if (String.IsNullOrEmpty(callerIDValue))
{
message.InnerText = "Caller ID is empty";
}
else
{
message.InnerText = "";
string query2 = "SELECT * FROM Reason WHERE callID = #callID AND reason != #reason";
SqlConnection con = getConnection();
SqlCommand command2 = new SqlCommand(query2, con);
command2.Parameters.AddWithValue("#callID", callIDValue);
command2.Parameters.AddWithValue("#reason", defaultReason);
con.Open();
if (command2.ExecuteScalar() != null)
{
message.InnerText = "Already saved";
command2.Dispose();
con.Close();
}
else
{
command2.Dispose();
con.Close();
string notes = taNotes.InnerText;
string query = "UPDATE Reason SET reason = #reason, notes = #notes, timestamp = #timestamp WHERE callID = #callID";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", reason);
command.Parameters.AddWithValue("#notes", notes);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
message.InnerText = "Done Successfully";
//ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerText = "Error, " + ee.Message;
}
}
}
}
else
{
sReasonError.InnerText = "Required";
message.InnerText = "Select a reason";
//fillReasons();
}
}
}
as you see, all the connection are being closed, what wrong did I do please?
Closing connections and disposing should be in a finally block while using a try catch.
or use a using block like the one below
using(SqlConnection con = getConnection())
{
con.Open();
//Do your operation here. The connection will be closed and disposed automatically when the using scope is exited
}

checking user name or user email already exists

I am working in a simple registration page where the user can't enter the same user name or email, I made a code that prevent the user from entering the username and it worked but when I tried to prevent the user from entring the same username or email it didn't work.
and my question is, "How can I add another condition where the user can't enter email that already exists?"
I tried to do it in this code, but it did't work:
protected void Button_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection( ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString );
SqlCommand cmd1 = new SqlCommand("select 1 from Table where Name =#UserName", con);
SqlCommand cmd2 = new SqlCommand("select 1 from Table where Email=#UserEmail", con);
con.Open();
cmd1.Parameters.AddWithValue("#UserName", Name_id.Text);
cmd2.Parameters.AddWithValue("#UserEmail", Email_id.Text);
using (var dr1 = cmd1.ExecuteReader())
{
if (dr1.HasRows)
{
Label1.Text = "user name already exists";
}
using (var dr2 = cmd2.ExecuteReader())
{
if (dr2.HasRows)
{
Label1.Text = "email already exists";
}
else
{
dr1.Close();
dr2.Close();
//add new users
con.Close();
}
}
}
}
but i get this error:
There is already an open DataReader associated with this Command which must be closed first.
Like I said in my comment your design is bad !
First you should have Data Access Layer. This should be project in big solutions but in your case you can put it like new directory. In this directory you create SqlManager class here is the code:
public class SqlManager
{
public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["DevConnString"].ConnectionString;
}
}
public static SqlConnection GetSqlConnection(SqlCommand cmd)
{
if (cmd.Connection == null)
{
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
public static int ExecuteNonQuery(SqlCommand cmd)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static object ExecuteScalar(SqlCommand cmd)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteScalar();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataRow GetDataRow(SqlCommand cmd)
{
return GetDataRow(cmd, "Table");
}
public static DataRow GetDataRow(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
if (resultDst.Tables.Count > 0 && resultDst.Tables[0].Rows.Count > 0)
{
return resultDst.Tables[0].Rows[0];
}
else
{
return null;
}
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
After that you should have Business Object Layer. In bigger solution is project in your case directory. If you are in the page TaxesEdit.aspx, you should add Tax.cs class in the BO(business object).
Example of methods for the class, for your first button:
public DataSet GetTaxesByUserName(string userName)
{
SqlCommand cmd = new SqlCommand(#"
select 1 from Table where Name =#UserName");
cmd.Parameters.AddWithValue("#UserName", userName);
return DA.SqlManager.GetDataSet(cmd);
}
You fetch all the needed data in datasets. After that you make checks like taxesDst.Tables[0].Rows.Count > 0 (or == 0)
For Insert you can have method like this:
public virtual void Insert(params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");
SqlCommand cmd = new SqlCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");
string insertCols = string.Empty;
string insertParams = string.Empty;
for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";
string param = "#P" + i;
insertCols += colValues[i] + separator;
insertParams += param + separator;
cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}
cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);
DA.SqlManager.ExecuteNonQuery(cmd);
}
For this you need to have property TableName in the current BO class.
In this case this methods can be used everywhere and you need only one line of code to invoke them and no problems like yours will happen.
You have opened another DataReader inside the First and thats causing the problem. Here I have re-arranged your code a bit
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd1 = new SqlCommand("select 1 from Table where Name =#UserName", con),
cmd2 = new SqlCommand("select 1 from Table where Email=#UserEmail", con);
con.Open();
cmd1.Parameters.AddWithValue("#UserName", Name_id.Text);
cmd2.Parameters.AddWithValue("#UserEmail", Email_id.Text);
bool userExists = false, mailExists = false;
using (var dr1 = cmd1.ExecuteReader())
if (userExists = dr1.HasRows) Label1.Text = "user name already exists";
using (var dr2 = cmd2.ExecuteReader())
if (mailExists = dr2.HasRows) Label1.Text = "email already exists";
if (!(userExists || mailExists)) {
// can add User
}
You need to close one datareader before opening the other one. Although it's not how I'd do it, but you can deal with the runtime error by closing the datareader after each IF:
using (var dr1 = cmd1.ExecuteReader())
{
if (dr1.HasRows)
{
string Text = "user name already exists";
}
dr1.Close();
}
using (var dr2 = cmd2.ExecuteReader())
{
if (dr2.HasRows)
{
string ext = "email already exists";
}
else
{
//add new users
}
dr2.Close();
}
con.Close();
This may work, although there are a few things I would do differently...
protected void Button_Click(object sender, EventArgs e)
{
bool inputIsValid = true;
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
var userNameCmd = new SqlCommand("SELECT 1 FROM Table WHERE Name = #UserName", con);
var emailCmd = new SqlCommand("SELECT 1 FROM Table WHERE Email = #UserEmail", con);
con.Open();
userNameCmd.Parameters.AddWithValue("#UserName", Name_id.Text);
emailCmd.Parameters.AddWithValue("#UserEmail", Email_id.Text);
using (var userNameReader = userNameCmd.ExecuteReader())
{
if (userNameReader.HasRows)
{
inputIsValid = false;
Label1.Text = "User name already exists";
}
}
using (var emailReader = emailCmd.ExecuteReader())
{
if (emailReader.HasRows)
{
inputIsValid = false;
Label1.Text = "Email address already exists";
}
}
if (inputIsValid)
{
// Insert code goes here
}
con.Close();
}
Why don't you do something like this:
[Flags]
public enum ValidationStatus
{
Valid = 0 ,
UserNameInUse = 1 ,
EmailInUse = 2 ,
}
public ValidationStatus ValidateUser( string userName , string emailAddr )
{
ValidationStatus status ;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString ;
using ( SqlConnection con = new SqlConnection( connectionString ) )
using ( SqlCommand cmd = con.CreateCommand() )
{
cmd.CommandText + #"
select status = coalesce( ( select 1 from dbo.myTable t where t.UserName = #UserName ) , 0 )
+ coalesce( ( select 2 from dbo.myTable t where t.UserEmail = #UserEmail ) , 0 )
" ;
cmd.Parameters.AddWithValue( "#UserName" , userName ) ;
cmd.Parameters.AddWithValue( "#emailAddr" , emailAddr ) ;
int value = (int) cmd.ExecuteScalar() ;
status = (ValidationStatus) value ;
}
return status ;
}
Aside from anything else, hitting the DB twice for something like this is silly. And this more clearly expresses intent.
Then you can use it in your button click handler, something like this:
protected void Button_Click( object sender , EventArgs e )
{
string userName = Name_id.Text ;
string emailAddr = Email_id.Text ;
ValidationStatus status = ValidateUser( userName , emailAddr ) ;
switch ( status )
{
case ValidationStatus.Valid :
Label1.Text = "" ;
break ;
case ValidationStatus.EmailInUse :
Label1.Text = "Email address in use" ;
break ;
case ValidationStatus.UserNameInUse :
Label1.Text = "User name in use" ;
break ;
case ValidationStatus.EmailInUse|ValidationStatus.UserNameInUse:
Label1.Text = "Both user name and email address in use." ;
break ;
default :
throw new InvalidOperationException() ;
}
if ( status == ValidationStatus.Valid )
{
CreateNewUser() ;
}
}

Categories