Can't Get value from database in ASP.net - asp.net

Hi can you help me with this??
I have this code and i want to display the result of my query into my 3rd Textbox but it not displaying.
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = '" + TextBox2.Text + "'";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
TextBox3.Text=rdr["UserID"].ToString() ;
}
}
}
}
}
But then i just use this query without the where condition i can see the output;
string query = "SELECT UserID FROM [IBSI].[sec].[Users]";
Thanks in advance

I'd recommend using parameterized queries for this task. Also, generating sql code from user input (like text boxes/memos) is prone to sql injections (user may enter any sql code into the textbox that may damage database data), so it'd be great to validate input data.
Sample parameter usage is like this:
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = #1";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlParameter p1 = new SqlParameter("#1", TextBox2.Text);
cmd.Parameters.Add(p1);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
TextBox3.Text=rdr["UserID"].ToString() ;
}
}
}
}
}

Step through the debugger and verify that your query is returning results.

ey Bert change in your code as follows:
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName= '"+TextBox2.Text+ "'";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
int UserId;
UserId=Convert.ToInt32(cmd.ExecuteScalar());
TextBox3.Text=UserId.ToString() ;
}
}
}

Related

Connecting MS_SQL DB IN asp.net

I was trying to connectMs_sql database in asp.net but server error of network path not found... it is not able to establish connection to sql server...comes while in gridview it is taking it as sqldatasource perfectly
This for customized class to call the ADO.Net. Please use this and let me know if you have any doubts.
public class DbConnectionHelper {
public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
string connString = # "your connection string here";
//Object Declaration
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
try {
//Get Connection string and Make Connection
con.ConnectionString = connString; //Get the Connection String
if (con.State == ConnectionState.Closed) {
con.Open(); //Connection Open
}
if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Query;
if (p.Length > 0) // If Any parameter is there means, we need to add.
{
for (int i = 0; i < p.Length; i++) {
cmd.Parameters.Add(p[i]);
}
}
}
if (cmdText == CommandType.Text) // Type : Text
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
if (cmdText == CommandType.TableDirect) //Type: Table Direct
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
cmd.Connection = con; //Get Connection in Command
sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
con.Close(); //Connection Close
} catch (Exception ex) {
throw ex; //Here you need to handle Exception
}
return ds;
}
}

How do i fill up textbox from database in asp.net visual studio without id?

I am trying to get details of an account in a row using the Username instead of id. I have limited knowledge on this matter so im only stuck with the code that i learned in class.
I have tried changing variables, but probably wont help and the code i have provided below, would not retrieve any data from the database...
(Username are retrieved from previous page and yes it did show up in this page)
This is the code used on previous page: (code is placed on a button)
string username = Session["Username"].ToString();
Response.Redirect("EditAccountDetail.aspx?Username="+ username);
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
This is the code im working on right now:
String Uname = Request.QueryString["Username"];
string constr = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname+"'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string Full_name = row["Full_name"].ToString();
string Username = row["Username"].ToString();
string Password = row["Password"].ToString();
string Email = row["Email"].ToString();
string DOB = row["DOB"].ToString();
string Gender = row["Gender"].ToString();
this.HiddenField1.Value = id;
this.TextBox_Name.Text = Full_name;
this.TextBox_Username.Text = Username;
this.TextBox_Password.Text = Password;
this.TextBox_Email.Text = Email;
this.TextBox_DOB.Text = DOB;
this.RadioButtonList_Gender.Text = Gender;
}
}
}
}
}
This is the code in the button:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
try
{
string query = "UPDATE Guest SET Full_name=#Full_name, Username=#Username, Password=#Password, Email=#Email, DOB=#DOB, Gender=#Gender WHERE Id=#id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", HiddenField1.Value);
cmd.Parameters.AddWithValue("#Full_name", TextBox_Name.Text);
cmd.Parameters.AddWithValue("#Username", TextBox_Username.Text);
cmd.Parameters.AddWithValue("#Password", TextBox_Password.Text);
cmd.Parameters.AddWithValue("#Email", TextBox_Email.Text);
cmd.Parameters.AddWithValue("#DOB", TextBox_DOB.Text);
cmd.Parameters.AddWithValue("#Gender", RadioButtonList_Gender.Text);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("GuestMenu.aspx");
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
If you are redirecting to the "GuestMenu" page, then you have to add username in the query string so that you can retrieve this on the page.
Response.Redirect("GuestMenu.aspx?Username="+TextBox_Username.Text);
By seeing your current code, you should be getting some error. Please post the error details if any.
You can try changing the query as below and check for database result
new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname + "'")

Using sqldatareader in another sqldatareader

