Image.MemoryStream : Parameter not valid - c#

When I'm trying to retrieve my image by combo box there show the massage . Parameter not valid
I was try many way but problem is same ..
Every time I run the code below, I get same massage.
private void cBoxSearch_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con = ConnectionController.GetInstance().GetConnection();
con.Open();
com = new SQLiteCommand("SELECT * FROM Stock WHERE ProductName = '" + cBoxSearch.Text + "' ", con);
myReader = com.ExecuteReader();
product prod = new product();
while (myReader.Read())
{
prod.proid = myReader[0].ToString();
prod.prodname = myReader[1].ToString();
prod.proMdl = myReader[2].ToString();
prod.serialN = myReader[3].ToString();
prod.byibgPr = myReader[4].ToString();
prod.sellPr = myReader[5].ToString();
prod.quantity = myReader[6].ToString();
tbxProductID.Text = prod.proid;
tbxName.Text =prod.prodname;
tbxModel.Text = prod.proMdl;
tbxserial.Text = prod.serialN;
tbxbyingprice.Text = prod.byibgPr;
tbxSellingprice.Text = prod.sellPr;
tbxQuantity.Text = prod.quantity;
prod.imgg = (byte[])(myReader[7] );
if (prod.imgg == null)
{
pBX.Image = null;
}
else
{
MemoryStream mstrm = new MemoryStream(prod.imgg);
Bitmap bmp = new Bitmap(mstrm);
}
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
com.Cancel();
con.Close();
}

Try to consult this question:
convert binary to bitmap using memory stream
Also, it might depend on DBType of the 8th column of the query.

Related

selecting all photographs from sql database

I want to export all photographs from our database into a data table. I will then loop through the table and save each image to disk. There are approx 7000 photos.
When I start the process I can retrieve around 4000 photographs before I start to get error messages like, Exception of type 'System.OutOfMemoryException' was thrown.
If I change the SQL query to retrieve half as many photographs, say 3500 then the process completes successfully.
While I have now achieved what I wanted by modifying the SQL each time I run the code, I would like to improve my code so that all 7000 photographs are returned. Could somebody please advise on a better process.
Here is my method
public static DataTable GetAllPhotos()
{
DataTable dt = new DataTable();
dt.Columns.Add("personId", typeof(string));
dt.Columns.Add("Photo", typeof(Bitmap));
string SQL = "";
byte[] getImg = new byte[0];
byte[] BitmapImg = new byte[0];
string personId = "";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = _connString;
SQL = #"select per.person_id,pho.photo
from person as per
left join photo as pho on per.photo_id = pho.photo_id
where photo is not null";
conn.Open();
SqlDataReader dr = null;
SqlCommand cmd = new SqlCommand(SQL, conn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
getImg = (byte[])dr["Photo"];
personId = Convert.ToString(dr["person_id"]);
MemoryStream str = new MemoryStream(getImg);
Bitmap bitmap = new Bitmap(Image.FromStream(str));
BitmapImg = ImageToByte(bitmap);
dt.Rows.Add(personId, bitmap);
}
catch (Exception ex)
{
LogWriter.WriteLine(personId + ex.Message.ToString());
}
}
conn.Close();
return dt;
}
If your intent is saving images to disk, then why would you get them into an intermediate datatable? Wouldn't it be better if you directly write out to disk as you read them? If so, assuming those are .bmp files:
public static void DumpAllPhotos()
{
string sql = #"select per.person_id,pho.photo
from person as per
inner join photo as pho on per.photo_id = pho.photo_id";
string folder = #"c:\MyFolder"; // output folder
using (SqlConnection con = new SqlConnection(_connString))
using (SqlCommand cmd = new SqlCommand(sql,con))
{
con.Open();
var rdr = cmd.ExecuteReader();
while (rdr.Read())
{
var bytes = (byte[])rdr["photo"];
var path = Path.Combine(folder, $"{rdr["person_id"].ToString()}.bmp");
File.WriteAllBytes(path, bytes);
}
con.Close();
}
}
Bitmap has to be disposed, you're using too many handles.
So your while loop should be something like this:
while (dr.Read())
{
try
{
getImg = (byte[])dr["Photograph"];
personId = Convert.ToString(dr["person_id"]);
MemoryStream str = new MemoryStream(getImg);
Bitmap bitmap = new Bitmap(Image.FromStream(str));
BitmapImg = ImageToByte(bitmap);
dt.Rows.Add(personId, bitmap);
bitmap.Dipose(); // <--- DISPOSE!!
}
catch (Exception ex)
{
LogWriter.WriteLine(personId + ex.Message.ToString());
}
}
or maybe even better:
while (dr.Read())
{
try
{
getImg = (byte[])dr["Photograph"];
personId = Convert.ToString(dr["person_id"]);
MemoryStream str = new MemoryStream(getImg);
using (Bitmap bitmap = new Bitmap(Image.FromStream(str))) {
BitmapImg = ImageToByte(bitmap);
dt.Rows.Add(personId, bitmap);
}
}
catch (Exception ex)
{
LogWriter.WriteLine(personId + ex.Message.ToString());
}
}

