c# Access OleDB err 80004005 - c#

I'm working on an app with an Access 2010 db connection and I keep receiving OleDB error 80004005 and I can't figure out why.
const String conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\OneDrive\Dropbox\SharpDevelop Projects\electronics inventory\electronics.mdb";
const String qCont = "select Section, Number, Stock from Container where Component = #IdComp order by Section, Number";
int oldParamSubcat = 0;
OleDbConnection connection = new OleDbConnection(conn);
void GrdCompCellClick(object sender, DataGridViewCellEventArgs e)
{
String IdComp = grdComp[grdComp.Columns["ID"].Index, grdComp.CurrentCell.RowIndex].Value.ToString();
try
{
grdSubcat.DataSource = null;
grdSubcat.Rows.Clear();
grdSubcat.Columns.Clear();
connection.Open();
OleDbCommand cmdDetail = new OleDbCommand();
cmdDetail.Connection = connection;
cmdDetail.CommandText = qDetail;
cmdDetail.Parameters.AddWithValue("#IdComp", Convert.ToInt32(IdComp));
txtDetails.Text = "";
OleDbDataReader rdDetail = cmdDetail.ExecuteReader();
rdDetail.Read();
txtDetails.Text = rdDetail["Component"].ToString() + "\r\n";
txtDetails.Text += rdDetail["Parameter"].ToString() + ": ";
txtDetails.Text += rdDetail["Val"].ToString() + "\r\n";
while(rdDetail.Read())
{
txtDetails.Text += rdDetail["Parameter"].ToString() + ": ";
txtDetails.Text += rdDetail["Val"].ToString() + "\r\n";
}
rdDetail.Close();
connection.Close();
connection.Open();
OleDbCommand cmdCode = new OleDbCommand();
cmdCode.Connection = connection;
cmdCode.CommandText = qCode;
cmdCode.Parameters.AddWithValue("#IdComp", Convert.ToInt32(IdComp));
txtDetails.Text += "\r\n";
OleDbDataReader rdCode = cmdCode.ExecuteReader();
while(rdCode.Read())
{
txtDetails.Text += rdCode["Seller"].ToString() + ": ";
txtDetails.Text += rdCode["Code"].ToString() + "\r\n";
}
rdCode.Close();
connection.Close();
connection.Open();
OleDbCommand cmdCont = new OleDbCommand();
cmdCont.Connection = connection;
cmdCont.CommandText = qCont;
cmdCont.Parameters.AddWithValue("#IdComp", Convert.ToInt32(IdComp));
txtDetails.Text += "\r\n";
OleDbDataReader rdCont = cmdCont.ExecuteReader(); ////////// here is where i receive the error ///////////////
while(rdCont.Read())
{
txtDetails.Text += "Container: ";
txtDetails.Text += rdCont["Section"].ToString() + "-";
txtDetails.Text += rdCont["Number"].ToString() + " = ";
txtDetails.Text += rdCont["Stock"].ToString() + " units\r\n";
}
rdCont.Close();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The rest of the code works perfectly, I only get the error on cmdCont.ExecuteReader();
The error message
If i execute the query in Access, it runs ok.
Any ideas are very much welcome.
Thanks.

The words Section, Number and Container are listed between the reserved keyword for MS-Access. You shouldn't use them in your table schema but if you really can't change these names to something different then you need to put them between square brackets
const String qCont = #"select [Section], [Number], Stock from [Container]
where Component = #IdComp order by [Section], [Number]";
Also you should use a more robust approach to your disposable objects like the connection, the commands and the readers. Try to add the using statement to your code in this way:
try
{
....
using(OleDbConnection connection = new OleDbConnection(......))
{
connection.Open();
....
string cmdText = "yourdetailquery";
using(OleDbCommand cmdDetail = new OleDbCommand(cmdText, connection))
{
.... // parameters
using(OleDbDataReader rdDetail = cmdDetail.ExecuteReader())
{
... read detail data ....
}
}
// here the rdDetail is closed and disposed,
// you can start a new reader without closing the connection
cmdText = "yourcodequery";
using(OleDbCommand cmdCode = new OleDbCommand(cmdText, connection))
{
.... parameters
using(OleDbReader rdCode = cmdCode.ExecuteReader())
{
// read code data...
}
}
... other command+reader
}
// Here the connection is closed and disposed
}
catch(Exception ex)
{
// any error goes here with the connection closed
}

Related

OleDb Update requires Insert Command?

I try to updata a single row, chosen by it ID. But what I got at best is an additional row instead of an updated one.
I made several attempts. Now I got a System.InvalidOperationException claiming that a valid InsertCommand is necessary for an update, if a DataRow listing will get a new row.
To me it is the same again: Why insert? I want to update.
Can anybody give me a hint?
This is my related code:
string selectQuery = $"SELECT * FROM Records";
string updateQuery = $"UPDATE Records SET AnyContent = #AnyContent WHERE [ID] = #ID";
OleDbDataAdapter adapter = null;
OleDbCommand cmd = null;
try
{
adapter = new OleDbDataAdapter(selectQuery, ConnectionString);
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = updateQuery;
cmd.Parameters.AddWithValue ("#AnyContent", "066066");
cmd.Parameters.AddWithValue("#ID", 2);
try
{
adapter.UpdateCommand = cmd;
nbRowsChanged = adapter.Update(content);
}
finally
{
adapter?.Close();
cmd?.Close();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
<<< Update >>>
Originally I tried it with an OleDbCommandBuilder before. But CommandBuilder created an update command, which seems to me like an insert command. This is why I tried it without CommandBuilder above. But inserting seems to follow me.
This is my old code, which is closer to where I want to get as it uses a DataTable instead of parameters:
string selectQuery = $"SELECT * FROM Records WHERE [ID] = ?";
OleDbConnection con = null;
OleDbDataAdapter adapter = null;
OleDbCommandBuilder builder = null;
try
{
adapter = new OleDbDataAdapter();
con = new OleDbConnection(ConnectionString);
adapter.SelectCommand = new OleDbCommand(selectQuery, con);
builder = new OleDbCommandBuilder(adapter);
try
{
con.Open();
nbRowsChanged = adapter.Update(content);
logText += "....InsertCommand: " + builder.GetInsertCommand().CommandText + "\n"; // Just to debug
logText += "....UpdateCommand: " + builder.GetUpdateCommand().CommandText + "\n"; // Just to debug
}
finally
{
con?.Close();
adapter?.Dispose();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
logText += tmpText ;
logText += "...Database: Access disposed.\n";
return isSuccess;
And this is the related trace:
LogText:
...Database: Trying to update <1> number of rows in table <Records>
....InsertCommand: INSERT INTO Records (AnyContent) VALUES (?)
....UpdateCommand: UPDATE Records SET AnyContent = ? WHERE ((ID = ?) AND ((? = 1 AND AnyContent IS NULL) OR (AnyContent = ?)))
.... Success: Updated <1> rows.
...Database: Access disposed.
NbRows Before: 5
NbRows After: 6

Pass next line as anew command

I want to print the output of the stored procedure in a .csv file.
When I insert a single stored procedure such as exec spGet Table 5 1,null,null,null,111,null,null,null,61,null,null,3;
Along with its parameters it executes. But when I pass the same procedure multiple times with different parameters, It only executes the first Stored procedure and the remaining are ignored. In the CSV file i only get the first SP Output.
My code is as follows
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnGetSku_Click(object sender, EventArgs e)
{
Stopwatch swra = new Stopwatch();
swra.Start();
StreamWriter CsvfileWriter = new StreamWriter(#"D:\testfile.csv");
string connectionString = null;
SqlConnection cnn;
connectionString = "Data Source=My-PC-Name;Initial Catalog=MyDB;User
cnn = new SqlConnection(connectionString);
ID=Name;Password=********";
cnn.Open();
SqlCommand cmd = new SqlCommand(textBox1.Text, cnn);
cmd.CommandText = textBox1.Text;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 2000;
using (cnn)
{
using (SqlDataReader rdr = cmd.ExecuteReader())
using (CsvfileWriter)
{
//For getting the Table Headers
DataTable Tablecolumns = new DataTable();
for (int i = 0; i < rdr.FieldCount; i++)
{
Tablecolumns.Columns.Add(rdr.GetName(i));
}
CsvfileWriter.WriteLine(string.Join(",",
Tablecolumns.Columns.Cast<DataColumn>().Select(csvfile =>
csvfile.ColumnName)));
while (rdr.Read())
{
label1.Text = rdr["SKU"].ToString() + " " +
rdr["SKUCode"].ToString();
CsvfileWriter.WriteLine(rdr["SKU"].ToString() + "," +
rdr["SKUCode"].ToString() + "," +
rdr["Compliance_Curr"].ToString() + "," +
rdr["Compliance_Prev"].ToString() + "," +
rdr["Difference"].ToString() + "," +
rdr["TotalSales_Curr"].ToString() + ",");
}
cnn.Close();
}
}
swra.Stop();
Console.WriteLine(swra.ElapsedMilliseconds);
}
}
I want to make sure that each procedure is executed differently and appended to the .csv file.
The problem you are facing is due to overwriting the file each time. So what you have in there is actually the result of the last execution of the command.
The culprit is the following line:
StreamWriter CsvfileWriter = new StreamWriter(#"D:\testfile.csv");
According to documentation,
If the file exists, it is overwritten; otherwise, a new file is created.
You need to use an overload of StreamWriter constructor which accepts a bool value specifying whether to append to the file or overwrite it.
var csvFileWriter = new StreamWriter(#"D:\testfile.csv", true);
Have you tried to call stored procedure with names of parameters (which declared in stored procedure)?
For example: EXECUTE spGet #Id = 1, #Number = 111, #....
In your code, you are creating StreamWriter object **everytime, you are clicking on **btnGetSku, Try to make it member variable and then write. Data is not being appended,
StreamWriter CsvfileWriter = null;
private void btnGetSku_Click(object sender, EventArgs e)
{
Stopwatch swra = new Stopwatch();
swra.Start();
if(CsvfileWriter == null)
CsvfileWriter = new StreamWriter(#"D:\testfile.csv");
string connectionString = null;
SqlConnection cnn;
connectionString = "Data Source=My-PC-Name;Initial Catalog=MyDB;User
cnn = new SqlConnection(connectionString);
ID=Name;Password=********";
cnn.Open();
SqlCommand cmd = new SqlCommand(textBox1.Text, cnn);
cmd.CommandText = textBox1.Text;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 2000;
using (cnn)
{
using (SqlDataReader rdr = cmd.ExecuteReader())
// Don't use using here. This disposes the streams
//using (CsvfileWriter)
{
//For getting the Table Headers
DataTable Tablecolumns = new DataTable();
for (int i = 0; i < rdr.FieldCount; i++)
{
Tablecolumns.Columns.Add(rdr.GetName(i));
}
CsvfileWriter.WriteLine(string.Join(",",
Tablecolumns.Columns.Cast<DataColumn>().Select(csvfile =>
csvfile.ColumnName)));
while (rdr.Read())
{
label1.Text = rdr["SKU"].ToString() + " " +
rdr["SKUCode"].ToString();
CsvfileWriter.WriteLine(rdr["SKU"].ToString() + "," +
rdr["SKUCode"].ToString() + "," +
rdr["Compliance_Curr"].ToString() + "," +
rdr["Compliance_Prev"].ToString() + "," +
rdr["Difference"].ToString() + "," +
rdr["TotalSales_Curr"].ToString() + ",");
}
cnn.Close();
}
}
swra.Stop();
Console.WriteLine(swra.ElapsedMilliseconds);
}

Wierd double quote being generated by C# going into SQL syntax

Could anyone point out what I'm doing wrong, I'm getting an error back in SQL saying Syntax error near '' at line 1
I have tried everything and can't seem to get rid of it ?
This is the code I'm Using -
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
MySqlConnection conn;
MySqlConnection conn1;
bool connection = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.toolStripStatusLabel1.Text = "Initialising";
db_connect();
}
private void db_connect()
{
string mydbconn = "server=localhost;user id=root;password=lap;database=test;";
string mydbconn1 = "server=localhost;user id=root;password=lap;database=test;";
try
{
conn = new MySqlConnection(mydbconn);
conn1 = new MySqlConnection(mydbconn1);
conn.Open();
conn1.Open();
this.toolStripStatusLabel1.Text = "Connected";
connection = true;
if (connection == true)
{
read_data();
}
}
catch (Exception ex)
{
this.toolStripStatusLabel1.Text = "WRONG";
connection = false;
}
}
private void read_data()
{
string sql = "SELECT first_name, last_name FROM dan";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string newsql = "REPLACE INTO dan1 (first_name, last_name) values";
newsql += "(";
for (int i = 0; i < 2; i++)
{
newsql += reader.GetString(i);
}
// System.Console.WriteLine(newsql);
int res = 0;
MySqlCommand cmd1 = new MySqlCommand(newsql, conn1);
try
{
res = cmd1.ExecuteNonQuery();
this.richTextBox1.Text = "copying";
}
catch (MySqlException ex)
{
this.richTextBox1.Text = ex.Message;
}
}
}
}
}
You are creating a query that looks like this:
REPLACE INTO dan1 (first_name, last_name) values(JohnDoe
when it should look like this;
REPLACE INTO dan1 (first_name, last_name) values ('John', 'Doe')
To create SQL dynamically like that you need to escape all the string data properly, and the way that it's done correctly depends on the database you are using. For MySQL it would be:
string newsql = "REPLACE INTO dan1 (first_name, last_name) values (";
bool first = true;
for (int i = 0; i < 2; i++) {
if (first) {
first = false;
} else {
newsql += ",";
}
newsql += "'" + reader.GetString(i).Replace("\\", "\\\\").Replace("'", "\\'") + "'";
}
newsql += ")";
However, you would rather use a parameterised query instead, then you don't have to worry about formatting the query and escaping characters correctly:
string newsql = "REPLACE INTO dan1 (first_name, last_name) values (#FirstName, #LastName)";
MySqlCommand cmd1 = new MySqlCommand(newsql, conn1);
cmd1.Parameters.Add("#FirstName", reader.GetString(0));
cmd1.Parameters.Add("#LastName", reader.GetString(1));
At a minimum I think that your query might be missing a closing paren. Your code seems to generate queries that look like this:
REPLACE INTO dan1 (first_name, last_name) values (first_name last_name
which is missing the closing ). I also do not see commas being added to separate the items in the values clause, and probably the items themselves are not quoted. Try this:
string newsql = "REPLACE INTO dan1 (first_name, last_name) values";
newsql += "(";
for (int i = 0; i < 2; i++)
{
newsql += reader.GetString(i);
}
newsql += ")";
// System.Console.WriteLine(newsql);

Windows service time out expired

protected override void OnStart(string[] args)
{
try
{
t.Enabled = true;
t.Interval = 10000; //60 * 24;
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
}
catch (Exception ex)
{
writeErrorToFile(ex.Message + " -- (OnStart) --");
}
}
this is my onstart method. I am new to making the windows service. Can you explain me what the code inside the instart method does.? I am not able to get the right answer when i googled.
Following is the method that is called from the onstart method
private void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
// Read Data from Excel
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
SqlCommand sm = new SqlCommand();
string connString = "";
string query = "";
string strDt = DateTime.Now.ToString("dd_MM_yyyy");
string strNewPath = #"E:\E-Cata_Stock_Report\ALL_INDIA_STOCK_REPORT_" + strDt + ".xls"; //Server.MapPath(#"C:\E-Cata_Stock_Report\ALL_INDIA_STOCK_REPORT.xls"); // ///" + strFileName + strFileType);
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
query = "SELECT * FROM [SPARE_LIST$]";
conn = new OleDbConnection(connString);
//Open connection
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
//Create the command object
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
dsExcel = new DataSet();
try
{
da.Fill(dsExcel);
}
catch (Exception ex)
{
writeErrorToFile(ex.Message + " -- (t_Elapsed -> Keep valid excel file which you want to upload..) --");
//lblMsg.Text = "Keep valid excel file which you want to upload..";
return;
}
//lblMsg.Text = "Data retrieved successfully! Total Records:" + dsExcel.Tables[0].Rows.Count;
da.Dispose();
conn.Close();
conn.Dispose();
if (dsExcel.Tables[0].Columns.Count != 32)
{
writeErrorToFile("Please check the Excel Sheet.. It contains more or less columns..");
return;
}
if (dsExcel.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < dsExcel.Tables[0].Rows.Count; i++)
File.AppendAllText(#"C:\E-Cata_Itms.txt", dsExcel.Tables[0].Rows[i][0].ToString() + " \n\r"+i+i);
}
//======================================================================================================
string con = getConn_string();
SqlConnection sn = new SqlConnection(con);
if (sn.State == ConnectionState.Open)
sn.Close();
sn.Open();
SqlTransaction transaction = sn.BeginTransaction();
try
{
for (int j = 4; j < dsExcel.Tables[0].Rows.Count; j++) // for rows
{
for (int i = 2; i < 32; i++) //for coloumns
{
sm = new SqlCommand();
sm.Transaction = transaction;
sm.CommandText = "whItmItemwise_upload_update";
sm.Connection = sn;
sm.CommandType = CommandType.StoredProcedure;
sm.Parameters.AddWithValue("#whItm_wh_code", dsExcel.Tables[0].Rows[3][i].ToString().Trim());
sm.Parameters.AddWithValue("#whItm_item_code", dsExcel.Tables[0].Rows[j][0].ToString().Trim());
try
{
// open stock quantity
decimal op_qty = (dsExcel.Tables[0].Rows[j][i].ToString().Trim() ==
"")
? Convert.ToDecimal(0.0)
: Convert.ToDecimal(
dsExcel.Tables[0].Rows[j][i].ToString().Trim
());
sm.Parameters.AddWithValue("#whItm_OP_STK_Qty", op_qty);
}
catch (Exception ex)
{
writeErrorToFile(ex.Message + " -- (t_Elapsed -> Enter valid Open stock quantity..) --"+i);
return;
}
sm.Parameters.AddWithValue("#whItm_Creation_DT", DateTime.Now.ToString("yyyy/MM/dd"));
//sm.Parameters.AddWithValue("#whItm_Created_By", "");
//sm.Parameters.AddWithValue("#His_whItm_Modify_Del_DT", DateTime.Now.ToString("yyyy/MM/dd"));
//sm.Parameters.AddWithValue("#His_whItm_Modify_Del_By", "");
try
{
int x = sm.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Text.StringBuilder str_Upload = new System.Text.StringBuilder();
str_Upload.Append(dsExcel.Tables[0].Rows[3][i].ToString().Trim() + ",");
str_Upload.Append(dsExcel.Tables[0].Rows[j][0].ToString().Trim() + ",");
str_Upload.Append(ex.Message.Replace(',', '-') + ",");
str_Upload.Append(DateTime.Now.ToString("dd/MM/yyyy") + ",");
File.AppendAllText(#"C:\E-Cata_Error" + ".csv", str_Upload.ToString());
}
sm.Parameters.Clear();
}
}
// Update stock from WH master to Item Master
SqlCommand sm2 = new SqlCommand();
sm2.Transaction = transaction;
sm2.CommandText = "Stock_Update_from_WH_to_Item_master";
sm2.Connection = sn;
sm2.CommandType = CommandType.StoredProcedure;
sm2.Parameters.AddWithValue("#Item_Code", "");
sm2.ExecuteNonQuery();
transaction.Commit();
sm2.Dispose();
MyNewService iyu = new MyNewService();
iyu.Stop();
}
catch (Exception ex)
{
transaction.Rollback();
writeErrorToFile(ex.Message+"abcd");
return;
}
finally
{
sm.Dispose();
transaction.Dispose();
sn.Close();
sn.Dispose();
}
//try
//{
// // delete uploaded file
// File.Delete(strNewPath);
//}
//catch (Exception)
//{
//}
}
catch (Exception ex)
{
writeErrorToFile(ex.Message + " -- (t_Elapsed) --"+"xyz");
}
}
Windows service has to inherit from ServiceBase class. It has OnStart and OnStop virtual methods that we need to override in the service class.
In your code, when the windows service is started, OnStart method is invoked. In this method the timer is enabled and set the interval to 10 sec. Timer interval always sets in milliseconds, that’s why value is 10000. When 10 sec elapsed the method subscribed in the Elapsed event is fired, in this case the t_Elapsed method in fired.
See the following article for hosting the wcf service in a managed windows service.
http://msdn.microsoft.com/en-us/library/ms733069.aspx

ORA-01036: illegal variable name/number

I retrieve data from Oracle database and populate a gridview. Next, I try to run a query to select some data but I get an error.
Here is the code:
Db.cs:
public static OracleConnection GetConnection()
{
OracleConnection connection = null;
string connectionString = "Data Source=" + Database +
";User ID=" + UserID +
";Password=" + Password +
";Unicode=True";
try
{
connection = new OracleConnection(connectionString);
}
catch (OracleException ex)
{
throw ex;
}
return connection;
}
Parameters are sent from default.aspx.cs:
new Db(database, userID, password);
OracleConnection connection = Db.GetConnection();
main.aspx.cs retrieves all the data:
private OracleConnection connection = new OracleConnection();
private Select select = new Select();
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
if (Db.IsLoggedIn())
{
string selectCommand =
"SELECT " + Settings.TABLE + ".* FROM " + Settings.TABLE + " ORDER BY ";
foreach (string ob in Settings.OB) selectCommand += ob + ", ";
Session["Error"] = null;
connection = Db.GetConnection();
select = new Select(ddlBubID, ddlBusArea, ddlDrillSite, ddlWell, connection);
gvData.DataKeyNames = Settings.PK;
gvData.SelectedIndex = -1;
DS.ConnectionString = connection.ConnectionString;
DS.SelectCommand = selectCommand.Remove(selectCommand.Length - 2, 2);
DS.ProviderName = Settings.PROVIDER_NAME;
PopulateFooter(gvData.FooterRow);
}
else
{
Session["Error"] = Settings.ERROR_MESSAGE[0, 0];
Response.Clear();
Response.Redirect("default.aspx");
}
}
public string ToolTip(string column)
{
string value = "";
OracleCommand cmd = new OracleCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT DISTINCT COMMENTS " +
"FROM SYS.ALL_COL_COMMENTS " +
"WHERE (TABLE_NAME = 'CTD_PROBLEM_EDIT_V') " +
"AND (COLUMN_NAME = " + column + ")";
cmd.CommandType = CommandType.Text;
OracleDataReader reader = cmd.ExecuteReader(); // I get an error here
reader.Read();
value = reader["COMMENTS"].ToString();
reader.Close();
return value;
}
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
for (int i = 1; i < e.Row.Cells.Count; i++)
{
try
{
LinkButton lb =
(LinkButton)gvData.HeaderRow.Cells[i].Controls[0];
lb.ToolTip = ToolTip(lb.Text);
/* Blah Blah*/
}
catch { }
}
if (e.Row.RowType == DataControlRowType.Footer)
PopulateFooter(e.Row);
}
ToolTip(); throws an error:
Invalid operation. The connection is closed.
EDIT:
This would have been helpful:
Static Classes and Static Class Members
Might not be the problem but this looks weird:
new Db(database, userID, password);
OracleConnection connection = Db.GetConnection();
GetConnection is a static method and thus it does not see any member attributes you might be setting in the constructor (unless they are static as well). If they are all static, consider refactoring your code to use the singleton pattern as it is more readable.
Another thing is that the connection attribute is a member of the page class which is generated for each request (not per application). This means you need either create a new connection in ToolTip method (and any other method that accesses the database) or make the connection attribute static to make it per-application.
Try 2 things:
1.. For your ToolTip() method, the value column to compare for COLUMN_NAME will need to be wrapped properly with single quotes indicating a string/varchar literal value. Likely it's evaluating to COLUMN_NAME = foo when it should be COLUMN_NAME = 'foo'.
cmd.CommandText = "SELECT DISTINCT COMMENTS " +
"FROM SYS.ALL_COL_COMMENTS " +
"WHERE (TABLE_NAME = 'CTD_PROBLEM_EDIT_V') " +
"AND (COLUMN_NAME = '" + column + "')";
2.. Try wrapping your ad-hoc SQL statements in BEGIN and END
3.. Consider refactoring your string building for your SELECT and dynamic ORDER BY clause. That you're doing it on the SelectCommand many lines below isn't obvious to the casual observer or maintainers later in its life.
string selectCommand = string.Format("SELECT {0}.* FROM {0} ORDER BY {1}"
,Settings.TABLE
,string.Join(",",Settings.OB));

Categories

Resources