Error binding in GetColumnNumber at row 1 - c#

I got this OfficeWriter error when debugging the console application. I used methods to retrieve config details for the database used in the coding from the master database, and ended up having this error.
Error binding in GetColumnNumber at row 1
Attached here is partial coding for my work. Anyone can explain me what the error is?
SqlDataReader rdSource = getSource();
SqlDataReader rdDestination = getDestination();
SqlDataReader rdCode = getCode();
while (rdSource.Read() && rdDestination.Read())
{
string src = rdSource["Value"].ToString();
string dest = rdDest["Value"].ToString();
ExcelTemplate XLT = new ExcelTemplate();
XLT.Open(src);
DataBindingProperties dataProps = XLT.CreateBindingProperties();
XLT.BindData(rdCode, "Code", dataProps);
XLT.Process();
XLT.Save(dest);
}
//rdCode method
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
while (rdConnection.Read())
{
string con = rdConnection["Value"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
string SQL = "SELECT * FROM Sales.Currency";
sqlCon.Open();
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader();
sqlCon.Close();
}
return rdConnection;
//getConnection method
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string cSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = 'Data Source=localhost;Initial Catalog=Test;Integrated Security=True'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);
//getSource & getDestination methods
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string srcPath = #"FILE PATH NAME"; //change to destPath for getDestination
string sSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = '" + srcPath + "'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);

The error is a generic message that is thrown by ExcelWriter when it is unable to bind data to the template.
I think this might be caused by your getCode() method. In getCode(), you use a SQLDataReader to retrieve the connection string for the database:
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
Then you execute a SQL query against that database, but you don't actually get a handle on the SqlDataReader that is executing the SQL query to return the data.
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader(); //Note: This returns the SqlDataReader that contains the data
Then you return rdConnection, which is the SQLDataReader for the connection string - not the data you are trying to import. rdConnection contained 1 row and you already called Read(), so there are no records left to read.
SqlDataReader rdCode = getCode();
...
XLT.BindData(rdCode, "Code", dataProps);
The SQL reader you are binding is the used 'connection string', rather than your sales data. I would recommend the following:
Return the new SqlDataReader that is generated by cmd.ExecuteReader() in getCode(), rather than rdConnection.
Do not close the connection to this new SqlDataReader. ExcelWriter needs to be able to read the data reader in order to bind the data. If you close the connection, ExcelWriter will not be able to bind data correctly.

Related

Why does my drop down list display “System.Data.DataRowView” instead of real values?

I tried to get data in a drop down list and it's not working. I don't understand what's the problem.
string connString = #" Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\oshri\Documents\Stock scores.mdf';Integrated Security=True;Connect Timeout=30";
string queryLecturer = "select name_student from student";
SqlConnection conn = new SqlConnection(connString);
//SqlCommand cmdL = new SqlCommand(queryLecturer, conn);
conn.Open();
//SqlCommand SQLCommand = new SqlCommand();
//cmdL.CommandType = CommandType.Text;
//SQLCommand.CommandText = queryLecturer;
//conn.Close();
SqlDataAdapter adapter = new SqlDataAdapter(queryLecturer, conn);
adapter.Fill(subjects);
DropDownListID.DataSource = subjects;
DropDownListID.DataBind();
DropDownListID.DataBind();
conn.Close();
You are assigning a DataSet containing DataRowView items to your drop down. Your drop down (is it a System.Windows.Forms.ComboBox?) is not smart enough to extract the real values from this DataSet. Instead, use a SqlDataReader to read your string values and add them to a list that you can use as data source for your drop down.
string connString = #"Data Source=...";
string queryLecturer = "select name_student from student";
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(queryLecturer)) {
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader()) {
var list = new List<string>();
while (reader.Read()) {
list.Add(reader.GetString(0)); // 0 is the column index.
}
DropDownListID.DataSource = list;
}
}
The using statements automatically close the connection and dispose resources at the end of the statement blocks. They do so even if the statement blocks are left prematurely because of an exception or because of a break or return statement.

C# How to execute a string and then store the results of that?