ProductInsert() does not exist in current context

protected void Btn_CheckOut_Click(object sender, EventArgs e)
{
int result = 0;
Payment user = new Payment(txt_CardNumber.Text, txt_CardHolderName.Text, txt_ExpirationDate.Text, txt_Cvv.Text);
result = ProductInsert();
/* Session["CardNumber"] = txt_CardNumber.Text;
Session["CardHolderName"] = txt_CardHolderName.Text;
Session["ExpirationDate"] = txt_ExpirationDate.Text;
Session["Cvv"] = txt_Cvv.Text;*/
Response.Redirect("Payment Sucessful.aspx");
}
public int ProductInsert()
{
int result = 0;
string queryStr = "INSERT INTO CustomerDetails(CardNumber, CardHolderName, ExpirationDate, Cvv)"
+ "values (#CardNumber,#CardHolderName, #ExpirationDate, #Cvv)";
try
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#CardNumber", this.CardNumber);
cmd.Parameters.AddWithValue("#CardHolderName", this.CardHolderName);
cmd.Parameters.AddWithValue("#ExpirationDate", this.ExpirationDate);
cmd.Parameters.AddWithValue("#Cvv", this.Cvv);
conn.Open();
result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
conn.Close();
return result;
}
catch (Exception ex)
{
return 0;
}
}
}
I am trying to store credit card informations into database. I have created a productInsert() method and now I am trying to insert whatever values into the database.
This code is giving the error:
ProductInsert() does not exist in current context

