I am attempting to get the data my connectionstring pulls in my C# class's to the appropriate data controls on my website. I have looked online how to go about doing this but no results. I figured it would be easy like C# and you just reference the control you want to fill in the .Net page. Any suggestions on how to get my data into my controls? I have posted my c# code to get the data.
load method:
public void load()
{
var sqlString = new StringBuilder();
sqlString.Append("SELECT CaseNum6, CaseNum9, Group, Completion ");
sqlString.Append("FROM WorkOrder ");
sqlString.Append("WHERE Group = 1 OR Group = 2 ");
sqlString.Append("AND Completion = 0 ");
SqlDataReader reader = null;
SqlConnection dbConn = DBHelper.getConnection();
SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("#CaseNum6", CaseNum6 )};
try
{
reader = DBHelper.executeQuery(dbConn, sqlString.ToString(), parameters);
if (reader != null)
{
if (reader.Read())
{
CaseNum6 = (int)reader["CaseNum6"];
CaseNum9 = (int)reader["CaseNum9"];
Group = (int)reader["Group"];
Completion = (bool)reader["Completion"];
}
else
throw new Exception("No record returned");
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
}
}
DBHelper:
class DBHelper
{
private DBHelper() { }
public static SqlConnection getConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
}
public static SqlConnection getFRESHConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["FRESHConnection"].ConnectionString);
}
public static SqlDataReader executeQuery(SqlConnection dbConn, string sqlString, SqlParameter[] parameters)
{
SqlCommand cmd = null;
SqlDataReader reader = null;
try
{
if (dbConn.State == ConnectionState.Closed)
dbConn.Open();
cmd = dbConn.CreateCommand();
cmd.CommandText = sqlString;
if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}
reader = cmd.ExecuteReader();
cmd.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return reader;
}
}
Not sure what exactly is the issue. But to give an overview of how to add values to controls.
Drop a control from the toolbox into the web page(.aspx).
You will now be able to reference it in the code behind, and simply use something like
TextBox1.Text = "Hello World"; // TextBox1 is the id of the control
See more on MSDN docs
Get and Set values on Textboxes
Did not have the right file extension for background coding.
Related
I currently have a DB library used for database access and I use it across several projects. I currently use the following code to get a recordset.
METHODS
public static IDataReader GetRs(string sql)
{
using (var con = NewSqlConnection())
{
con.Open();
return GetRs(sql, con);
}
}
public static IDataReader GetRs(string sql, SqlConnection dbconn)
{
using (var cmd = new SqlCommand(sql, dbconn))
{
int tries = 1;
while (tries <= 3)
{
try
{
if (dbconn.State == ConnectionState.Closed)
{
dbconn.Open();
}
DataTable myTable = new DataTable();
var reader = cmd.ExecuteReader();
myTable.Load(reader);
return myTable.CreateDataReader();
//return cmd.ExecuteReader();
}
catch (SqlException ex)
{
if (ex.Message.Contains("Timeout expired") || ex.Number == 1205) // Deadlock
{
Thread.Sleep(1000);
if (tries == 3)
{
throw ex;
}
tries += 1;
cmd.CommandTimeout *= 10;
}
else
{
throw ex;
}
}
}
}
throw new Exception("Could not get RecordSet");
}
USAGE
public static void Test()
{
using(var reader = GetRs("SELECT Col FROM TABLE"))
{
while(reader.Read())
{
// do stuff with data here e.g. var value = reader[0];
}
}
}
While this method works, as you can see it loads the entire dataset into memory thus causing issues with scaling.
I tried replacing the following code in the GetRs(string sql, SqlConnection con) method
DataTable myTable = new DataTable();
var reader = cmd.ExecuteReader();
myTable.Load(reader);
return myTable.CreateDataReader();
and tried returning just the return cmd.ExecuteReader();
However an error is thrown on the while (reader.Read()) - Invalid attempt to call read when the reader is closed. I am guessing this is because the SqlConnection property is disposed (and hence closed) after returning the IDataReader.
I'm aware that I can wrap the GetRs method with a new sql connection but this means rewriting a lot of my code, and I was hoping that I would be able to dispose the reader AND the connection with my using(var reader = GetRs()) method.
Is there any way I can still use these methods without loading the whole dataset into memory?
You can inject in your code with a Action<DataTableReader> parameter to you GetRs call.
Try this:
public static void GetRs(string sql, Action<DataTableReader> consumer)
{
using (var con = NewSqlConnection())
{
con.Open();
GetRs(sql, con, consumer);
}
}
public static void GetRs(string sql, SqlConnection dbconn, Action<DataTableReader> consumer)
{
using (var cmd = new SqlCommand(sql, dbconn))
{
if (dbconn.State == ConnectionState.Closed)
{
dbconn.Open();
}
DataTable myTable = new DataTable();
var reader = cmd.ExecuteReader();
myTable.Load(reader);
consumer(myTable.CreateDataReader());
}
}
(I removed your try/catch code for clarity.)
Then you call it like this:
public static void Test()
{
GetRs("SELECT Col FROM TABLE", reader =>
{
while(reader.Read())
{
// do stuff with data here e.g. var value = reader[0];
}
});
}
Your connection object was closed by the following line
using (var con = NewSqlConnection())
{
con.Open();
return GetRs(sql, con);
}//Connection object gets released here
But still, you are returning the reader object which was created by SqlCommand object using the above connection object. Hence the reader object is closed.
I am running an sql database for movies and I am working on this function so that whenever a user checks out a movie, the movie would be updated saying it has been checked out, then the checked out movie would be added to a table for checked out movies. I have a code that runs without any errors but my checked out movie does not get added to my checked out table. Code for the gridview that displays the selected movie below:
<asp:ListBox ID="CheckOutList" runat="server" OnSelectedIndexChanged="Get_data" AutoPostBack="true">
</asp:ListBox>
<asp:Panel ID="panel5" runat="server" Visible="false">
<asp:GridView id="one_data" AutoGenerateColumns="false" runat="server" DataKeyNames="MovieID">
<Columns>
<asp:BoundField DataField="MovieID"
HeaderText="Movie ID"/>
<asp:BoundField DataField="MovieTitle"
HeaderText="Movie"/>
<asp:BoundField DataField="DateChecked"
HeaderText="Date Checked"/>
<asp:BoundField DataField="CheckedOut"
HeaderText="Checked Out"/>
</Columns>
</asp:GridView>
<asp:Button runat="server" Text="Choose another Movie" OnClick="GoBack" />
<asp:Button runat="server" Text="Check Out" OnClick="CheckOut" />
</asp:Panel>
CS code for checking out the movie:
public void CheckOut(object sender, EventArgs e)
{
get_connection();
try
{
connection.Open();
command = new SqlCommand("UPDATE Content SET DateChecked=#DateChecked, CheckedOut=#CheckedOut WHERE MovieID=#MovieID", connection);
command.Parameters.AddWithValue("#DateChecked", DateTime.Now);
command.Parameters.AddWithValue("#CheckedOut", 'Y');
//command.Parameters.AddWithValue("#MovieID",);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
reader = command.ExecuteReader();
one_data.DataSource = reader;
one_data.DataBind();
reader.Close();
command = new SqlCommand("INSERT INTO checkout (MovieID, SubscriberID) VALUES #MovieID, #SubscriberID", connection);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
command.Parameters.AddWithValue("#SubscriberID", loginName.Text);
command.ExecuteNonQuery();
}
catch (Exception err)
{
// Handle an error by displaying the information.
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally
{
connection.Close();
lblInfo.Text = "Movie Checked Out";
}
}
The UPDATE SQL statement does work saying the movie has been taken but the movie does not get added to the checked out table.
I see some missing concept.
why update use command.ExecuteReader(); while insert use command.ExecuteNonQuery(); .
I think you should use
ExecuteNonQuery
INSERT INTO checkout (MovieID, SubscriberID) VALUES #MovieID, #SubscriberID .
This sql syntax need bracket for values :
INSERT INTO checkout (MovieID, SubscriberID) VALUES (#MovieID, #SubscriberID)
I hope this solve yours.
I think you better execute coding in the transaction block. also you can update as following examlpe with ";"
connection.ConnectionString = connectionString;
command.CommandText = #"
UPDATE MultiStatementTest SET somevalue = somevalue + 1;
UPDATE MultiStatementTest SET" + (generateError ? "WONTWORK" : "") +
" somevalue = somevalue + 2;";
command.CommandType = System.Data.CommandType.Text;
command.Connection = connection;
Can I execute multiple SQL statements?
Of course you can! You can execute it in a single or multiple SqlCommand. :)
The UPDATE SQL statement does work saying the movie has been taken but
the movie does not get added to the checked out table
Are you using a local database? If yes, check out Data not saving permanently to SQL table.
Anyway, I would like to my code for data access which could help you in your development.
Disclaimer: I know that using SqlCommand as parameter is better but I got lazy so here's the string version.
public interface IDAL
{
void BeginTransaction();
void EndTransaction();
void SaveChanges();
DataTable RetrieveData(string query, [CallerMemberName] string callerMemberName = "");
string RetrieveString(string query, [CallerMemberName] string callerMemberName = "");
bool ExecuteNonQuery(string query, [CallerMemberName] string callerMemberName = "");
bool ExecuteNonQuery(string query, object[] parameters, [CallerMemberName] string callerMemberName = "");
}
public class MSSQLDAL : IDAL, IDisposable
{
private bool disposed = false;
private string _connectionString { get; set; }
private SqlTransaction _transaction { get; set; }
private SqlConnection _connection { get; set; }
private IsolationLevel _isolationLevel { get; set; }
private bool _isCommitted { get; set; }
public string ConnectionString
{
get { return _connectionString; }
}
public MSSQLDAL(string connectionString)
{
this.connectionString = _connectionString;
this._connection = new SqlConnection();
this._connection.ConnectionString = this._connectionString;
this._isolationLevel = IsolationLevel.ReadCommitted;
this._isCommitted = false;
}
public void BeginTransaction()
{
this.Open();
}
public void EndTransaction()
{
this.Close();
}
public void SaveChanges()
{
if(_transaction != null)
{
_transaction.Commit();
this._isCommitted = true;
}
this.EndTransaction();
}
public DataTable RetrieveData(string query, [CallerMemberName] string callerMemberName = "")
{
DataTable dataTable = new DataTable();
try
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = _connection;
command.Transaction = _transaction;
command.CommandText = query;
command.CommandType = CommandType.Text;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.Fill(dataTable);
}
}
//this.AuditSQL(query, string.Empty);
}
catch (Exception ex)
{
this.AuditSQL(query, ex.Message, callerMemberName);
}
return dataTable;
}
public string RetrieveString(string query, [CallerMemberName] string callerMemberName = "")
{
string text = string.Empty;
try
{
using (SqlCommand oracleCommand = new SqlCommand())
{
oracleCommand.Connection = _connection;
oracleCommand.Transaction = _transaction;
oracleCommand.CommandText = query;
oracleCommand.CommandType = CommandType.Text;
using (SqlDataReader dataReader = oracleCommand.ExecuteReader())
{
dataReader.Read();
text = dataReader.GetValue(0).ToString();
}
}
//this.AuditSQL(query, string.Empty);
}
catch (Exception ex)
{
this.AuditSQL(query, ex.Message, callerMemberName);
}
return text;
}
public bool ExecuteNonQuery(string query, [CallerMemberName] string callerMemberName = "")
{
bool success = false;
try
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = _connection;
command.Transaction = _transaction;
command.CommandText = query;
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
//this.AuditSQL(query, string.Empty);
success = true;
}
catch (Exception ex)
{
this.AuditSQL(query, ex.Message, callerMemberName);
success = false;
}
return success;
}
public bool ExecuteNonQuery(string query, object[] parameters, [CallerMemberName] string callerMemberName = "")
{
bool success = false;
try
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = _connection;
command.Transaction = _transaction;
command.CommandText = query;
command.CommandType = CommandType.Text;
command.Parameters.AddRange(parameters);
command.ExecuteNonQuery();
}
//this.AuditSQL(query, string.Empty);
success = true;
}
catch (Exception ex)
{
this.AuditSQL(query, ex.Message, callerMemberName);
success = false;
}
return success;
}
private void Open()
{
if(_connection.State == ConnectionState.Closed)
{
_connection.Open();
_transaction = _connection.BeginTransaction(_isolationLevel);
}
}
private void Close()
{
if (!this._isCommitted)
{
if (this._transaction != null)
{
this._transaction.Rollback();
}
}
if(this._connection.State == ConnectionState.Open)
{
this._connection.Close();
}
}
private void AuditSQL(string query, string message, string callerMemberName = "")
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("**************************************************************************************************");
stringBuilder.AppendLine(string.Format("DATETIME: {0}", DateTime.Now.ToString("MM/dd/yyyy HHmmss")));
stringBuilder.AppendLine(string.Format("SQL: {0}", query));
stringBuilder.AppendLine(string.Format("MESSAGE: {0}", message));
if (!string.IsNullOrWhiteSpace(callerMemberName))
{
stringBuilder.AppendLine(string.Format("METHOD: {0}", callerMemberName));
}
stringBuilder.AppendLine("**************************************************************************************************");
Logger.WriteLineSQL(stringBuilder.ToString()); // Log the query result. Add an #if DEBUG so that live version will no longer log.
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (!this._isCommitted)
{
if (this._transaction != null)
{
this._transaction.Rollback();
}
}
this._transaction.Dispose();
this._connection.Dispose();
}
// Free your own state (unmanaged objects).
// Set large fields to null.
// Free other state (managed objects).
this._transaction = null;
this._connection = null;
disposed = true;
}
}
}
Sample usage:
public void CheckOut(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; // Assuming it is in your web.config
try
{
using(MSSQLDAL dal = new MSSQLDAL(connectionString))
{
dal.BeginTransaction();
string updateQuery = "UPDATE Content SET DateChecked=#DateChecked, CheckedOut=#CheckedOut WHERE MovieID=#MovieID";
SqlParameter uDateChecked = new SqlParameter("DateChecked", SqlDbType.DateTime);
uDateChecked = DateTime.Now;
SqlParameter uCheckedOut = new SqlParameter("CheckedOut", SqlDbType.VarChar);
uCheckedOut = 'Y';
SqlParameter uMovieID = new SqlParameter("MovieID", SqlDbType.Int);
uMovieID = CheckOutList.SelectedValue;
ICollection<SqlParameter> updateParameters = new List<SqlParameter>();
updateParameters.Add(uDateChecked);
updateParameters.Add(uCheckedOut);
updateParameters.Add(uMovieID);
bool updateSuccessful = dal.ExecuteNonQuery(updateQuery, updateParameters.ToArray());
string insertQuery = "INSERT INTO checkout (MovieID, SubscriberID) VALUES (#MovieID, #SubscriberID)";
SqlParameter iSubscriberID = new SqlParameter("SubscriberID", SqlDbType.VarChar);
iSubscriberID = loginName.Text;
SqlParameter iMovieID = new SqlParameter("MovieID", SqlDbType.Int);
iMovieID = CheckOutList.SelectedValue;
ICollection<SqlParameter> insertParameters = new List<SqlParameter>();
insertParameters.Add(iSubscriberID);
insertParameters.Add(iMovieID);
bool insertSuccessful = dal.ExecuteNonQuery(insertQuery, insertParameters.ToArray());
if(updateSuccessful && insertSuccessful)
{
dal.SaveChanges();
lblInfo.Text = "Movie Checked Out";
}
else
{
lblInfo.Text = "Something is wrong with your query!";
}
}
}
catch(Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Error reading the database.");
sb.AppendLine(ex.Message);
if(ex.InnerException != null)
sb.AppendLine(ex.InnerException.Message);
lblInfo.Text = sb.ToString();
}
}
How can I execute multiple SQL statements in a single command?
You simply need to encapsulate your queries with a BEGIN and END;.
Ex:
BEGIN
SELECT 'A';
SELECT * FROM TableA;
END;
Take note that you need to have ; after your statements. I'd use a StringBuilder to write my long queries if I were you. Also, sending multiple queries as one is only useful if you are not reading any data.
What's the IDAL interface for?
In some of my projects I had to work with different databases. Using the same interface, I am able to create a DAL class for Oracle, MSSql and MySql with very minimal code change. It is also the OOP way. :)
Please change the code like this and try.change the reader.close() after executenonquery().
try
{
connection.Open();
command = new SqlCommand("UPDATE Content SET DateChecked=#DateChecked, CheckedOut=#CheckedOut WHERE MovieID=#MovieID", connection);
command.Parameters.AddWithValue("#DateChecked", DateTime.Now);
command.Parameters.AddWithValue("#CheckedOut", 'Y');
//command.Parameters.AddWithValue("#MovieID",);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
reader = command.ExecuteReader();
one_data.DataSource = reader;
one_data.DataBind();
command = new SqlCommand("INSERT INTO checkout (MovieID, SubscriberID) VALUES #MovieID, #SubscriberID", connection);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
command.Parameters.AddWithValue("#SubscriberID", loginName.Text);
command.ExecuteNonQuery();
reader.Close();
}
I finally found an answer after reading all the posts and found that this actually got my INSERT to work
try
{
connection.Open();
command = new SqlCommand("UPDATE Content SET DateChecked=#DateChecked, CheckedOut=#CheckedOut WHERE MovieID=#MovieID", connection);
command.Parameters.AddWithValue("#DateChecked", DateTime.Now);
command.Parameters.AddWithValue("#CheckedOut", 'Y');
//command.Parameters.AddWithValue("#MovieID",);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
//reader = command.ExecuteReader();
command.ExecuteNonQuery();
one_data.DataSource = reader;
one_data.DataBind();
connection.Close();
connection.Open();
command = new SqlCommand("INSERT INTO checkout (MovieID, SubscriberID) VALUES (#MovieID, #SubscriberID)", connection);
command.Parameters.AddWithValue("#MovieID", CheckOutList.SelectedValue);
command.Parameters.AddWithValue("#SubscriberID", loginName.Text);
command.ExecuteNonQuery();
//reader.Close();
}
First of all: I got my code running without using oop. I declared all my variables inside the same class and opened/closed the connection right before and after passing the query to the db. That worked! Now with some new experiences I tried to split my code into different classes. Now it wont work anymore.
It tells me "Connection must be valid and open". Enough text, here's my current code:
Services.cs
public static MySqlConnection conn // Returns the connection itself
{
get
{
MySqlConnection conn = new MySqlConnection(Services.ServerConnection);
return conn;
}
}
public static string ServerConnection // Returns the connectin-string
{
get
{
return String.Format("Server={0};Port=XXXX;Database=xxx;Uid=xxx;password=xxXxxXxXxxXxxXX;", key);
}
}
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
LoginForm.cs
private void checkUser(string username, string password)
{
using (Services.conn)
{
Services.conn.Open();
Services.DB_Select("..a short select statement..");
Services.conn.Close();
}
I guess this is all we need. I have shortened my code to get a focus on the problem.
I created Services.cs to get a global way to access the db from all forms without copy&pasting the connection info. Now when I reach my LoginForm.cs it throws an error "Connection must be valid and open". I've already debugged my code. It's all time closed. Even when passing conn.Open() it stays closed. Why?
Another try: I've also tried placing conn.Open() and conn.Close() inside Services.DB_Select(..) at the beginning and end. Same error here.
I have to say: The code worked before and I've used the same connection-string. So the string itself is surely valid.
I appreciate any help given here!
The problem is that you don't store the connection that was returned from your factory property. But don't use a property like a method. Instead use it in this way:
using (var con = Services.conn)
{
Services.conn.Open();
Services.DB_Select("..a short select statement..", con ));
//Services.conn.Close(); unnecessary with using
}
So use the same connection in the using that was returned from the property(or better created in the using) and pass it to the method which uses it. By the way, using a property as factory method is not best practise.
But in my opinion it's much better to create the connection where you use it, best place is in the using statement. And throw the con property to the garbage can, it is pointless and a source for nasty errors.
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
using(var conn = new MySqlConnection(Services.ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = s;
using( var sqlreader = cmd.ExecuteReader())
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
} // unnecessary to close the connection
} // or the reader with the using-stetement
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
Try to restructure your Services class as follows
public static MySqlConnection conn // Returns the connection itself
{
get
{
MySqlConnection conn = new MySqlConnection(Services.ServerConnection);
return conn;
}
}
private static string ServerConnection // Returns the connectin-string - PRIVATE [Improved security]
{
get
{
return String.Format("Server={0};Port=XXXX;Database=xxx;Uid=xxx;password=xxXxxXxXxxXxxXX;", key);
}
}
// Rather than executing result here, return the result to LoginForm - Future improvement
public static void DB_Select(MySqlConnection conn ,string s, params List<string>[] lists)
{
try
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
In LoginForm.cs use returning connection and store it there. When you need to execute query, use
MySqlConnection conn=Services.conn(); // Get a new connection
Services.DB_Select(conn,"..a short select statement.."); // Executing requirement
Services.conn.Close();
Additional - I suggest you need to return MySqlDataReader to LoginForm and handle results there
private MySqlConnection _conn;
public MySqlConnection conn // Returns the connection itself
{
get
{
if(_conn == null)
_conn = new MySqlConnection(Services.ServerConnection);
return _conn;
}
}
I have a problem with my SQL datareader, i want to make an external class and make the code in my xaml.cs as short as possible, because there are a lot of sqldatareaders needed in my program. for this I want to pass following two strings to the datareader class:
public void refreshcombobox()
{
cbGebruiker.Items.Clear();
database = new DataBase();
string sqlrdr = "(rdr.GetString(1).ToString().Trim())";
List<string> reader = database.ReaderRdr("Select * from Gebruikers", ref sqlrdr);
foreach (String str in reader)
{
cbGebruiker.Items.Add(str);
}
}
however, when I do this this is the result in my program instead of the actual results that are stored in the database:
http://i58.tinypic.com/301j2vo.jpg (I can't post images)
can somebody help me with this? I've searched everywhere...
I don't know how to pass the rdr.GetString(1).ToString().Trim() to make it actually look stuff up in the db. Instead of just copying the string directly into the list.
This is the class:
namespace ClassLib
{
public class DataBase
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["kassadatabase"].ConnectionString);
public object ScalarObject(string sql)
{
object value = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
value = cmd.ExecuteScalar();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
return value;
}
public List<string> ReaderRdr(string sql)
{
SqlDataReader rdr = null;
List<string> reader = new List<string>();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//reader.Add(rdr.GetString(1).ToString().Trim());
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (rdr != null) rdr.Close();
if (conn != null) conn.Close();
}
return reader;
}
//public List<string> ReaderRdr(string sql, ref string str)
//{
// SqlDataReader rdr = null;
// List<string> reader = new List<string>();
// try
// {
// conn.Open();
// SqlCommand cmd = new SqlCommand(sql, conn);
// rdr = cmd.ExecuteReader();
// while (rdr.Read())
// {
// //MessageBox.Show(str.ToString());
// //var strRdr = str;
// //MessageBox.Show(strRdr.ToString());
// //reader.Add(rdr.GetString(1).ToString().Trim());
// reader.Add(str);
// Console.WriteLine(String.Format("{0}", rdr[0]));
// }
// }
// catch (SqlException ex)
// {
// MessageBox.Show(ex.Message);
// }
// finally
// {
// if (rdr != null) rdr.Close();
// if (conn != null) conn.Close();
// }
// return reader;
//}
public void ExecuteNQuery(string insertString)
{
try
{
conn.Open();
SqlCommand cmd2 = new SqlCommand(insertString, conn);
cmd2.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
}
}
public List<string> ReaderRdr(string sql)
{
SqlDataReader rdr = null;
List<string> reader = new List<string>();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//reader.Add(rdr.GetString(1).ToString().Trim());
}
.....
now in the methode public list i want to replace the //reader.Add(rdr.GetString(1).ToString().Trim()); part(wich works fine)
with a string that is passed to the method.
public List<string> ReaderRdr(string sql, string strRdr)
{
SqlDataReader rdr = null;
List<string> reader = new List<string>();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//reader.Add(strRdr);
}
I'm not 100% sure what you're trying to do, but I can tell you right now that this is what you're doing wrong - the string (str) you're passing to ReaderRdr is just a string literal of C# code. There's super hacky (super inadvisable) things you can do to mimic what exists in other languages as eval(), but there's no built-in way to do that in C#. Nothing (sensible) you do to "(rdr.GetString(1).ToString().Trim())" is ever going to get a string, or cast it to string, or trim anything.
Within your ReaderRdr function, all you're accomplishing is just to add the string str to your List<string> reader. This accomplishes nothing and has no bearing whatsoever on the results you get from your database query in your SqlDataReader rdr. If you want to store the data you actually get from your database, use rdr, not the (useless) string argument str.
Also, I feel like you must have left something out of your code - you're instantiating your SqlCommand cmd with conn as your second argument, but I don't see that defined anywhere within your ReaderRdr method, and it's not an argument passed to ReaderRdr. You don't have an SqlConnection object as a field or property within your class, do you?
As far as what you should maybe do, despite lacking much of any context in terms of your actual aims - if you want to get any given column of the result for each row returned by your SqlDataReader:
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
var yourDataCell = rdr[yourColumnIndex];
// or:
var yourDataCellOtherWay = rdr["YourColumnName"];
}
Alternately, you can just iterate through each of the cells in any given row produced by your SqlDataReader like so:
for(int i = 0 ; i < numberOfColumns; i++) {
// do something with rdr[i] here
}
I'm not sure if there's anything you can do establish numberOfColumns based on the state of your SqlDataReader, but others might know better.
You actually adding the String that you passed to a function to your reader reader.Add(str); You get the response from SQL I your rdr.
This item will show you something from your database:
Console.WriteLine(String.Format("{0}", rdr[0]));
I have a DataClassLibrary attached to my ASP.Net project. I use it to access the database to get my values. I want to take the values given in the Line1 class and put them in the corresponding label. I tried DataLibraryClass.Line1 NewDataA = new DataLibraryClass.Line1(); but it gives me a zero I know that they have values. Could it be that my NewDataA = new is causing it to return zero? I also used breakpoints in the Line1 class and it never reaches the database query. How can I get the data I need into the labels properly?
DataLibraryClass
Line1:
var sqlString = new StringBuilder();
sqlString.Append("SELECT CaseNum6, CaseNum9, Group, Completion ");
sqlString.Append("FROM WorkOrder ");
sqlString.Append("WHERE Group = 1 OR Group = 2 ");
sqlString.Append("AND Completion = 0 ");
SqlDataReader reader = null;
SqlConnection dbConn = DBHelper.getConnection();
SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("#CaseNum6", CaseNum6 )};
try
{
reader = DBHelper.executeQuery(dbConn, sqlString.ToString(), parameters);
if (reader != null)
{
if (reader.Read())
{
CaseNum6 = (int)reader["CaseNum6"];
CaseNum9 = (int)reader["CaseNum9"];
Group = (int)reader["Group"];
Completion = (bool)reader["Completion"];
}
else
throw new Exception("No record returned");
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
DataLibraryClass
DBHelper:
private DBHelper() { }
public static SqlConnection getConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
}
public static SqlConnection getFRESHConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["FRESHConnection"].ConnectionString);
}
public static SqlDataReader executeQuery(SqlConnection dbConn, string sqlString, SqlParameter[] parameters)
{
SqlCommand cmd = null;
SqlDataReader reader = null;
try
{
if (dbConn.State == ConnectionState.Closed)
dbConn.Open();
cmd = dbConn.CreateCommand();
cmd.CommandText = sqlString;
if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}
reader = cmd.ExecuteReader();
cmd.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return reader;
Code behind ASP page:
DataClassLibrary.LineAData NewDataA = new DataClassLibrary.LineAData();
DataClassLibrary.LineBData NewDataB = new DataClassLibrary.LineBData();
protected void Page_Load(object sender, EventArgs e)
{
L1.Text = NewDataA.CaseNum6.ToString();
L2.Text = NewDataA.CaseNum9.ToString();
L4.Text = NewDataB.CaseNum6.ToString();
L5.Text = NewDataB.CaseGNum9.ToString();
}
Upon setting up the webpage I failed to realize the behind code was set to .vb not .cs which is why everything was not working.