Return string not matching textbox text - c#

I have bit of code in my program that will not let and operator start another batch until they finish the one that they are on but still allows another operator to start the same batch. The sqldatareader is returning the correct data i.e. 17080387-002 but the program keeps going to the "Please finish batch" step. I'm trying to figure out if it possibly has anything to do with how the batch is being returned.
public void BatchLockOut()
{
string eventID = null;
string batchLock = null;
string enteredLot = TextBoxLot.Text;
string connectionString = "";
string commandText = "SELECT BadgeNo, Container_ID, Event_ID, Event_Time " +
"FROM dbo.Custom_EventLog " +
"WHERE Event_Time IN (SELECT MAX(Event_Time) FROM dbo.Custom_EventLog WHERE BadgeNo = #BADGENO)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#BADGENO", SqlDbType.NChar, 10).Value = TextBoxLogin.Text;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
eventID = Convert.ToInt32(reader["Event_ID"]).ToString();
batchLock = reader["Container_ID"] as string;
break;
}
}
connection.Close();
}
if (batchLock == null)
{
ButtonBeginStir.IsEnabled = true;
}
else if (batchLock != enteredLot)
{
if (eventID == "1")
{
MessageBox.Show("Please finish previous stir", "Finish Stir", MessageBoxButton.OK, MessageBoxImage.Information);
ClearForm();
}
else
{
ButtonBeginStir.IsEnabled = true;
}
}
else if (batchLock == enteredLot)
{
if (eventID == "1")
{
ButtonEndStir.IsEnabled = true;
}
else if (eventID == "2")
{
ButtonBeginStir.IsEnabled = true;
}
}
}

Related

How can this database connection class be improved? (ADO.NET)

I am attempting to create a database access layer. I am looking for some improvements to this class/recommendations on best practice. It would be helpful if someone could point me to documentation on how this could be potentially done/things to consider. I have looked at using entity framework but it does not seem applicable, however, should I really be looking to move to EF? Is ADO.NET an outdated way of doing this?
public static IDbCommand GetCommandObject(string Connstring)
{
IDbConnection conn = new SqlConnection(Connstring);
return new SqlCommand { Connection = (SqlConnection)conn };
}
public static void AddParameter(ref IDbCommand cmd, string Name, object value, DbType ParamType)
{
IDbDataParameter Param = cmd.CreateParameter();
Param.DbType = ParamType;
Param.ParameterName = (Name.StartsWith("#")) ? "" : "#"; //# character for MS SQL database
Param.Value = value;
cmd.Parameters.Add(Param);
}
public static Int32 ExecuteNonQuery(string SQL, IDbCommand cmd = null)
{
Boolean CommitTrans = true;
Boolean CloseConn = true;
SqlTransaction Trans = null;
try
{
//IF Required - create command object if required
if (cmd == null) { cmd = DB.GetCommandObject(""); }
//Add the commandtext
cmd.CommandText = SQL;
if (cmd.Connection == null) { throw new Exception("No connection set"); }
//IF REQUIRED - open the connection
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
else
{
CloseConn = false;
}
if (cmd.Transaction != null)
{
//We have already been passed a Transaction so dont close it
CommitTrans = false;
}
else
{
//Create and open a new transaction
Trans = (SqlTransaction)cmd.Connection.BeginTransaction();
cmd.Transaction = Trans;
}
Int32 rtn = cmd.ExecuteNonQuery();
if (CommitTrans == true) { Trans.Commit(); }
return rtn;
}
catch (Exception e)
{
if (CommitTrans == true) { Trans.Rollback(); }
throw new Exception();
}
finally
{
if (CloseConn == true)
{
cmd.Connection.Close();
cmd = null;
}
}
}
public static object ExecuteScalar(string SQL, IDbCommand cmd, Boolean NeedsTransaction = true)
{
Boolean CommitTrans = true;
Boolean CloseConn = true;
SqlTransaction Trans = null;
try
{
//IF Required - create command object if required
if (cmd == null) { cmd = DB.GetCommandObject(""); }
//Add the commandtext
cmd.CommandText = SQL;
//IF REQUIRED - create default Connection to CourseBuilder DB
if (cmd.Connection == null) { throw new Exception("No Connection Object"); }
//IF REQUIRED - open the connection
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
else
{
CloseConn = false;
}
if (NeedsTransaction == true)
{
if (cmd.Transaction != null)
{
//We have already been passed a Transaction so dont close it
CommitTrans = false;
}
else
{
//Create and open a new transaction
Trans = (SqlTransaction)cmd.Connection.BeginTransaction();
cmd.Transaction = Trans;
}
}
Object rtn = cmd.ExecuteScalar();
if (NeedsTransaction == true && CommitTrans == true) { Trans.Commit(); }
return rtn;
}
catch
{
if (NeedsTransaction == true && Trans != null) { Trans.Rollback(); }
throw new Exception();
}
finally
{
if (CloseConn == true) { cmd.Connection.Close(); cmd = null; }
}
}
public static DataRow GetDataRow(string SQL, IDbCommand cmd = null, Boolean ErrorOnEmpty = true)
{
var dt = FillDatatable(SQL, ref cmd);
if (dt.Rows.Count > 0)
{
return dt.Rows[0];
}
else
{
if (ErrorOnEmpty == true) { throw new Exception(nameof(GetDataRow) + " returned no rows."); }
return null;
}
}
public static DataTable FillDatatable(string SQL, ref IDbCommand cmd)
{
string newline = System.Environment.NewLine;
var DT = new DataTable();
Boolean LeaveConOpen = false;
try
{
//Add the commandtext
cmd.CommandText = SQL;
//IF REQUIRED - create default Connection to CourseBuilder DB
if (cmd?.Connection == null) { throw new Exception("No Connection Object"); }
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
LeaveConOpen = false;
}
else
{
LeaveConOpen = true;
}
var DA = new SqlDataAdapter((SqlCommand)cmd);
DA.Fill(DT);
}
catch (Exception ex)
{
var sbErr = new StringBuilder();
sbErr.AppendLine("Parameters (type defaults to varchar(max)):" + newline);
foreach (SqlParameter p in cmd.Parameters)
{
string s = "";
sbErr.AppendLine("declare " + p.ParameterName + " varchar(max) = '" + (p.Value == DBNull.Value ? "Null" : p.Value + "'; ") + newline);
}
sbErr.AppendLine(newline + SQL + newline);
throw new Exception("Failed to FillDataTable:" + newline + newline + sbErr.ToString(), ex);
}
finally
{
if (LeaveConOpen == false) { cmd.Connection.Close(); }
}
return DT;
}
public static T CheckNull<T>(T value, T DefaultValue)
{
if (value == null || value is System.DBNull)
{
return DefaultValue;
}
else
{
return value;
}
}
Couple of things to keep in mind when you are creating a DAL
DAL should be able to cater to multiple Databases (oracle , sql , mysql etc..)
You should have minimum of DB , Connection , Command and Reader implementations of each.
Do not worry about the connection pool
Be aware of the transaction scope , Especially when you are trying to save nested objects. (For Eg: by saving company, you are saving Company and Company.Employees and Employee.Phones in a single transaction)
Alternative is to use something like Dapper.
enter image description here