Reading Multiple data

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Ontrip _ontrip = new Ontrip(_FNAME);
string _query2 = "select CContactno from CustomerTbl where CUsername = #USERNAME";
string _query3 = "select Price from TransactionTypeTble T join PendingTransTbl P ON P.TransType = T.TransType ";
string _query4 = "select VehicleDescription from DriverTbl D join VehicleSpecTbl V ON D.VehicleType = V.VehicleType";
SqlConnection _sqlcnn = new SqlConnection("Data Source=MELIODAS;Initial Catalog=WeGo;Integrated Security=True");
_sqlcnn.Open();
try
{
SqlDataReader _reader = null;
SqlCommand _cmd = new SqlCommand("Select CFName+' '+CLName from CustomerTbl where CUsername=#USERNAME", _sqlcnn);
SqlParameter _param = new SqlParameter();
_param.ParameterName = "#USERNAME";
_param.Value = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
_cmd.Parameters.Add(_param);
_reader = _cmd.ExecuteReader(); //for displaying users name in the label
while (_reader.Read())
{
_ontrip._txtboxUsername.Text = _reader.GetString(0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
using (SqlCommand _sqlcmd = new SqlCommand(_query2, _sqlcnn))
{
try
{
SqlDataReader _reader = null;
SqlParameter _param = new SqlParameter();
_param.ParameterName = "#USERNAME";
_param.Value = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
_sqlcmd.Parameters.Add(_param);
_reader = _sqlcmd.ExecuteReader(); //for displaying users name in the label
while (_reader.Read())
{
_ontrip._txtboxContact.Text = _reader.GetString(0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Is their a way for me to read the query and display the output, when i run this code their is an error saying that their is already an open data reader associated with the command. I should be displaying multiple data in a textbox
try Call Close when done reading.
_reader.Close();
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Ontrip _ontrip = new Ontrip(_FNAME);
string _query2 = "select CContactno from CustomerTbl where CUsername = #USERNAME";
string _query3 = "select Price from TransactionTypeTble T join PendingTransTbl P ON P.TransType = T.TransType ";
string _query4 = "select VehicleDescription from DriverTbl D join VehicleSpecTbl V ON D.VehicleType = V.VehicleType";
SqlConnection _sqlcnn = new SqlConnection("Data Source=MELIODAS;Initial Catalog=WeGo;Integrated Security=True;MultipleActiveResultSets=True ");
_sqlcnn.Open();
I added MultipleActiveResultSet or MARS

Retrieve database values to textboxes whenever listbox selected index changed

so I just want to view the values from my database to some textboxes in my project whenever the selected index of listbox changes
I have these code but whenever I click an item on my listbox, none of the textboxes displays a data or anything
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringHRMS"].ConnectionString);
conn.Open();
string selectone = "SELECT * FROM Applicant WHERE ApplicationNo = '" + ListBox1.SelectedValue.ToString() + "'";
SqlCommand cmd = new SqlCommand(selectone, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
asln.Text = reader["LastName"].ToString();
asfn.Text = reader["FirstName"].ToString();
asmn.Text = reader["MiddleName"].ToString();
ashea.Text = reader["HEA"].ToString();
astitle.Text = reader["Title"].ToString();
aspos.Text = reader["Position"].ToString();
asaddress.Text = reader["Address"].ToString();
asbday.Text = reader["Birthday"].ToString();
asgender.Text = reader["Gender"].ToString();
asage.Text = reader["Age"].ToString();
asht.Text = reader["Height"].ToString();
aswt.Text = reader["Weight"].ToString();
asemail.Text = reader["Email"].ToString();
ascontact.Text = reader["ContactNumber"].ToString();
}
reader.Close();
conn.Close();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}

Select statement using OleDbCommand throws InvalidOperationException

I need to find a record in C# but I get an InvalidOperationException:
public static Auto findAuto(int kfznr)
{
Auto retAuto = new Auto();
try
{
myOleDbConnection.Open();
string query = "SELECT * FROM Auto WHERE Auto.KFZNR = " + kfznr;
OleDbCommand select = new OleDbCommand();
select.Connection = myOleDbConnection;
select.CommandText = query;
OleDbDataReader reader = select.ExecuteReader();
while (reader.Read())
{
Auto at = new Auto(Convert.ToInt32(reader[0]), Convert.ToString(reader[1]), Convert.ToString(reader[2]));
retAuto = at;
}
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
}
return retAuto;
}
I get the error in the while loop at the creation of the new Auto.
When I run the same query in the SQLDeveloper I get one record (take a look at the first screenshot) but in my C# program I get there is no data for my row/cell.
When I hover the reader I get the following image. It says that the reader has rows:
Hope that you can help me fix this problem.
You need to use reader.GetValue(0)
public static Auto findAuto(int kfznr)
{
Auto retAuto = new Auto();
try
{
myOleDbConnection.Open();
string query = "SELECT * FROM Auto WHERE Auto.KFZNR = " + kfznr;
OleDbCommand select = new OleDbCommand();
select.Connection = myOleDbConnection;
select.CommandText = query;
OleDbDataReader reader = select.ExecuteReader();
while (reader.Read())
{
Auto at = new Auto(Convert.ToInt32(reader.GetValue(0)), Convert.ToString(reader.GetValue(1)), Convert.ToString(reader.GetValue(2)));
retAuto = at;
}
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
}
return retAuto;
}
Also wanted to add...you can access the reader values by column name as well using:
reader["ColumnName"]...don't forget the "" around the name of the column ;)
public static Auto findAuto(int kfznr)
{
Auto retAuto = new Auto();
try
{
myOleDbConnection.Open();
string query = "SELECT * FROM Auto WHERE Auto.KFZNR = " + kfznr;
OleDbCommand select = new OleDbCommand();
select.Connection = myOleDbConnection;
select.CommandText = query;
OleDbDataReader reader = select.ExecuteReader();
while (reader.Read())
{
Auto at = new Auto(Convert.ToInt32(reader["col1"]), Convert.ToString(reader["col2"]), Convert.ToString(reader["col3"]));
retAuto = at;
}
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
}
return retAuto;
}

Categories