How to fix this error ''reader' is a 'variable' but is used like a 'method'' - sql

I am using a C# class.Everythink working fine but i am facing this error, so please help to fix this error.
public void Filldropdownlist(DropDownList ddl, string DisplayVal, string Qstr)
{
try
{
CreateConn();
SqlCommand cmd = new SqlCommand(Qstr, constr);
SqlDataReader reader = cmd.ExecuteReader();
ddl.Items.Clear();
ddl.Items.Add(new ListItem(DisplayVal, "none"));
while (reader.Read())
{
ddl.Items.Add(new ListItem(reader(0).ToString(), reader(1).ToString()));
ddl.DataTextField = reader(0).ToString();
ddl.DataValueField = reader(1).ToString();
}
}
catch (Exception ex)
{
}
finally
{
CloseConn();
}
}
problem coming in inside the while loop.

Indexing in C# is done with the [] operator, not with the () operator as in, for example Visual Basic.
In essence
reader(0)
means "call the method reader with and argument 0" and
reader[0]
means give me value with the index 0 within the variable reader.
Aside from that, the DataTextField and the DataValueField are used only if you are data-binding the drop down, not if you are manually inserting the items, so those two lines can be omitted.
They are also incorect, because they need to be set to the name of the fields, not to their values

Change like this:
while (reader.Read())
{
ddl.Items.Add(new ListItem(reader[0].ToString(), reader(1).ToString()));
ddl.DataTextField = reader[0].ToString();
ddl.DataValueField = reader[1].ToString();
}
use [] instead of ()

Related

How to check whether table column of the binary type has a value?

The Download command is showing in front of all the rows, I want to show it to only those rows having PDF file attached in the database.
protected void gvupdationsummary_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(st);
con.Open();
SqlCommand com = new SqlCommand("select [name],[data] from [Pragati].[dbo].[Pragati_Status_Updations] where Pragati_no=#Pragati_no", con);
com.Parameters.AddWithValue("Pragati_no", gvupdationsummary.SelectedRow.Cells[3].Text);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
Response.Clear();
Response.Buffer = true;
//Response.ContentType = dr["type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dr["name"].ToString());
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dr["data"]);
Response.End();
}
else
{
// ...
}
}
The code that you show seems to do the actual PDF download already. There is nothing you can do there to prevent the showing of a download button or link.
Instead you need to change the SQL query that provides data for gvupdationsummary, and add a column such as HasPDF there, like this:
SELECT /* your columns */ ,
CAST(CASE WHEN [data] IS NULL THEN 0 ELSE 1 END AS BIT) AS HasPDF
FROM ....
WHERE ....
Then in your grid rendering code you can use the boolean value of HasPDF to decide if the Download button should be shown.
Using this approach you don't needlessly transfer all PDF binary data from your database to your application, every time the grid is being rendered.
You can use SQLDataReader's IsDBNull method to see whether the column contains non-existent or missing values.
ind idx = dr.GetOrdinal("data");
if (!dr.IsDBNull(idx))
{
// set download link on to response.
}
else
{
}

SQL Command not properly ended Exception

Pretty basic sql Command. Just want to get the count from different tables I am looping through. However, if I alter the sqlCommand and add a ';' at the end I get exception, SQL command not properly ended.
sqlCommand = String.Format("SELECT COUNT(1) FROM SO.{0} where DR_ADDRESS_ID = {1};", table, drAddr);
I am curious why this semi-colon makes this exception thrown since commands are suppose to end with a ';'
sqlCommand = String.Format("SELECT COUNT(1) FROM SO.{0} where DR_ADDRESS_ID = {1}", table, drAddr);
try
{
using(OracleCommand ocCommand = new OracleCommand(sqlCommand,CommandType.Text))
{
ocCommand.Connection = dbConnection;
recordCounter = Convert.ToInt64(ocCommand.ExecuteScalar());
}
}
catch (Exception er)
{
MessageBox.Show(String.Format("Error in RecordCount for table {0}: Reference {1} for log. err = {2}",table, logFilePath,er.ToString()));
recordCounter = -1;
using (StreamWriter writer = new StreamWriter(logFilePath, true))
{
writer.WriteLine(String.Format("Table: {0}. Command {1}", table,sqlCommand.ToString()));
}
}
Semi colons are usually just used as a command terminator for interactive tools like sqlplus.

SQL ERROR: The connection was not closed. The connection's current state is open

