hii,can anyone tell what is wrong with this code.??
SqlCommand command = new SqlCommand("SELECT DISTINCT TOR_Name FROM TESTCASESTATUS_TABLE WHERE TestCaseID = '"
+ DropDownList1.SelectedItem.Text + "'", connection);
SqlDataReader x = command.ExecuteReader();
if (null != x && x.HasRows)
TestCaseName.Text = Convert.ToString(x["TOR_Name"]);
else
TestCaseName.Text = "something";
x.Close();
when i debug the code it is even getting into the if conditioon but then it is throwing an error, invalid attempt to read data when no data is present. !!!
please help/.
You need to issue a DataReader.Read command for the data to be actually loaded into fields, like
SqlDataReader x = command.ExecuteReader();
if (null != x && x.HasRows)
{
x.Read();
TestCaseName.Text = Convert.ToString(x["TOR_Name"]);
}
....
Call x.Read() to fetch the first result.
Related
I have the following code that runs on a button click:
protected void Button2_Click(object sender, EventArgs e)
{
String str = "SELECT * " +
"FROM ConcernTicket INNER JOIN Employee " +
"ON ConcernTicket.EmployeeReportedToID = Employee.EmployeeId " +
"WHERE (Employee.FirstName LIKE '%' + #search2 + '%')";
SqlCommand xp = new SqlCommand(str, vid);
xp.Parameters.Add("#search2", SqlDbType.NVarChar).Value =
TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Employee.FirstName");
GridView2.DataSource = ds;
GridView2.DataBind();
vid.Close();
}
The problem I am facing is that the search runs with no errors but instead of just returning the results where the FirstName variable matches, it displays all current Concern Tickets. I am assuming it is a fairly simple fix with the SELECT statement, but for some reason I have not been able to figure out what is going wrong. I just started working with sql so I apologize that I am having such a silly issue, any help would be appreciated, thanks!
Check that TextBox1.Text is not empty. If it is empty, the query will be:
WHERE (Employee.FirstName LIKE '%%')";
Also check that #search2 is being replaced properly. The + operator is not what you would expect in MySQL. Perhaps this is what you're looking for:
"WHERE (Employee.FirstName LIKE '%#search2%')";
Hope that helps
your problem is not the SQL query. In fact you use ExecuteNonQuery() to extract select result. ExecuteNonQuery() just returns a single integer.Please use a code like this and let me know if the problem persists.
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[1].ItemArray[1].ToString());
}
}
I have the following code:
{
c = Request.QueryString["city"];
SqlConnection objConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand objCmd2;
SqlDataReader objRdr2;
// String strCmd2;
objConn2.Open();
objCmd2 = new SqlCommand("SELECT * FROM subject_details WHERE Roll_no = " +"'" + c + "'", objConn2);
objRdr2 = objCmd2.ExecuteReader();
while (objRdr2.Read())
{
Label122.InnerText = (string)objRdr2["Name"].ToString().ToUpper();
objRdr2.Close();
objConn2.Close();
}
This code was working perfectly alright, suddenly I'm getting the error:
System.InvalidOperationException: Invalid attempt to call Read when
reader is closed.
Can anyone can help me why am getting this error
Close() should be after while loop as below
while (objRdr2.Read())
{
Label122.InnerText = (string)objRdr2["Name"].ToString().ToUpper();
}
objRdr2.Close();
objConn2.Close();
but above code set to Label122.InnerText last value from your query. So you should add TOP 1 to the query
objCmd2 = new SqlCommand("SELECT TOP 1* FROM subject_details WHERE Roll_no = " +
"'" + c + "'", objConn2);
then in Label122.InnerText will be first value from your query. You can also remove while loop as below
objRdr2.Read();
Label122.InnerText = (string)objRdr2["Name"].ToString().ToUpper();
objRdr2.Close();
objConn2.Close();
then in Label122.InnerText will be first value from the query too.
you shoudl remove objRdr2.Close(); from while loop
it should be after while loop
like below
while (objRdr2.Read())
{
Label122.InnerText = (string)objRdr2["Name"].ToString().ToUpper();
objConn2.Close();
}
objRdr2.Close();
if you close it inside while loop on next loop the error you specified will throw
i am trying the below query but i am getting error like incorrect syntax at SqlDataReader reader = command.ExecuteReader .. please correct me where i am wrong
string querystring = "SELECT ImageName FROM dbo.ProfilePic WHERE UserName = #UserName & IsActive = 'Y' order by ID Desc";
SqlCommand command = new SqlCommand(querystring, con);
command.Parameters.AddWithValue("#UserName", Session["UserName"].ToString());
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",
reader[0]));
ViewBag.ProfilePic = reader[0];
}
reader.Close();
updated with all suggested answers
SQL doesn't need the double equal signs.
SELECT ImageName FROM dbo.ProfilePic WHERE Username = #UserName
in SQL you don't need to use double equal sign to compare values and && is wrong, then this is wrong:
string querystring = "select ImageName from dbo.ProfilePic where UserName == #UserName && IsActive == 'Y' order by ID descending";
and this is true:
string querystring = "select ImageName from dbo.ProfilePic where UserName = #UserName AND IsActive = 'Y' order by ID desc";
string querystring = "select ImageName from dbo.ProfilePic where UserName =
#UserName AND IsActive = 'Y' order by ID DESC";
// on sql compare oprator not need to '==' sign
SqlCommand command = new SqlCommand(querystring, con);
command.Parameters.AddWithValue("#UserName", Session["UserName"].ToString());
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",
reader[0]));
// when you assign reader value to any object you must assign while DataReader read not after DataReader close
ViewBag.ProfilePic = reader[0];
}
reader.Close();
EDIT
try
string querystring = "select ImageName from dbo.ProfilePic where UserName like '#UserName' AND IsActive = 'Y' order by ID DESC";
I am trying to access a table in Visual Studio 2012 and am using Oracle 11g as the back end.
This is my code part which is giving error:
comm = new OracleCommand();
comm.Connection = conn;
comm.CommandText = "select * from message where send_username='" + username + "' or r_username='"+username+"' order by id desc";
ds = new DataSet();
da = new OracleDataAdapter(comm.CommandText, conn);
da.Fill(ds, "message");
dt = ds.Tables["message"];
The same query when i run in SQL Command Prompt, it gives me 3 tuples as output but in this it is giving error
There is no row at position 1.
It is only giving one particular row as output no matter whatever else i do.
Any idea what I am doing wrong ??
if (ds.Tables.Count > 0 )
{
dt = ds.Tables["message"];
}
And
if (ds.Tables["message"].Rows.Count > 0)
{
}
I am storing an image in a table in varbinary(max) format, actually first time it will be empty, I am checking whether it is empty of not but while checking for null field I am getting any exception stating invalid cast so can any one suggest what is the problem with this.
code sample is
con = new SqlCeConnection(CommonClass.ConnectionStringStartup);
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT Signature,UserId FROM UserMaster Where " +
" LoginName = '" + UserName + "' " +
" AND Password = '" + Password + "'";
cmd.CommandType = CommandType.Text;
// MessageBox.Show(UserName);
SqlCeDataReader dr;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
if (dr.IsDBNull(0))
SignLoaded = false;
else
SignLoaded = true;
}
Thanks in advance
With regards
Bharath kumar
To me, it looks like this should work?
Have you tried Convert.IsDbNull( dr.GetValue(0))?
Otherwise I can only suggest using dr.GetValue(0) and look at the result.
Cheers