code asp.net c# oledb, cookies, if else

Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.

OleDbDataReader = null

I'm currently building a program which stores messages between users in a database and returns these messages to the user when the button below gets pressed. I'm using a SQL CE database using a OleDbConnection and using a DataReader.
private void button3_Click(object sender, EventArgs e)
{
string [] lec_name = new string [10] ;
string [] content = new string [10] ;
string conn = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\\Users\\Leon\\Admin.sdf";
OleDbConnection connection = new OleDbConnection(conn);
OleDbCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Contact_DB WHERE Student_ID =" + iD + " AND Direction = '" + "To the student" + "'";
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("" + ex.Message);
}
OleDbDataReader reader = command.ExecuteReader();
int up = 0;
int count = 0;
while (reader.Read())
{
lec_name[up] = reader["Lecturer_Name"].ToString();
content[up] = reader["Description"].ToString();
up++;
MessageBox.Show("The lecturer " + lec_name[count] + " has messaged you saying :" + "\n" + content[count]);
count++;
}
}
This code works for my Student class but when I reuse the code with minor changes within the Lecturer class the OledbDataReader says null, anyone know why?
Btw the values being returned aren't null the reader itself is null.
Below is the non working code.
private void button2_Click(object sender, EventArgs e)
{
string [] studentID = new string [10] ;
string [] content = new string [10] ;
string conn = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\\Users\\Leon\\Admin.sdf";
OleDbConnection connection = new OleDbConnection(conn);
OleDbCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Contact_DB WHERE Lecturer_Name =" + full + " AND Direction = '" + "To the lecturer" + "'";
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("" + ex.Message);
}
OleDbDataReader reader1 = command.ExecuteReader();
int up = 0;
int count = 0;
while (reader1.Read())
{
studentID[up] = reader1["Student_ID"].ToString();
content[up] = reader1["Description"].ToString();
up++;
}
MessageBox.Show("The student " + studentID[count] + " has messaged you saying :" + "\n" +content[count]);
}
}
Using Reflector:
OleDbCommand.ExcuteReader:
public OleDbDataReader ExecuteReader(CommandBehavior behavior)
{
OleDbDataReader reader;
IntPtr ptr;
OleDbConnection.ExecutePermission.Demand();
Bid.ScopeEnter(out ptr, "<oledb.OleDbCommand.ExecuteReader|API> %d#, behavior=%d{ds.CommandBehavior}\n", this.ObjectID, (int) behavior);
try
{
this._executeQuery = true;
reader = this.ExecuteReaderInternal(behavior, "ExecuteReader");
}
finally
{
Bid.ScopeLeave(ref ptr);
}
return reader;
}
The CommandBehavior is
default.the reader returned by this.ExecuteReaderInternal()---- >
private OleDbDataReader ExecuteReaderInternal(CommandBehavior behavior, string method)
{
OleDbDataReader dataReader = null;
OleDbException previous = null;
int num2 = 0;
try
{
object obj2;
int num;
this.ValidateConnectionAndTransaction(method);
if ((CommandBehavior.SingleRow & behavior) != CommandBehavior.Default) behavior |= CommandBehavior.SingleResult;
switch (this.CommandType)
{
case ((CommandType) 0):
case CommandType.Text:
case CommandType.StoredProcedure:
num = this.ExecuteCommand(behavior, out obj2);
break;
case CommandType.TableDirect:
num = this.ExecuteTableDirect(behavior, out obj2);
break;
default:
throw ADP.InvalidCommandType(this.CommandType);
}
if (this._executeQuery)
{
try
{
dataReader = new OleDbDataReader(this._connection, this, 0, this.commandBehavior);
switch (num)
{
case 0:
dataReader.InitializeIMultipleResults(obj2);
dataReader.NextResult();
break;
case 1:
dataReader.InitializeIRowset(obj2, ChapterHandle.DB_NULL_HCHAPTER, this._recordsAffected);
dataReader.BuildMetaInfo();
dataReader.HasRowsRead();
break;
case 2:
dataReader.InitializeIRow(obj2, this._recordsAffected);
dataReader.BuildMetaInfo();
break;
case 3:
if (!this._isPrepared) this.PrepareCommandText(2);
OleDbDataReader.GenerateSchemaTable(dataReader, this._icommandText, behavior);
break;
}
obj2 = null;
this._hasDataReader = true;
this._connection.AddWeakReference(dataReader, 2);
num2 = 1;
return dataReader;
}
finally
{
if (1 != num2)
{
this.canceling = true;
if (dataReader != null)
{
dataReader.Dispose();
dataReader = null;
}
}
}
}
try
{
if (num == 0)
{
UnsafeNativeMethods.IMultipleResults imultipleResults = (UnsafeNativeMethods.IMultipleResults) obj2;
previous = OleDbDataReader.NextResults(imultipleResults, this._connection, this, out this._recordsAffected);
}
}
finally
{
try
{
if (obj2 != null)
{
Marshal.ReleaseComObject(obj2);
obj2 = null;
}
this.CloseFromDataReader(this.ParameterBindings);
}
catch (Exception exception3)
{
if (!ADP.IsCatchableExceptionType(exception3)) throw;
if (previous == null) throw;
previous = new OleDbException(previous, exception3);
}
}
}
finally
{
try
{
if (dataReader == null && 1 != num2) this.ParameterCleanup();
}
catch (Exception exception2)
{
if (!ADP.IsCatchableExceptionType(exception2)) throw;
if (previous == null) throw;
previous = new OleDbException(previous, exception2);
}
if (previous != null) throw previous;
}
return dataReader;
}
this._executeQuery wraps the new instance of OleDbDataReader, if it doesn't run the dataReader will be null.
The only way the reader is returned as null is if the internal RunExecuteReader method is passed 'false' for returnStream, which it isn't.
Here is the only place where this._executeQuery is set to false, but this one is not called in parallel because of Bid.ScopeEnter and Bid.ScopeLeave.
public override int ExecuteNonQuery()
{
int num;
IntPtr ptr;
OleDbConnection.ExecutePermission.Demand();
Bid.ScopeEnter(out ptr, "<oledb.OleDbCommand.ExecuteNonQuery|API> %d#\n", this.ObjectID);
try
{
this._executeQuery = false;
this.ExecuteReaderInternal(CommandBehavior.Default, "ExecuteNonQuery");
num = ADP.IntPtrToInt32(this._recordsAffected);
}
finally
{
Bid.ScopeLeave(ref ptr);
}
return num;
}
Theoretically the data reader can be null if the query cannot be executed.
UPDATE:
https://github.com/Microsoft/referencesource/blob/master/System.Data/System/Data/OleDb/OleDbCommand.cs#L658

