Double data in database - c#

[WebMethod]
public string Login(string Username, string Password)
{
String result;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Nicole Wong\Desktop\Inari Tracking System\Inari Tracking System\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Username, Password from UserData where Username = #Username AND Password = #Password", con);
cmd.Parameters.AddWithValue("#UserName", Username);
cmd.Parameters.AddWithValue("#Password", Password);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count> 0)
{
DateTime dt = DateTime.Now;
SqlCommand cmd1 = new SqlCommand("INSERT INTO ActivityLog (CreateOn, CreateBy) VALUES (#CreateOn,#CreateBy)", con);
cmd1.Parameters.AddWithValue("#CreateOn", dt);
cmd1.Parameters.AddWithValue("#CreateBy", Username);
cmd1.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
// Create an instance of DataSet.
DataSet ds1 = new DataSet();
da1.Fill(ds);
con.Close();
result = "Successful";
return result;
}
else
{
result = "Fail";
return result;
}
This is my simple web method to store user login time into database.
The problem is the data saved twice into the database. For example, I login into the system, then it returns successful, but I checked the database there is two same records saved with the same data. I run with breakpoint but the there is no any duplication, the code run nicely line by line.
Any idea? Thank you in advance

public string Login(string Username, string Password)
{
String result;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Nicole Wong\Desktop\Inari Tracking System\Inari Tracking System\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Username, Password from UserData where Username = #Username AND Password = #Password", con);
cmd.Parameters.AddWithValue("#UserName", Username);
cmd.Parameters.AddWithValue("#Password", Password);
//This us pretty much useless on a select, SELECT is a query, not a NonQuery
//cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count> 0)
{
DateTime dt = DateTime.Now;
SqlCommand cmd1 = new SqlCommand("INSERT INTO ActivityLog (CreateOn, CreateBy) VALUES (#CreateOn,#CreateBy)", con);
cmd1.Parameters.AddWithValue("#CreateOn", dt);
cmd1.Parameters.AddWithValue("#CreateBy", Username);
cmd1.ExecuteNonQuery();
//Don't use the DataAdapter and try to fill a dataset from an insert, all this insert will return is ##ROWCOUNT
//SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
// Create an instance of DataSet.
//DataSet ds1 = new DataSet();
//da1.Fill(ds);
con.Close();
result = "Successful";
return result;
}
else
{
result = "Fail";
return result;
}
You executed both your select and your insert twice, with the select it didn't matter so much, but with the insert it does. Remove the .ExecuteNonQuery() from the select and remove the SqlDataAdapter from the insert.

Related

How to Reuse Logic Without Copy/Pasting Blocks of Code - C#

My project reuses the code below multiple times with only a few variables changing. I've noted the values that change with e.g. ***value***.
if (comboBox1.Text == ***"Most recent first"***)
{
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\CW\CW\bin\Debug\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #userID Order By ***Date Desc***";
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter.SelectCommand.Parameters.AddWithValue("#userID", currentUserID);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
recordsDataGridView.DataSource = ds;
recordsDataGridView.DataMember = "Records";
}
How can I use this same logic, with different values, without copying and pasting the if statement multiple times?
Sounds to me you want something like:
private void foo(string matchText, string sortBy) {
if (comboBox1.Text == matchText)
{
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\CW\CW\bin\Debug\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #userID Order By " + sortBy;
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter.SelectCommand.Parameters.AddWithValue("#userID", currentUserID);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
recordsDataGridView.DataSource = ds;
recordsDataGridView.DataMember = "Records";
}
}//foo
//Call the method
foo("Most recent first", "Date DESC");
foo("Most recent last", "Date");
foo("By Username", "User");

Input string was not in a correct format

public int getcid(string UserName)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
int js;
string query = "select Username from register_tab where Email='" + UserName + "' ";
sqlda = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
sqlda.Fill(ds);
js = Convert.ToInt32(ds.Tables[0].Rows[0]["Username"].ToString());
return (js);
Change your method to this and check it out:
SqlConnection con = new SqlConnection(strConnString);
con.Open();
string js;
string query= "select Username from register_tab where Email= #username";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#username",SqlDbType.VarChar, 50).Value =
UserName;
using(SqlDataReader reader= cmd.ExecuteReader())
{
while (reader.Read())
{
js= reader["Username"].ToString();
}
}
con.Close();
return js;
Also why do you set your UserName to Email Column in your query?
And why do you use DataSet if you only want to return int?
UPDATE: no need to convert to int.

How to Convert DataSet to User Object in C#?

// GetUserByUsername
public DataSet GetUserByUsername(string Username)
{
User _user = null;
using (SqlCommand cmd = new SqlCommand(DBHelper.UserMethod("GetUsername"),con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", Username);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.Fill(ds);
}
return ds;
}
In my above method return type is DataSet, here my dout is if I change the DataType to User then how to Convert that DataSet ds to User let me show you.
For example:
// GetUserByUsername
public User GetUserByUsername(string Username)
{
User _user = null;
using (SqlCommand cmd = new SqlCommand(DBHelper.UserMethod("GetUsername"),con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", Username);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.Fill(ds);
}
return (User)ds;
}
Can I use in this way or is their any other way can I use instead of DataSet, DataTable?
If you don't want to build the User obj by parsing the results yourself go for the automapper lib OR there is a such a thing as strongly type datasets (IE define a set AS User). Its been a long time since I've done that but this will get you started
https://msdn.microsoft.com/en-us/library/esbykkzb(v=vs.110).aspx

passing a parameter to GridView when calling data from database

so my GridView Returns all the data in my Table but i want to return data that are related to the UserName attribute in the table,mind you that i have Multiple UserName's in the table.
i tried giving my function a string username and in my page_load:
string SessionName;
protected void Page_Load(object sender, EventArgs e)
{
SessionName = Session["Username"].ToString();
DataSet ds = InsertClass.GetCart(SessionName);
}
in my class:
public static DataSet GetCart(string UserName)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [ShoppingCart] WHERE UserName = #UserName ", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#UserName", UserName));
DataSet ds = new DataSet();
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
adapter1.Fill(ds);
conn.Close();
return ds;
}
Edit:my mistake guys i didnt add the parameter to my function because i was trying alot of things before i asked the question and forgot to put it back.
You are not passing username as string parameter here in your code public static DataSet GetCart()
Here is correct one:
public static DataSet GetCart(string userName)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [ShoppingCart] WHERE UserName = #UserName ", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", userName);
DataSet ds = new DataSet();
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
adapter1.Fill(ds);
conn.Close();
return ds;
}
So in your page_load you are calling your GetCart function with parameter SessionName, but i cannot see your GetCart function is taking any parameter:
DataSet ds = InsertClass.GetCart(SessionName);
public static DataSet GetCart()
{.....}
And what is the reference of UserName, when you add the parameter to sql query:
cmd.Parameters.Add(new SqlParameter("#UserName", UserName));
Did you debug and see that you are passing the right parameter ?

How to get data from SQL database to store in combo box - C#

How can i get the value of company_name from Comp table and store it on a comboBox?
here is my initial code on getting the values from Database and store it on a combobox:
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
it point out to da.fill(ds) and says "Could not locate entry in sysdatabases for database 'select company_name from JO'. No entry found with that name. Make sure that the name is entered correctly."
hope for your reply thanks!
Use datareader it is much simpler \
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn);
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
combobox1.Items.Add(DR[0]);
}
If you set up your connection string to be something of this sort:
string SqlConnectionString = "Data Source=[SERVER];Initial Catalog=[DATABASE];"
Then using that set up, you can set your string 'Sql' as:
string Sql = "select company_name from dbo.Comp";
This could be a possible set up you could use to read out the values.
using (SqlConnection saConn = new SqlConnection(this.ConnectionString))
{
saConn.Open();
string query = "select DBName from dbo.Company";
SqlCommand cmd = new SqlCommand(query, saConn);
using (SqlDataReader saReader = cmd.ExecuteReader())
{
while (saReader.Read())
{
string name = saReader.GetString(0);
combobox1.Add(name);
}
}
saConn.Close();
}
I would like to introduce you a very simple way to SQL data into a combobox as:
first you have a create a SQL table,
in C# platform drop a combobox and go to its property,
in the property menu click on "DataSource"
specify the database and table to load into combobox,
Note, the combobox name and table's row should be the same.
{
SqlConnection con =new SqlConnection("Data Source=Server_Name;Initial Catalog=Database_Name;integrated security=true");
SqlCommand cmd;
SqlDataReader dr;
private void CashMemoForm_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("Select Column_Name From Table_Name", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr[0]).ToString();
}
}
}
Have you ever tried Entity Framework for database access and dto creation?
Change your line to cmd.CommandType = CommandType.Text; instead of cmd.CommandType = CommandType.StoredProcedure;
Try this
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}
There is no use of for loop. you just need to check that whether the dataset contains rows or not.
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("Select", "0"));
}
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
public System.Data.DataTable EmployeeViewAll()
{
DataTable dtbl = new DataTable();
try
{
// Here it shuld be your database Connection String
string connectionString = "Server = .; database = HKS; Integrated Security = true";
using (SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString))
{
SqlDataAdapter SqlDa = new SqlDataAdapter("employeeViewAll", sqlCon);
SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlDa.Fill(dtbl);
}
return dtbl;
}
catch (Exception)
{
throw;
}
}
public void ComboFill()
{
DataTable dt = new DataTable();
eSP SP = new eSP();
d = SP.EmployeeViewAll();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "department";
comboBox1.ValueMember = "empName";
}

Categories

Resources