string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string selstatus = "select status from Status where c_email=#c_email";
SqlCommand cmd = new SqlCommand(selstatus, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string value = Session["user"].ToString();
DataRow[] row =dt.Select(value);
sda.Fill(ds);
sda.Fill(dt);
if(row!=null){
Label13.Text = ds.Tables[0].Rows[0]["status"].ToString();
}else{
Label13.Text = "No response from mechanic";
}
cmd.ExecuteNonQuery();
con.Close();
I have been finding way to check a specific email id exist in the table. But I can't query what is the correct format to do so. I just need that if a specific email id is available then a message should be displayed.
There is no need for the DataAdapter, DataTable etc. Simply count the number of records
select count(1) from Status where c_email=#c_email
and then on the SqlCommand just use ExecuteScalar:
string selstatus = "select count(1) from Status where c_email=#c_email";
SqlCommand cmd = new SqlCommand(selstatus, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
var count = cmd.ExecuteScalar();
// if count=0 the email doesnt exist
Related
I connot able to filter the current user record. I want to display the data of current user only. But I did not understand how to handl query.
here is the ss of login.
As I selected Student, and username =50 and pass=50 ,
and when i press he show button this will display all the record but i want only current user data :
here is the code :
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
OleDbDataAdapter sda = new OleDbDataAdapter(#"SELECT student.s_id, student.f_name, student.l_name, student.email, student.address, course.c_id, course.cname, resultdate.resultgrade FROM ((student INNER JOIN resultdate ON student.s_id = resultdate.s_id) INNER JOIN course ON resultdate.c_id = course.c_id)", conn);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
//dataGridView1.Text = dt.Rows.Count.ToString();
conn.Close();
Paste this code in your combobox.
con.Open();
string query = “ select* from student where student.s_id = ’”
+combobox1.SelectedItem.ToString() + “’”;
OleDbDataAdapter sda = new OleDbDataAdapter(query, con);
OleDbCommandBuiler builer = new OleDbCommandBuiler(da);
var ds = new DataSet();
sda.Fill(ds);
datagridview1.Datasource = ds.Table[0];
conn.Close();
I am trying to update my data in a SQL Server database through C#. I am getting updated. But the problem is the data is updated twice.
For example I have 10 (int) in my balance and if I add another 10, it turns to 30.
Any help would be appreciated.
Here is my code:
protected void LoginClick(object sender, EventArgs e)
{
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
}
I would like to rectify few mistakes in your code,
DataTable is not needed to execute the update query, ExecuteNonQuery will do the job
The adapter.Fill and ExecuteNonQuery do the same job here and that's why your updates happening twice
Make use of parameterization while dealing with user inputs to avoid exceptions
For parsing integers use int.TryParse instead for Convert.ToInt32
I think the following code would help you to do the same function in a smarter way:
int currentBalance = 0;
if(int.TryParse(txtAdd.Text, out currentBalance))
{
string querSql = "Update [Order] set Balance = Balance + #balance," +
" Card = #card where email = #email"
using (SqlConnection dbConn = new SqlConnection("connectionString here"))
{
dbConn.Open();
using (SqlCommand sqlCommand = new SqlCommand(querySql, dbConn))
{
sqlCommand.Parameters.Add("#balance", SqlDbType.int).value = currentBalance;
sqlCommand.Parameters.Add("#card", SqlDbType.VarChar).value = card.Text;
sqlCommand.Parameters.Add("#email", SqlDbType.VarChar).value = email;
sqlCommand.ExecuteNonQuery();
}
}
}
Please note: YOu are parsing the balance as an integer value, so I assume the column Balance is an integer field in the database, if not make use of corresponding datatype for the parameter #balance also update the parsing technique
As per the documentation:
SqlDataAdapter(SqlCommand)
Initializes a new instance of the SqlDataAdapter class with the specified SqlCommand as the SelectCommand property.
What is going wrong in your code?
Actually you are passing SqlDataAdapter your update query as the Select command. So now when you will use this instance of SqlDataAdapter to Fill your datatable then actually you are executing your Update command. Look at the following code along with comments to see what is going wrong:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);//The Select command for SqlDataAdapter
//is actually now the update command specified by cmd instnace of SqlCommand
DataTable dt = new DataTable();
sda.Fill(dt);//here SqlDataAdapter will execute it's Select command which is actually set
//to an update statement so your record will be updated
int i = cmd.ExecuteNonQuery();//and here again the update command is being executed now
//directly using the SqlCommand cmd instance and thus your record gets updated twice
con.Close();
Fixed Code:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
//Create a new SqlComamnd
SqlCommand selectCommand = new SqlCommand("Select * from [Order]");
//Put the newly created instance as SelectCommand for your SqlDataAdapter
SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
Hope this help and do have a look at the documentation for better understanding of the SqlDataAdapter and DataTable. Thanks.
I am new to ASP.NET C#, I am working to develop web forms to send and receive messages (SQL Server as database) like emails. I want to store the result of SQL query in Session Variable and use it later in another page.
Kindly help me how can I do that, please correct if any things goes wrong.
Here is my code:
SqlConnection con = new SqlConnection("Data Source=AZEEM\\SQLEXPRESS; Initial Catalog=kics;User ID=sa;Password=123");
con.Open();
String query = "select username as sender,subject,message from emailtable where receiver='" + Session["username"] + "'";
enter code here
//this is the query for which I want to store the result in variable myvar, how can I store the result of following query in variable myvar and use it later, when I execute it, string is shown instead of result of string.
String myvar = "select receiver from emailtable where username='" + Session["username"] + "'";
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(query, con);
SqlCommand cmd2 = new SqlCommand(myvar, con);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
reader = cmd2.ExecuteReader();
GridView1.DataSource = dt;
GridView1.DataBind();
DataSet ds = new DataSet();
ds = myvar;
Try below,
SqlConnection con = new SqlConnection("Data Source=AZEEM\\SQLEXPRESS; Initial Catalog=kics;User ID=sa;Password=123");
con.Open();
String query = "select username as sender,subject,message from emailtable where receiver='" + Session["username"] + "'";
enter code here
//this is the query for which I want to store the result in variable myvar, how can I store the result of following query in variable myvar and use it later, when I execute it, string is shown instead of result of string.
String myvar = "select receiver from emailtable where username='" + Session["username"] + "'";
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(query, con);
SqlCommand cmd2 = new SqlCommand(myvar, con);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
reader = cmd2.ExecuteReader();
GridView1.DataSource = dt;
GridView1.DataBind();
session["dt"] = dt;
When you retrieve,
if (session["dt"] != null) {
DataTable dt = (DataTable)session["dt"];
}
You Need to Pass that Query to this Method which will return you the result Set and then try to assign it to the Session
String myvar = "select receiver from emailtable where username='" + Session["username"] + "'";
Session["myvar"] = GetData(myvar);
Method for GetData as Follows
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = "Data Source=AZEEM\\SQLEXPRESS; Initial Catalog=kics;User ID=sa;Password=123";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
I have the following code:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=#username and Password=#password and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Here I want to fetch some values from the table according to a condition,
but when I run this code it shows the following error:
Even though I passed the correct parameters value in #username and #password. How can I resolve this error? Please help.
Try This:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=? and Password=? and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Try This
string query = "Select [UserId],[Firstname],[UserType] from [TBL_USER_LOGIN] where [Username]=? and [Password]=? and [Status]=1";
how am i going prevent "lesson Title" from duplicating in database when user input duplicate data?
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
That kind of uniqueness should be enforced by the database. Add a unique constraint to your table:
CREATE UNIQUE INDEX UK_Lesson_Title ON Lesson (Title)
You can create a function to check the duplicate LessonTitle.
Explanantion: here i have created a function called checkDuplicateTitle().
this function takes AllRows of a LessonTable as DataRowCollection and LessonTitle to be verified as inputs.
it will check the LessonTitle of each and every row.
if given LessonTitle is matched with existing Titles from Table then this function returns true else returns false.
if the returned value is true we will ignore the updating the table with new row as LessonTitle is already Existing otherwise we will add it.
Code as below:
void UpdateLessonTable()
{
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
if (!checkDuplicateTitle(ds.Tables["Lesson"].Rows, textBox1.Text.ToString()))
{
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
}
else
{
//you can display some warning here
// MessageBox.Show("Duplicate Lesson Title!");
}
}
//function for checking duplicate LessonTitle
bool checkDuplicateTitle(DataRowCollection rowTitle,String newTitle)
{
foreach (DataRow row in rowTitle)
{
if(row["LessonTitle"].Equals(newTitle))
return true;
}
return false;
}