EDIT
After staring at this for 2 days, I do see one issue. I was still opening the original connection. So I changed the inner open statements to conn2.Open. Then, I changed the second inner query to where all the variables were number 3 instead of 2 so that they were completely different than the previous query. At that point, I got the error:
There is already an open DataReader associated with this Command which must be closed first.
I took out the inner connections, thinking I could use the outer connection and took out the inner .Close lines, but that also returned an error saying the connection was not closed.
END EDIT
I am writing a script that updates user information with data pulled from other tables where that user may be in it multiple times for purchases made.
So first, the "outside" sql query pulls some data from the items table which contains purchaser information as well as category information. For each item, it is going to check it's purchaser's information.
Second, the first "inner" sql query pulls category information from the user table. Some code is then run to see if they're already marked as purchasing from the category of the "outside" query. If they are not, it adds the category to a string variable.
Lastly, the second "inner" sql query updates the user table for the current user with the new category list.
I've asked about how to perform queries like this before, but was always given a solution of combining the queries into one. That worked for the other queries, but I cannot do that here. I must iterate through each record of the outer query to perform the necessary functions inside of it. But my issue here is that I get an SQL error saying that the connection was not closed, and it points to the catch of the outer query (for 'conn').
I had tried to set my 2 inner queries so that they used different connection variables (conn2 and conn3), and also different strSQL variables, but that didn't help. And I'm still a newb when it comes to SQL, having programmed using MySQL until this probject. Any help would be greately appreciated.
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionName"].ToString()))
using (SqlCommand strSQL = conn.CreateCommand())
{
strSQL.CommandText = "SELECT field FROM itemsTable";
try
{
conn.Open();
using (SqlDataReader itemReader = strSQL.ExecuteReader())
{
while (itemReader.Read())
{
{Do some stuff here}
using (SqlConnection conn2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionName"].ToString()))
using (SqlCommand strSQL2 = conn2.CreateCommand())
{
strSQL2.CommandText = "SELECT fields FROM userTable";
try
{
conn2.Open();
using (SqlDataReader itemReader2 = strSQL2.ExecuteReader())
{
while (itemReader2.Read())
{
{Do stuff here}
}
itemReader2.Close();
}
}
catch (Exception e3)
{
throw new Exception(e3.Message);
}
finally
{
conn2.Close();
}
}
{Do some more stuff here}
using (SqlConnection conn2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionName"].ToString()))
using (SqlCommand strSQL2 = conn2.CreateCommand())
{
strSQL2.CommandText = "UPDATE userTable set field='value'";
try
{
conn2.Open();
strSQL2.ExecuteNonQuery();
}
catch (Exception e2)
{
throw new Exception(e2.Message);
}
finally
{
conn2.Close();
}
}
{Do even more stuff here.}
}
itemReader.Close();
}
}
catch (Exception e1)
{
throw new Exception(e1.Message);
}
finally
{
conn.Close();
}
}
There's some unusual logic going on with conn.Open(). I see it used several times, but I think you mean to use conn2.Open() in the inner using statements after the first call.

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool

I am fairly new in asp.net development, so you can say that I have developed a poorly coded application that is giving me this error.
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.
I tried searching on google and found that it happens because of unclosed connections in the application pool so I carefully examined my application and inserted using keyword for all Sqlconnections but still I am having this problem, here is some sample code from my application. All Sqlconnections are enclosed in using statement like this.
using (Connection = new SqlConnection(CIPConnection))
{
string ReturnValue = String.Empty;
try
{
SqlDataReader Reader;
Connection.Open();
string CommandText = "SELECT * FROM Users WHERE NAME = #NAME AND PASSWORD = #PASSWORD";
Command = new SqlCommand(CommandText, Connection);
Command.Parameters.AddWithValue("#NAME", UserName);
Command.Parameters.AddWithValue("#PASSWORD", Password);
Reader = Command.ExecuteReader();
Reader.Read();
if (Reader.HasRows)
{
Session["ID"] = Reader["ID"];
Session["NAME"] = Reader["NAME"];
Session["DEPARTMENT"] = Reader["DEPARTMENT"];
switch (Reader["DEPARTMENT"].ToString())
{
case "Admin":
ReturnValue = "Admin";
break;
case "Editing":
ReturnValue = "Editing";
break;
case "Sales and Support":
ReturnValue = "Sales and Support";
break;
case "Writing":
ReturnValue = "Writing";
break;
default:
ReturnValue = "Sorry";
break;
}
}
}
catch (Exception exp)
{
Response.Write(exp.Message.ToString());
}
return ReturnValue;
}
Now my question is do I need to close Connection even in using statement block ? what will be the best way to close connection ? (putting it in finally block ? with every try statement ?) should I also use using statement with SqlReader and SqlCommand ? Please tell me the best way to get rid of unused connections so I can solve this problem.
Thanks.
Perhaps the problem is related to the SqlDataReader object, which is not closed. Try a using block:
using (var Reader = Command.ExecuteReader())
{
As a sidenote, the Read function returns false if no rows were found. So you could shorten this:
Reader.Read();
if (Reader.HasRows)
{
to:
if (Reader.Read())
{
No, when it exists the using block, it will Dispose, which will Close and return it to the pool. The problem lies elsewhere, or you missed one.
Does End Using close an open SQL Connection

Unable to update a list item from a workflow task in C#

I am not getting any exceptions, but the code below is simply not working. Any ideas?
SPSecurity.RunWithElevatedPrivileges(delegate() {
using (SPWeb web = this.workflowProperties.Web) {
try {
SPListItem item = web.Lists["NewHireFormsLibrary"].Items[workflowProperties.ItemId - 1];
item["Field 1"] = "Gotcha!!!";
item.Update();
LogHistory("Information", "Workflow indexing complete. " + item["Field 1"], "");
}
catch (Exception ex) {
LogHistory("Error", ex.Message, ex.StackTrace);
}
}
)};
It looks like you are not referencing the field by it's Internal Name, which is how you have to reference fields when accessing them with the SPListItem's indexer. Try something like
item["Field_x0020_1"] = "Gotcha!!!";
and it should work. Note that Internal names never contain spaces and are replaced by their hex character string like above.