How to automatically update database value when issue book in library management

I want to make a library system in C#. In this system when a book is issued it should automatically reduce the book quantity in database. When book quantity == 0 there should be a message box showing "not available".
This is my code:
private void btnIssue_Click(object sender, EventArgs e)
{
if (cmbResID.Text != "" && cmbMemID.Text != "" && cmbBookID.Text != "" && txtBkTitle.Text != "" && txtCategory.Text != "" && txtAuthor.Text != "" && txtIssueDate.Text != "" && txtActDate.Text != "")
{
SqlCommand Quantity = new SqlCommand("Select * from tblBookDetails where Book_ID = '" + cmbBookID.Text +"'");
DataSet ds = Library.Select(Quantity);
if (ds.Tables[0].Rows.Count > 0)
{
textBox1.Text = ds.Tables[0].Rows[0].ItemArray.GetValue(5).ToString();
int b = Convert.ToInt32(textBox1.Text);
if (b > 0)
{
//a = a - 1;
//int b = Convert.ToInt32(a);
//label15.Text = a.ToString();
SqlCommand update=new SqlCommand("UPDATE tblBookDetails SET Quantity=Quantity-1 WHERE Book_ID='"+ cmbBookID +"'");
Library.ExecuteInsert(update);
SqlCommand save = new SqlCommand("insert into tblBookIssue values(#ResID,#Member_ID,#Book_ID,#Issue_Date,#Act_Ret_Date)");
save.Parameters.AddWithValue("#ResID", cmbResID.Text);
save.Parameters.AddWithValue("#Member_ID", cmbMemID.Text);
save.Parameters.AddWithValue("#Book_ID", cmbBookID.Text);
save.Parameters.AddWithValue("#Issue_Date", txtIssueDate.Text);
save.Parameters.AddWithValue("#Act_Ret_Date", txtActDate.Text);
Library.Insert(save);
MessageBox.Show("Book Issued", "Book Issue", MessageBoxButtons.OK, MessageBoxIcon.Information);
clear();
}
else
{
MessageBox.Show("this book is not available");
}
}
}
else
{
MessageBox.Show("FILL COLUMS");
}
}
Executing SQL based off of text boxes is very unsafe and Prone to SQL injection attacks. Also, to follow Object Oriented program and make much cleaner code it would be advisable to make a Book object, I completed some code below which shows an example including the book incrementer. It would be better to make focused stored procs which execute gets for books and updates for book checkouts. You will have to turn your basic select into a stored proc, and write another proc which looks at the quantity and if quantity < 1 return 0 else return 1. Let me know if you need more info, this code should help you get rolling
using System;
using System.Data;
using System.Data.SqlClient;
namespace MockLibrary
{
internal class Book
{
#region Constructors
public Book()
{
}
public Book(string resId, string memberId, string bookId, DateTime issueDate, DateTime actRetDate)
{
this.ResId = resId;
this.MemberId = memberId;
this.BookId = bookId;
this.IssueDate = issueDate;
this.ActRetDate = actRetDate;
}
#endregion
#region Properties
private string _ResID;
private string _MemberID;
private string _BookId;
private DateTime _IssueDate;
private DateTime _ActRetDate;
public string ResId
{
get { return _ResID; }
set { _ResID = value; }
}
public string MemberId
{
get { return _MemberID; }
set { _MemberID = value; }
}
public string BookId
{
get { return _BookId; }
set { _BookId = value; }
}
public DateTime IssueDate
{
get { return _IssueDate; }
set { _IssueDate = value; }
}
public DateTime ActRetDate
{
get { return _ActRetDate; }
set { _ActRetDate = value; }
}
#endregion
public Book GetBookByID(string resId, string memberId)
{
try
{
using (SqlConnection con = new SqlConnection("put your db con string here"))
{
using (SqlCommand cmd = new SqlCommand("sp_GetBookById", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ResId", SqlDbType.VarChar).Value = resId;
cmd.Parameters.Add("#MemberId", SqlDbType.VarChar).Value = memberId;
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Book newBook = new Book(rdr["ResId"].ToString(),rdr["MemberId"].ToString(),rdr["BookId"].ToString(),DateTime.Now,DateTime.Now);
return newBook;
}
}
}
}
catch
{
throw new Exception("something went wrong");
}
return null;
}
public bool CheckoutBook(string resId, string memberId)
{
using (SqlConnection con = new SqlConnection("put your db con string here"))
{
using (SqlCommand cmd = new SqlCommand("sp_CheckoutBook", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ResId", SqlDbType.VarChar).Value = resId;
cmd.Parameters.Add("#MemberId", SqlDbType.VarChar).Value = memberId;
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (rdr["checkoutsuccessful"].ToString() == "1")
{
return true;
}
}
}
}
return false;
}
}
}
when user returns a book:-
MySqlCommand cm1;
cm1 = new MySqlCommand("update addbook set bookquantity=bookquantity+1 where bookname='" + txt_bookname.Text + "'",con);
cm1.ExecuteNonQuery();

