ODBC Select all command - asp.net

The following code works fine when the limit is 0,1 when I limit them to 0,30 I cannot retrieve records I am sure that my database has enough number of records.
But I doubt the syntax after dr[3].ToString(); How to retrieve all of them.
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=malla_softmail2;" + "UID=xxx;" + "PASSWORD=xxx;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select * from awm_test where user=? limit= 0, 1", MyConnection);
cmd.Parameters.Add("#email", OdbcType.VarChar, 255).Value = "hello";
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
// throw new Exception();
}
if (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
//string d = dr[3].ToString();
//string f = dr[4].ToString();
//string g = dr[5].ToString();
Response.Write(a);
Response.Write(b);
Response.Write(c);
//Response.Write(d);
//Response.Write(f);
//Response.Write(g);

You're only processing the first record returned by your query. Try:
while (dr.Read()) {
string firstField = dr[0].ToString();
string secondField = dr[1].ToString();
string thirdField = dr[2].ToString();
// ...
}

You just need to read the rows in a loop with while(dr.Read()) {...do stuff for each row...} - each dr.Read() moves to the next row.

Related

How to Implement Multiple search in Asp.Net

I want to Implement multiple search query system in Asp.Net where search input are in form of TEXTBOX and DROPDOWN LIST. Query should work in combination or indivisually to filter the data from SQL Server
and show in Gridview.
This Code Snippet is for filtering two Dropdown values:
if (Agree_type_srch.SelectedValue != null || Status_srch.SelectedValue != null)
{
if (Agree_type_srch.SelectedValue != null)
{
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand com = new SqlCommand("Select *from EntryDatabase where Agree_type ='" + Agree_type_srch.SelectedItem.Text + "'", conn);
SqlDataAdapter sqldatad = new SqlDataAdapter();
DataSet ds = new DataSet();
com.Connection = conn;
sqldatad.SelectCommand = com;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else if (Status_srch.SelectedValue != null)
{
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand com = new SqlCommand("Select *from EntryDatabase where Curnt_St ='" + Status_srch.SelectedItem.Text + "'", conn);
SqlDataAdapter sqldatad = new SqlDataAdapter();
DataSet ds = new DataSet();
com.Connection = conn;
sqldatad.SelectCommand = com;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
if (Agree_type_srch.SelectedItem.Text != null && Status_srch.SelectedItem.Text != null)
{
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand com = new SqlCommand("Select * from EntryDatabase where Agree_type ='" + Agree_type_srch.SelectedItem.Text + "'and Curnt_St ='" + Status_srch.SelectedItem.Text + "'", conn);
SqlDataAdapter sqldatad = new SqlDataAdapter();
DataSet ds = new DataSet();
com.Connection = conn;
sqldatad.SelectCommand = com;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
...
First, using string concatenation to provide parameters can result in SQL injection, use SqlParameter to pass parameters would be better.
Second, consider to warp all SqlClient classes by using scope so you don't have to worry close/dispose.
Lastly, For your question, you can use WHERE 1=1 then append any conditions you need.
Take your code as instance.
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string query = "SELECT * FROM EntryDatabase WHERE 1=1";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
if (Agree_type_srch.SelectedValue != null)
{
query += " AND Agree_type = #agree_type";
cmd.Parameters.AddWithValue("agree_type", Agree_type_srch.SelectedValue);
}
if (Status_srch.SelectedValue != null)
{
query += " AND Curnt_St = #curnt_st";
cmd.Parameters.AddWithValue("curnt_st", Status_srch.SelectedValue);
}
cmd.CommandText = query;
using (SqlDataAdapter sqldatad = new SqlDataAdapter())
{
DataSet ds = new DataSet();
sqldatad.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}

i want code for Autocomplete Textbox Using Database Return Value in c#.net

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

Label does not show up in asp.net

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.

There is no row at position 0 error at asp.net

I was writing a web based program and this is my authentication page. It was working fine but suddenly it started to give that error.
Here is my code:
else if (LoginAs.SelectedValue == "Student")
{
string tableName = "StudentTable";
String name = "", surname = "", email = "";
string query = "Select level from " + tableName + " where ID='" + idBox.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
string level = Convert.ToString(cmd.ExecuteScalar());
CreateUser(con, tableName, ref name, ref surname, ref email);
query = "Select program from " + tableName + " where ID='" + idBox.Text + "'";
cmd = new SqlCommand(query, con);
string program = Convert.ToString(cmd.ExecuteScalar());
MyGlobals.student = new Student(Convert.ToInt32(idBox.Text), "Active", email, name, surname, password, level, program);
MyGlobals.currentID = idBox.Text;
query = "Select * from RegisterTable where StudentID='" + idBox.Text + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
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]; //ERROR COMES AT HERE
Course course = new Course(dr2["InstructorName"].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(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
}
int num = (int)Application["OnlineUsers"];
Response.Redirect("Student.aspx");
}
Can anyone help me with this? Thanks in advance.
You don't specify where the exception is thrown but a very common reason for this (my opinion) is that your query doesn't return any results (or rows).

Strange! MySQL update not working without error

The below is my code to create account in my project. The code is working perfect till Response.Write(iduser) but the UPDATE command is not working. No error found using exception but MySQL's record is not updated.
try
{
string pet1 = "admin#testlite.php";
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=newtest;" + "UID=root;" + "PASSWORD=**********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcCommand cmd = new OdbcCommand("Select id_user from awm_accounts where email=?", MyConnection);
cmd.Parameters.Add("#val1", OdbcType.VarChar, 255).Value = pet1;
MyConnection.Open();
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
if (dr.Read())
{
int iduser = Convert.ToInt32(dr[0].ToString());
Account acct = new Account();
acct.Email = username.Text + domain.Text;
acct.MailIncomingLogin = username.Text + domain.Text;
acct.MailIncomingHost = "imap." + DropDownList1.SelectedValue;
acct.MailIncomingPassword = password.Text;
acct.MailIncomingPort = 993;
acct.MailOutgoingHost = "smtp." + DropDownList1.SelectedValue;
acct.MailOutgoingPort = 465;
acct.MailIncomingProtocol = IncomingMailProtocol.Imap4;
acct.MailOutgoingAuthentication = true;
acct.DefaultAccount = false;
acct.IDUser = 1;
integr.CreateUserFromAccount(acct);
Response.Write(iduser);
if (!IsPostBack)
{
cmd = new OdbcCommand("UPDATE awm_accounts SET id_user=? WHERE email=? ", MyConnection);
cmd.Parameters.Add("#tb_nickname", OdbcType.Int, 11).Value = iduser;
cmd.Parameters.Add("#tb_fullname", OdbcType.VarChar, 255).Value = username.Text + domain.Text;
cmd.ExecuteNonQuery();
}
}
MyConnection.Close();
}
catch (Exception exp)
{
Response.Write(exp);
}
I'm not sure about the Response.Write part but I am sure that you create a SQLCommand but never actually execute it.
Did you forget to put a cmd.executeNonScalar() in there?

Resources