For reference, this page (add.ashx.cs), is an add page to a database.
What I'm trying to do is :
figure out how to execute string queryID, and then
store the results of queryID
I'm a bit new at this, but this is what I'm working with so far. Am I on the right path, and what should I change? I don't believe the code below includes storing the results, but just executing queryID.
// new query to get last ID value
// store the command.executeNonQuery results into a variable
string queryID = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
// first: look up how to execute queryID
// then: store results of query ^
// execute queryID? (section below)
SqlConnection sqlConnection1 = new SqlConnection(queryID);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * FROM queryID";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// data is accessible through the datareader object here
sqlConnection1.Close();
There are some things missmatched in your code sample. First queryID is your actual query. Second in SqlConnection you need to provide a connection string, that connects to your database (SQL Server, ACCESS, ...). A valid example could look like this:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
SqlDataReader reader;
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
List<string> results = new List<string>();
if(reader.HasRows)
{
while(reader.Read())
{
results.Add(reader[0].ToString());
}
}
sqlConnection1.Close();
Another thing is, that you execute a reader but only select one single value. You can perfectly use ExecuteScalar for that:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
sqlConnection1.Close();
One last thing. You should use objects that implement IDisposable in a using block. This way the will be removed from memory when they are no longer needed:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
using(SqlConnection sqlConnection1 = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
}

C# Query MS-Access Table and place read values from column in a text box

Below is a snapshot of my code. I am trying to access the only column in the customer table and place the values into a textbox on the form. I keep getting the error with my code "InvalidOperationException was unhandled" at the line declaring dr as a OleDbDataReader object.
What do I have wrong with the below code that would be giving me this error?
Should I do a list to pick out the text I want from the database?
How can I return the column values from access into a list in C# so that I can search the list for a particular value?
string strsql = "Select * from Customer";
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
textBox1.Text += dr["Customer"].ToString();
}
conn.Close();
A command carries the info to be executed, a connection carries the info to reach the database server. The two objects should be linked together to produce any result. You miss that line
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
cmd.Connection = conn; // <= here
conn.Open();
Remember also that disposable objects like a command, a reader and a connection should be disposed immediately after usage. For this pattern exists the using statement
So you should write
string cmdText = "Select * from Customer";
using(OleDbConnection conn = new OleDbConnection(.....constring...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, conn))
{
conn.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
.....
}
}
Here is some sample code.
try
{
using (OleDbConnection myConnection = new OleDbConnection())//make use of the using statement
{
myConnection.ConnectionString = myConnectionString;
myConnection.Open();//Open your connection
OleDbCommand cmdNotReturned = myConnection.CreateCommand();//Create a command
cmdNotReturned.CommandText = "someQuery";
OleDbDataReader readerNotReturned = cmdNotReturned.ExecuteReader(CommandBehavior.CloseConnection);
// close conn after complete
// Load the result into a DataTable
if (readerNotReturned != null) someDataTable.Load(readerNotReturned);
}
}
After that you have a Datatable containing your data. Ofcourse you can afterwards search for records in the Datatable any way you like.

Populate listview with data received from SQL query

I am currently trying to populate a listview with some data I have pulled from my database table; but not sure where to start; I have tried the following:
lstData.DataSource = conn;
lstData.DataBind();
But that causes an error:
"Data source is an invalid type. It must be either an IListSource,
IEnumerable, or IDataSource. MVC"
Am I using the correct query strings in order to populate my listview?
Thanks,
Callum
C# Code:
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
command.ExecuteNonQuery();
string com = command.ExecuteScalar().ToString();
lblSQL.Text = com;
conn.Close();
Using your code as a base to start from you may want to try the following: I assume your connection in "Server connection" is a place holder for a real connection string and you know what should go there.
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dataTable;
da.Fill(dataTable);
lstData.DataSource = dataTable;
lstData.DataBind();
conn.Close();

Retrieving values from DB to Label in C#

I have created an Entity Framework application to retrieve Database values but i want to show them in individual labels instead of a gridview??
EmployEntities2 fd = new EmployEntities2();
int idToupdate = Convert.ToInt32(TextBox1.Text);
var jj = (from bn in fd.Contacts
where bn.Id == idToupdate
select bn);
GridView1.DataSource = jj;
GridView1.DataBind();
Established a connection
SqlConnection con = new SqlConnection("CONNECTION_STRING);
SqlCommand cmd = new SqlCommand();
and then,
cmd.CommandText = "select * from table where Condition ;
cmd.Connection = con
Label1.text = ((string)cmd.ExecuteScalar());
Try this one..
You should use SQLDataReader class. Base on what type of data you have in structure you should call a different method of the SQLDataReader object. For example, if you need to retrieve an integer value and display it in a label, this is the code sinppet to do it:
string queryString = "SELECT integer_value FROM table_name";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
label1.Text = reader.getSqlInt32(0).ToString();
}
reader.close();
}
This is the best I can do since you didn't provide additional info.
Check out this link for info on SqlDataReader class: SqlDataReader reference

Categories