I'm checking table to see if ID exists in table A if that ID exists insert it in table B but I also would like to check in table B if that ID number was not already inserted. But my issue is that I'm not able to combine all of that together. I'm not sure how to put a sqldatareader into another.
SqlCommand cmd1 = new SqlCommand("CreateID", con);
SqlCommand cmd = new SqlCommand("selectID", conn);
SqlCommand com = new SqlCommand("SelectIDfromtableB", con);
public SqlDataReader dr;
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
sessionCount++;
Session["Count"] = sessionCount;
cmd1.Parameters.Add("#crate_box_no", SqlDbType.NVarChar).Value = id;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
}
reader.Close();
cmd1.ExecuteNonQuery();
}
else
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert( Id number does not exist'); window.location.href = 'Return.aspx';", true);
}
}
if (dr.Read())
{
lblError.Text = "Data was inserted before";
}
dr.Close();
You can minimize the code, use one connection for all the readers and one command, but you have to set the CommandText each time and clear the parameters if there were any. Use the using keyword to make sure your resources are disposed.
If there is anything you need to check in your first command, you can set a flag
using (var conn = GetTheConnection())
{
conn.Open();
//flag to check if id exists
var idExists = false;
var cmd= new SqlCommand("CreateID", conn );
cmd.Parameters.Add("#crate_box_no", SqlDbType.NVarChar).Value = id;
using (var myReader = cmd.ExecuteReader())
{
if(myReader.Read())
{
idExists = true;
}
}
//clear parameters
if (idExists)
{
cmd.Parameters.Clear();
cmd.commandText = "You 2nd SQL Script here"
using (var myReader = cmd.ExecuteReader())
{
}
}
}
Cant you just do 2 queries? First one counting rows of id occurences, if greater 0 then count occurences in table b, if 0 continue?
Edit Example pseudo code:
command1 = "select id from tableA where id = toLookForId";
Define GridView1 and Gridview2;
Gridview1.datasource = sqldatareader.executenonquery(command1);
Gridview1.databind();
if gridview1.rows.count > 0 then
command2 = "select id from tableB where id = toLookForId";
Gridview2.datasource = sqlreader.executenonquery(command2);
gridview2.databind();
if gridview2.rows.count = 0 then
//your code goes here
else
//id exists so quit
return;
end if
end if
Regards,
Maheshvara

why does SELECT SCOPE_IDENTITY() returning null?

I am trying to get ID generated by last Insert function. I understand very little about Scope and Session. But by reading blogs and other sources, I understood that, I should use Scope_Identity() function. But I am getting null value. Here is my code :
public int InsertUser(string username, string gender, string agegroup, string email, int partnerID, string userType)
{
try
{
string query = "Insert into tblUser (username,gender,agegroup,email,partnerid,usertype) values (#username,#gender,#age,#email,#partnerid,#usertype)";
SqlCommand cmd = new SqlCommand(query, _dbConnection.getCon());
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#age", agegroup);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#partnerid", partnerID);
cmd.Parameters.AddWithValue("#usertype", userType);
if (cmd.ExecuteNonQuery() > 0)
{
query = "select scope_identity() as id";
cmd = new SqlCommand(query, _dbConnection.getCon());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);// dt is showing no value in it
return 1;// This should return ID
}
else {
return -1;
}
}
catch (Exception e) {
throw e;
}
}
How can I achieve this?
Try appending SELECT scope_identity() to your first query and then capture the identity using var identity = cmd.ExecuteScalar() instead of running cmd.ExecuteNonQuery().

How to read uncommited transaction within sqltransaction?

i got a problem when using SQLTransaction in my .net framework 2.0 c# code
this is my code:
public bool register()
{
SqlConnection conn = DB.getInstance().getConnection();
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = sqlTransaction;
try
{
cmd = insertMembers(cmd);
cmd.ExecuteNonQuery();
SqlDataReader read = null;
cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
read = cmd.ExecuteReader();
while (read.HasRows)
{
id0 = (int)read["id0"];
}
cmd = insertMembersBalance(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersEPoint(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersVerify(cmd);
cmd.ExecuteNonQuery();
reset();
sqlTransaction.Commit();
}
catch(Exception e)
{
sqlTransaction.Rollback();
Console.WriteLine(e.ToString());
return false;
}
finally
{
conn.Close();
}
return true;
}
I can't get the id from members table to use for insert another records into another table.
is there any other solution?
You must call dr.Read() first than SqlDataReader dr = cmd.........
if (read.HasRows) // needs to be if not while or it will just loop
{
read.Read();
id0 = (int)read["id0"];
}
read.Close(); // need to close the reader before you can use the cmd
if you want to loop through all rows then
while (read.Read())
{
id0 = (int)read["id0"];
}

Resources