I want to return userid against username and password
e.g.
1 abc a
11 def ab
when I enter abc in username textbox and a in password textbox then want to return 1 in label how to modify this code
protected void Button4_Click(object sender, EventArgs e)
{
string query = #"Data Source=HOME\SQL;Initial Catalog=The_Coffe;Integrated Security=True";
SqlConnection con = new SqlConnection(query);
con.Open();
string b = "Select C_ID from Customer_Register where Email='" + TextBox1.Text + "' AND password='" + TextBox2.Text + "'";
SqlCommand cam = new SqlCommand(b, con);
cam.Parameters.AddWithValue("#Email", TextBox1.Text);
cam.Parameters.AddWithValue("#password", TextBox2.Text);
cam.ExecuteNonQuery();
SqlDataReader dr = cam.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
TextBox1.Text = Convert.ToString(dr["Email"]);
TextBox2.Text = Convert.ToString(dr["password"]);
Session["UserName"] = TextBox1.Text;
Session["UserID"] = ID.Text;
//Response.Redirect("Fronpa.aspx");
}
}
else
{
Label4.Visible = true;
Label4.Text = "Incorrect Email or Password..";
}
con.Close();
}
For Returning UserId in the above code, you can use
Label1.Text = dr["id"].toString(); inside the while (dr.Read()) code block
Related
I'm getting the above error in this code`
protected void btnsubmit_Click(object sender, EventArgs e)
{
string veturaid = Request.QueryString["VetID"].ToString();
int vetuid = int.Parse(veturaid);
SqlConnection con = new SqlConnection("Data Source=DESKTOP-SUV91Q2\\AGONAJREDINI;Initial Catalog=VeturaOnline;Integrated Security=True; MultipleActiveResultSets=true ");
con.Open();
SqlCommand cmd = new SqlCommand("Select PerdID from Perdoruesit where Username='" + btnuser.Text + "'", con);
SqlDataReader reader = cmd.ExecuteReader();
string str = "";
while (reader.Read())
{
str = (reader["PerdID"].ToString());
id = int.Parse(str);
}
SqlCommand cmd2 = new SqlCommand("Select * from Veturat where VetID='" + vetuid + "'", con);
SqlDataReader reader1 = cmd2.ExecuteReader();
string modeli = "";
while (reader1.Read())
{
modeli = (reader["Modeli"].ToString());
}
reader1.Close();`
I'm getting the error at this line modeli = (reader["Modeli"].ToString());
Any idea why it is happening? Thank you in advance.
private void txtBoxSearch_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namecollection = new AutoCompleteStringCollection();
SqlConnection con = new SqlConnection("connectionn string");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
string searchFor = "%" + txtBoxSearch.Text + "%";
com.CommandText = "select cust_nm from Customer_Info where (cust_nm LIKE ' % " + searchFor + " %') ";
con.Open();
cmd.Parameters.AddWithValue("#name", searchFor);
SqlDataReader rea = cmd.ExecuteReader();
if (rea.HasRows == true)
{
while (rea.Read())
namecollection.Add(rea["name"].ToString());
}
rea.Close();
txtBoxSearch.AutoCompleteMode = AutoCompleteMode.Suggest;
txtBoxSearch.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtBoxSearch.AutoCompleteCustomSource = namecollection;
}
i want textbox which is act as a search option
A few problems here
You set the CommandText on com but execute cmd
You set % both on the variable and on the CommandText
You add a parameter but you don't have the parameter in the CommandText
public partial class adduser : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into login values username = #un,password = #ps, sequirity_que = #sq, ans = #answer,usertype = #ustp ");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
cmd.Connection = con;
if (con.State != System.Data.ConnectionState.Open)
con.Open();
string un = txtusername.Text.Trim();
string ps = txtpass.Text.Trim();
string sq = txtseq.Text.Trim();
string answer = txtans.Text.Trim();
string ustp = DropDownList1.SelectedValue;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("un", un);
cmd.Parameters.AddWithValue("ps", ps);
cmd.Parameters.AddWithValue("sq", sq);
cmd.Parameters.AddWithValue("answer", answer);
cmd.Parameters.AddWithValue("ustp", ustp);
//string qry = "insert into login values (username = '" + txtusername.Text + "',password='" + txtpass.Text + "',sequirity_que='" + txtseq.Text + "',ans='" + txtans.Text + "',usertype='" + DropDownList1.SelectedValue + "') ";
//SqlCommand md = new SqlCommand(qry,con);
int n= cmd.ExecuteNonQuery();
if(n>0)
{
Response.Write("User added");
}
else
{
Response.Write("fail");
}
}
}
This is the correct syntax of INSERT INTO:
SqlCommand cmd = new SqlCommand("insert into login (username, password, sequirity_que, ans, usertype) values (#un, #ps, #sq, #answer, #ustp)");
Some good examples
i have a problem when put in Response.Redirect
Example, the data only record for the first key in, for all the rest data no record in DB.
Secondly, the purpose i use Response.Redirect is to refresh the webpage, any idea to clear data after insert data into DB ?
kindly advise. thank you.
protected void Page_Load(object sender, EventArgs e)
{
string stat = Request.QueryString["stat"];
if (stat == "insert")
{
StatLabel.Text = "New Record have been Insert";
}
}
private void BindGrid(int rowcount)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("Test1", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Test2", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Test3", typeof(String)));
if (ViewState["CurrentData"] != null)
{
for (int i = 0; i < rowcount + 1; i++)
{
dt = (DataTable)ViewState["CurrentData"];
if (dt.Rows.Count > 0)
{
dr = dt.NewRow();
dr[0] = dt.Rows[0][0].ToString();
}
}
dr = dt.NewRow();
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
}
// If ViewState has a data then use the value as the DataSource
if (ViewState["CurrentData"] != null)
{
GridView1.DataSource = (DataTable)ViewState["CurrentData"];
GridView1.DataBind();
}
else
{
// Bind GridView with the initial data assocaited in the DataTable
GridView1.DataSource = dt;
GridView1.DataBind();
}
// Store the DataTable in ViewState to retain the values
ViewState["CurrentData"] = dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
// Check if the ViewState has a data assoiciated within it. If
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
int count = dt.Rows.Count;
BindGrid(count);
}
else
{
BindGrid(1);
}
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
TextBox3.Text = string.Empty;
TextBox1.Focus();
TextBox2.Focus();
TextBox3.Focus();
}
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridViewRow oItem in GridView1.Rows)
{
string str1 = oItem.Cells[0].Text;
string str2 = oItem.Cells[1].Text;
string str3 = oItem.Cells[2].Text;
insertData(str1, str2, str3);
}
}
public void insertData(string str1,string str2,string str3)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CIMProRPT01ConnectionString"].ConnectionString);
string sql = "insert into test (test1,test2,test3) values ('" + str1 + "','" + str2 + "','" + str3 + "')";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
con.Close();
Response.Redirect("WebForm1.aspx?stat=insert");
}
}
}
When you are saving into the database, you redirect right after each insert. Hence, none of the subsequent inserts are executed. I would move the redirect out of the loop. Maybe you can pass the number of records inserted in the query string as well.
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridViewRow oItem in GridView1.Rows)
{
string str1 = oItem.Cells[0].Text;
string str2 = oItem.Cells[1].Text;
string str3 = oItem.Cells[2].Text;
insertData(str1, str2, str3);
}
Response.Redirect("WebForm1.aspx?stat=insert");
}
public void insertData(string str1,string str2,string str3)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CIMProRPT01ConnectionString"].ConnectionString);
string sql = "insert into test (test1,test2,test3) values ('" + str1 + "','" + str2 + "','" + str3 + "')";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
con.Close();
}
I see your code i have find
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridViewRow oItem in GridView1.Rows)
{
string str1 = oItem.Cells[0].Text;
string str2 = oItem.Cells[1].Text;
string str3 = oItem.Cells[2].Text;
insertData(str1, str2, str3);
}
}
public void insertData(string str1,string str2,string str3)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CIMProRPT01ConnectionString"].ConnectionString);
string sql = "insert into test (test1,test2,test3) values ('" + str1 + "','" + str2 + "','" + str3 + "')";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
con.Close();
Response.Redirect("WebForm1.aspx?stat=insert");
}
in this on Button2_Click in for loop after first time it will redirect page so now Your method will be like this
Replace this Method
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridViewRow oItem in GridView1.Rows)
{
string str1 = oItem.Cells[0].Text;
string str2 = oItem.Cells[1].Text;
string str3 = oItem.Cells[2].Text;
insertData(str1, str2, str3);
}
Response.Redirect("WebForm1.aspx?stat=insert");
}
public void insertData(string str1,string str2,string str3)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CIMProRPT01ConnectionString"].ConnectionString);
string sql = "insert into test (test1,test2,test3) values ('" + str1 + "','" + str2 + "','" + str3 + "')";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
con.Close();
}
I have a label in asp.net page and change its text in certain situations. Here is the code:
<asp:Label ID="errorMessage" runat="server" Text="Label" Visible="False"></asp:Label>
errorMessage.Text = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
When i debugged, i saw that MyGlobals.student.registerCourse(c, ref addList, course).ToString() method returns my error message well. Then i set the label visible, but when page loads i cannot see the label. Also, while debugging i saw that "textsetbyaddparsedsubobject" property of the label is false. Can that be the problem? Why is not the label being showed in my page? Can anyone help?
Thanks.
Edit: Here is the full code:
protected void bSubmitChanges_Click1(object sender, EventArgs e)
{
Userfunctions function = new Userfunctions();
List<string> dropList = new List<string>();
List<string> addList = new List<string>();
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
SqlCommand cmd;
con.Open();
string ID = MyGlobals.currentID;
try
{
for (int i = 1; i <= 6; i++)
{
string course;
if ((course = boxCRN(i)) != "")
{
cmd = new SqlCommand("select count (*) from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
cmd = new SqlCommand("select * from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
cmd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
string query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
cmd = new SqlCommand("select * from PrereqTable where CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'", con);
da2 = new SqlDataAdapter(cmd);
dt2 = new DataTable();
da2.Fill(dt2);
List<string> pre = new List<string>();
foreach (DataRow dr5 in dt2.Rows)
{
pre.Add(Convert.ToString(dr5["pCourseCode"]) + Convert.ToString(dr5["pCourseNumber"]));
}
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
c.addPrereq(pre);
string message = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.Text = message;
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
Label1.Visible = true;
Label1.Text = "asdasdasd";
}
}
}
}
}
catch (Exception) { }
for (int i = 0; i < showCourses.Rows.Count; i++)
{
string a = ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue;
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
string courseCode = showCourses.Rows[i].Cells[1].Text, courseNumber = showCourses.Rows[i].Cells[2].Text;
SqlCommand com = new SqlCommand("select * from CourseTable where CourseCode=#courseCode and CourseNumber=#courseNumber", con);
com.Parameters.AddWithValue("courseCode", courseCode);
com.Parameters.AddWithValue("courseNumber", courseNumber);
try
{
SqlDataAdapter da2 = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(c, MyGlobals.student);
MyGlobals.student.dropCourse(reg);
dropList.Add(showCourses.Rows[i].Cells[1].Text + showCourses.Rows[i].Cells[2].Text);
}
catch (Exception) { }
}
}
foreach (string course in dropList)
{
for (int i = 0; i < MyGlobals.student.getRegistered().Count; i++ )
{
if (MyGlobals.student.getRegistered()[i].getCourse().getCode().ToString() + MyGlobals.student.getRegistered()[i].getCourse().getNumber().ToString() == course)
MyGlobals.student.dropCourse(MyGlobals.student.getRegistered()[i]);
}
cmd = new SqlCommand("delete from RegisterTable where StudentID='" + MyGlobals.currentID + "' and CourseCode='" + course.Substring(0, course.Length - 3) + "' and CourseNumber='" + course.Substring(course.Length - 3, 3) + "'", con);
cmd.ExecuteNonQuery();
}
try
{
foreach (string courses in addList)
{
string courseCode = "";
string courseNumber = "";
string term = MyGlobals.currentTerm + " " + MyGlobals.currentYear;
string q = ("select CourseCode from CourseTable where CRN=#courses");
string grade = "";
SqlCommand command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseCode = Convert.ToString(command.ExecuteScalar());
q = ("select CourseNumber from CourseTable where CRN=#courses");
command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseNumber = Convert.ToString(command.ExecuteScalar());
cmd = new SqlCommand("insert into RegisterTable (CourseCode,CourseNumber,Term,StudentID,Grade) values(#courseCode,#courseNumber,#term, #ID,'U')", con);
cmd.Parameters.AddWithValue("#courseCode", courseCode);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#term", term);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
}
}
catch (Exception) { }
con.Close();
Response.Redirect("AddDropClasses.aspx");
}
}
And the registerCourse function:
public string registerCourse(Course course, ref List <string> addList, string crn) {
bool registered = true;
string message ="";
foreach (string s in course.getTime())
{
Userfunctions f = new Userfunctions();
foreach (Register r in this.register) {
if (r.getCourse().getTerm() == MyGlobals.currentTerm.ToString() + " " + MyGlobals.currentYear.ToString() && !f.TimeCheck(s, r.getCourse().getTime()))
{
registered = false;
message = "Time conflict";
}
}
}
if (registered) {
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string id = MyGlobals.currentID;
SqlCommand cmd = new SqlCommand("SELECT count (*) from RegisterTable where CourseCode ='" + course.getCode() +"' and CourseNumber='" + course.getNumber() + "' and Term='" + course.getTerm()+"'" , con);
cmd.Parameters.AddWithValue("#id", id);
int active = Convert.ToInt32(cmd.ExecuteScalar());
if (active >= Convert.ToInt32(course.getCapacity())){
registered = false;
message = "Not enough capacity";
}
if (registered) {
foreach (string s in course.getPrerequisites()) {
if (!hasPassedCourse(s)) {
registered = false;
message = "Prerequisite error";
}
}
}
}
if (registered)
{
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
addList.Add(crn);
}
return message;
}
Remove below line
Response.Redirect("AddDropClasses.aspx");
it will load your page again as new page
When you have Visible="false" set on the control then the control properties may not been instatiated fully.
I would try hiding the control using, errorMessage.Visible=false in the code-behind in your Page_Load instead.