Is it possible to use ExecuteReader() twice?

I'm programming a database manager for a gameserver called OTServer, and I'm having problems using executereader() the second time. Here's code:
private void button1_Click(object sender, EventArgs e)
{
Form1 f = new Form1();
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=" + f.GetText1().Text + ";Username=" + f.GetText2().Text + ";Pwd=" + f.GetText3().Text + ";Database=" + f.GetText4().Text + ";";
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM `players` WHERE name = #Name", conn);
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
MySqlDataReader Reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
while (Reader.Read())
{
label7.Text = (string)Reader[1];
label7.Show();
label8.Text = Reader[5].ToString();
label8.Show();
if ((int)Reader[6] == 1)
{
label9.Text = "Sorcerer (1)";
}
if ((int)Reader[6] == 2)
{
label9.Text = "Druid (2)";
}
if ((int)Reader[6] == 3)
{
label9.Text = "Paladin (3)";
}
if ((int)Reader[6] == 4)
{
label9.Text = "Knight (4)";
}
if ((int)Reader[6] == 0)
{
label9.Text = "None (0)";
}
label9.Show();
if ((int)Reader[3] == 1)
{
label10.Text = "Player";
}
if ((int)Reader[3] == 2)
{
label10.Text = "Tutor";
}
if ((int)Reader[3] == 3)
{
label10.Text = "Senior Tutor";
}
if ((int)Reader[3] == 4)
{
label10.Text = "Gamemaster";
}
if ((int)Reader[3] == 5)
{
label10.Text = "Community Manager";
}
if ((int)Reader[3] == 6)
{
label10.Text = "God";
}
if ((int)Reader[3] < 1 || (int)Reader[3] > 6)
{
label10.Text = "Unknown";
}
label10.Show();
label13.Text = "Account: " + Reader[4].ToString();
label13.Show();
}
Reader.Close();
cmd = new MySqlCommand("SELECT * FROM accounts WHERE id = #Account_ID", conn);
cmd.Parameters.AddWithValue("#Account_ID", label13.Text);
Reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
while (Reader.Read())
{
label11.Text = (string)Reader[0];
label11.Show();
}
Reader.Close();
}
Suggested solution: Try putting a using block around your DataReader, or call Dispose on it:
using (DataReader Reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
// ...do something with your data reader... then finish by:
Reader.Close();
} // <-- Reader.Dispose() called automatically at the end of using block.
// ...prepare second command...
// the same again for the second command:
using (DataReader Reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
// ...
Reader.Close();
}
Assumed cause of your problem: The DB connection object may do some internal book-keeping to keep track of data readers. I've found out in a similar scenario that you're only allowed one DataReader at a time. So I believe the problem with your code is that, while you Close the Reader, you haven't explicitly Disposed it, so the connection object thinks the first data reader is still in use when you execute the second one.
Besides... why not simplify this code:
if ((int)Reader[6] == 1)
{
label9.Text = "Sorcerer (1)";
}
if ((int)Reader[6] == 2)
{
label9.Text = "Druid (2)";
}
...
to a switch statement?:
int x = (int)(Reader[6]);
string label9Text = string.Empty;
switch (x)
{
case 1: label9Text = "Sorcerer (1)"; break;
case 2: label9Text = "Druid (2)"; break;
...
}
label9.Text = label9Text;
(That would save you quite a bit of repetitive typing.)
Well, assuming that your code is correct you shouldn't have problem in executing two readers as you show in your code. Maybe you have problems because of not disposing commands or something else. I recommend an approach like this (Example made with Northwind db):
using (SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM Orders", connection))
{
using (SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SingleRow))
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(2));
}
}
}
using (SqlCommand command = new SqlCommand("SELECT * FROM Products", connection))
{
using (SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SingleRow))
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(1));
}
}
}
}
You should clean your code when recognizing the type of player. Create an enum instead:
public enum PlayerType
{
None = 0,
Sorcerer = 1,
Druid = 2,
Paladin = 3
}
And then do the following while reading:
PlayerType playerType = (PlayerType)reader.GetInt32(6);
label9.Text = playerType.ToString();

Categories

Resources