Update Stored Procedure with a DataBound CheckBoxList - c#

I have a webapp that dynamically generates images (i.e. Barcodes). The images are generated using user input. The user chooses data from a databound checkbox lists, that data is then concatenated a date using a date picker, and lastly the user enters an amount. That then creates a number of images from the amount entered by the user.
My program runs and generates the images with no issue. I want to eventually have the information entered by the user sent to a database, that way, the amount entered will be sequenced, which resets itself after every 24 hours.
My issue is at the moment, when I run my app, and enter the information, if 1 checkbox is selected, it updates the information with no issue, along with successfully generating the images. If I choose more than one checkbox my database will only update the first checkbox selected in my CheckBoxList and it's respective row in the database.
Here is my C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.CheckBoxListDataBind();
//Binds Database Data to CheckBoxList1
}
}
private string GetConnectionString()
{
//SQL Connection String
return System.Configuration.ConfigurationManager.ConnectionString["DatabaseConnection"].ConnectionString;
}
//method to bind CheckBoxList
public void CheckBoxListDataBind()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT AccountID, AccountName FROM AccountTable ORDER BY AccountID ASC;"
cmd. Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while(sdr.Read())
{
ListItem. item = new ListItem();
item.Text = sdr["AccountID"].ToString() + "-" + sdr["AccountName].ToString();
item.Value = sdr["AccountID"].ToString();
item.Text = sdr{"AccountName].ToString();
cmd.Parameters.AddWithValue("AccountID", CheckBoxList1)
cmd.Parameters.AddWithValue("AccountName", CheckBoxList1)
CheckBoxList1.Items.Add(item);
}
}
conn.Close();
}
//method to generate image
public Bitmap DrawBarcode(string data, string label)
{
Bitmap dyn_image = new Bitmap(date,Length * 27, 150);
PointF point = new PointF(2,2)
Font dyn_image_font = new Font("ImageFontName", 16, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
Font label_font = new Font("Tahoma", 9, System.Drawing.FontStyle.Reguar, System.Drawing.GraphicsUnit.Point);
Graphics graphics = Graphics.FromImage(dyn_image);
graphics = Graphics.FromImage(dyn_image);
graphics.Clear(Color.White);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, dyn_image.Width, dyn_image.Height);
graphics.DrawString(dyn_image_font, label_font, new SolidBrush(Color.Black), point);
RectangleF rectF = new RectangleF(5 , 100, 250, 170);
graphics.DrawString(label, label_font, new SolidBrush(Color.Black), rectF);
graphics.Flush();
graphics.Dispose();
System.Web.UI.Controls.Image gen_image = new System.Web.UI.WebControls.Image();
using (MemoryStream ms = new MemoryStream())
{
dyn_image.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
gen_image.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(byteImage);
}
return dyn_image;
}
//button click method handles user inputs
protected void Generate(object sender, EventArgs e)
{
CultureInfo provider = CultureInfo.InvariantCulture;
System.Globalization.DateTimeStyle style = DateTimeStyle.None;
DateTime dt;
DateTime.TryParseExact(datepicker.Text, "mmddyyyy", provider, style out dt)"
int i = Int32.Parse(amount.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Update_Account_Table";
cmd.Parameters.AddWithValue("#SeqNum", SqlDbType.VarChar).Value = i;
cmd.Parameters.AddWithValue("#SeqDate", SqlDbType.DateTime).Value = dt;
cmd.Parameters.AddWithValue("#Account_ID", SqlDbType.VarChar).Value = CheckBoxList1.SelectedValue;
foreach(List item in CheckBoxList1.Items)
{
//this forloops is for the DrawImage() method to generate more than
//one image from user input amount
for(int n = 1; n <= i; n++)
{
if (item.Selected)
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string barcode_label = item.Text + "QTY:___________"
//When image generates, it will show 1 to user input amount
string barode_data = item.Value + datepicker.Text + n.ToSTring("D2");
Bitmap dynImage = DrawBarcode(barcode_data, barcode_label)
MemoryStream ms = new MemoryStream();
dynImage.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
img.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(byteImage);
panel1.Controls.Add(img);
double spacing;
double mg = 5;
spacing = img.Width.Value + mg;
}
}
//handling parameters in loop.
cmd.Parameters["#SeqNum"].Value = amount.Text;
cmd.Parameters["#SeqDate"].Value = DateTime.ParseExact(datepicker.Text, "mmddyyyy", CultureInfo.InvariantCulture);
cmd.Parameters["#Account_ID"].CheckBoxList1.SelectedValue;
cmd.ExecuteNonQuery();
}
conn.Close();
}
SQL Code
CREATE TABLE AccountTable
(
RowID int IDENTITY(1, 1),
AccountID varchar(2),
AccountName varchar(50),
SeqNum int,
SeqDate datetime
)
CREATE PROCEDURE [ACCOUNTTABLE_UPDATE]
(
#SeqNum int,
#SeqDate datetime,
#Account_ID varchar(2)
)
AS
SET NOCOUNT ON
BEGIN
UPDATE AccountTable
SET SeqNum = #SeqNum, SeqDate = #SeqDate
WHERE AccountID = #AccountID
END
On my webpage I have a checkboxlist, a textbox that reads an int value, another textbox that uses a JQuery Calender for input, as well as a javascript print function that prints the panel from a webpage and finally, the CheckBoxList uses another javascript function to check all the boxes or uncheck them.
As stated before, my code works fine, but it's not updating the database as intended. It will only update one row in the database which is determined by the Account_ID selected in the checkboxlist. As long as 1 is selected, any selection can be update. If I select all in the checkboxlist, or more than one, only the first checkbox in the list is updated.

Related

C# Read the image from database and Save it to another database

Below this code is where i try to retrieve the image to my database and try to save it to another database. In the first image you will see the error that i encountered during the run time when i click that ok button. In the second image you will see that i already inserted the data with my retrieve image but i encountered that error (I see that the image is inserted but i don't know if that is the correct one)
In my employee_product table i have the "Image" column = image datatype
(This table is where i retrieve my image)
In my product_result table I have the same column and same datatype
(This table is where i inserted the retrieved image)
What i want to happen is to retrieve that image and when click the ok button it will save to my database also it will show to my datagridview
//My Code for Adding the image to my employee_product
private void btn_add_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
try
{
var ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] PhotoByte = ms.ToArray();
if (string.IsNullOrEmpty(cbox_supplier.Text) || string.IsNullOrEmpty(txt_code.Text) || string.IsNullOrEmpty(txt_item.Text) || string.IsNullOrEmpty(txt_quantity.Text) || string.IsNullOrEmpty(txt_cost.Text))
{
MetroMessageBox.Show(this, "Please input the Required Fields", "System Message:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
var selectCommand = new SqlCommand("Insert into employee_product (Image, Supplier, Codeitem, Itemdescription, Date, Quantity, Unitcost) Values (#Image, #Supplier, #Codeitem, #Itemdescription, #Date, #Quantity, #Unitcost)", con);
selectCommand.Parameters.AddWithValue("#Image", PhotoByte);
selectCommand.Parameters.AddWithValue("#Supplier", cbox_supplier.Text);
selectCommand.Parameters.AddWithValue("#Codeitem", txt_code.Text.Trim());
selectCommand.Parameters.AddWithValue("#Itemdescription", txt_item.Text.Trim());
selectCommand.Parameters.AddWithValue("#Date", date);
selectCommand.Parameters.AddWithValue("#Quantity", txt_quantity.Text.Trim());
selectCommand.Parameters.AddWithValue("#Unitcost", txt_cost.Text.Trim());
selectCommand.ExecuteNonQuery();
MessageBox.Show("Added successfully", "SIMS", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
txt_path.Clear();
pictureBox1.Image = null;
cbox_supplier.Items.Clear();
txt_code.Clear();
txt_item.Clear();
txt_quantity.Clear();
txt_cost.Clear();
_view.AddingProduct();
}
}
catch (Exception)
{
MessageBox.Show("Input image");
}
}
}
byte[] data;
public void display()
{
using (var con = SQLConnection.GetConnection())
{
SqlCommand selectTable = new SqlCommand("Select * from product_result ; ", con);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = selectTable;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
_view.ListProduct.DataSource = bSource;
sda.Update(dbdataset);
}
}
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
var selects = new SqlCommand("Select * from employee_product where Codeitem =#Codeitem ", con);
selects.Parameters.Add("#Codeitem", SqlDbType.VarChar).Value = _view.txt_code.Text;
SqlDataReader reader;
reader = selects.ExecuteReader();
while (reader.Read())
{
data = (byte[])reader["Image"];
}
reader.Close();
var selectCommand = new SqlCommand("Insert into product_result (Image, Code, Name, Price, Discount, Quantity) Values (#Image, #Code, #Name, #Price, #Discount, #Quantity)", con);
selectCommand.Parameters.AddWithValue("#Image", data);
selectCommand.Parameters.AddWithValue("#Code", _view.txt_code.Text);
selectCommand.Parameters.AddWithValue("#Name", _view.txt_name.Text.Trim());
selectCommand.Parameters.AddWithValue("#Price", _view.txt_price.Text.Trim());
selectCommand.Parameters.AddWithValue("#Discount", txt_discount.Text.Trim());
selectCommand.Parameters.AddWithValue("#Quantity", txt_quantity.Text.Trim());
selectCommand.ExecuteNonQuery();
var select = new SqlCommand("Update employee_product set quantity = quantity - #Quantity where Codeitem= #Codeitem",con);
select.Parameters.AddWithValue("#Codeitem", _view.txt_code.Text);
select.Parameters.AddWithValue("#Quantity", txt_quantity.Text);
select.ExecuteNonQuery();
this.Close();
display();
}
}
You will see in this picture that image has a code. If user input another code it will get another image
You can save the image of the PictureBox to db like this....
MemoryStream getimagestream = new MemoryStream();
pictureBox1.Image.Save(getimagestream, _pb_photo.Image.RawFormat);
byte[] Imagedata = getimagestream.GetBuffer();
You can receive the image from db to picture box like this.
var ImagedataReceive = (byte[])reader["Image"];
var stream = new MemoryStream(ImagedataReceive);
pictureBox1.Image = Image.FromStream(stream);
You will need to provide a cell formatting method that puts the data into an image object the data gridview can use.
private void dgv_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (dgv.Columns[e.ColumnIndex].Name == "Image")
{
if (e.Value != null)
{
... convert byte[] to image...
}
}
}

Generating a sequence using user input and database values

I'm trying to figure out how to create a sequence of numbers using values stored in a database and user input. I have a webapp that is generating barcodes. I know my issue lies with my nested for loop. Whatever value I have stored on my database, I want the user to start from that number and generate the amount of barcodes entered by the user starting from that number. The loop iterates strangely where it will not generate any images if the value entered is less than the what is in the database. If I enter a value greater than what is in the database it will only generate a number of images that is the difference between what the use entered and what's in the database.
CREATE TABLE AccountTable
(
RowID int IDENTITY(1, 1),
AccountID varchar(2),
AccountName varchar(50),
SeqNum int,
SeqDate datetime
)
protected void Btn_Click(object sender, EventArgs e)
(
CultureInfo provider = CultureInfo.InvariantCulture;
System.Globalization.DateTimeStyle style = DateTimeStyle.None;
DateTime dt;
DateTime.TryParseExact(datepicker.Text, "mmddyyyy", provider, style out dt);
int i = Int32.Parse(amount.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.Text = "SELECT MAX(SeqNum) as k FROM AccountTable;";
cmd.Connection = conn;
foreach(List item in CheckBoxList1.Items)
{
conn.Open();
var k = Convert.Int31(cmd.ExecuteScalar());
for(int n = k; n <= i; n++)
{
if (item.Selected)
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string barcode_label = item.Text + "QTY:___________"
string barode_data = item.Value + datepicker.Text + n.ToSTring("D2");
Bitmap dynImage = DrawBarcode(barcode_data, barcode_label)
MemoryStream ms = new MemoryStream();
dynImage.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
img.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(byteImage);
panel1.Controls.Add(img);
double spacing;
double mg = 5;
spacing = img.Width.Value + mg;
}
}
conn.Close();
}
}

Dynamically creating images in a sequence and having the sequence reset

Being a novice, I'm working on something and wanted to know if the desired end product can be achieved and if it is efficient. I've asked several questions on here and with each small triumph, I've hit a brick wall and researching has given mixed results. I don't know if a question like this should be asked on here or on one of the other Stack Exchange sites.
I have a web app that dynamically generates barcodes. The web app has a databound checkboxlist. The user checks their desired checkbox. With that, the user enters how many they want as well as a date. With that, the barcode is generated and the code uses a concatenation of the data in the checkboxlist, the date, and the amount entered. Using WebControls, the images are placed in a panel on the webpage and the user can simply print the image, that portion works just fine.
What I would like to know if it's at least possible or not, each time the user generates images, so they choose 1 or more names int the CheckBoxList, enter the amount desired, as well as the date, if that information being stored on a database can then be retrieved again in the same event if the user wants to generate more of the same barcodes?
I'll add my code to give an idea of what's going on.
EDIT
To elaborate more on what I'm asking.
A user selects a checkbox
[X] AB
[] BC
[] CD
[] DE
Then enters an amount and selects a date. Let's say 10 and the date is January 25th 2016. The code generates 10 barcodes. The code generated for those barcodes are AB01251601 AB01251602 AB01251603...AB01251610 which ends on 10. What I'd want to know if it's possible, each time the user runs this, if this information can be added to a a database and then on another page event or even the same (maybe with a TextChanged Event) If the user wants another 3 barcodes, they can enter the information again and the generated codes start at 11. AB01251611, AB01251612, AB01251613.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.CheckBoxListDataBind();
//Binds Database Data to CheckBoxList1
}
}
private string GetConnectionString()
{
//SQL Connection String
return System.Configuration.ConfigurationManager.ConnectionString["DatabaseConnection"].ConnectionString;
}
//method to bind CheckBoxList
public void CheckBoxListDataBind()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT AccountID, AccountName FROM AccountTable ORDER BY AccountID ASC;"
cmd. Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while(sdr.Read())
{
ListItem. item = new ListItem();
item.Text = sdr["AccountID"].ToString() + "-" + sdr["AccountName].ToString();
item.Value = sdr["AccountID"].ToString();
item.Text = sdr{"AccountName].ToString();
cmd.Parameters.AddWithValue("AccountID", CheckBoxList1)
cmd.Parameters.AddWithValue("AccountName", CheckBoxList1)
CheckBoxList1.Items.Add(item);
}
}
conn.Close();
}
//method to generate image
public Bitmap DrawBarcode(string data, string label)
{
Bitmap dyn_image = new Bitmap(date,Length * 27, 150);
PointF point = new PointF(2,2)
Font dyn_image_font = new Font("ImageFontName", 16, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
Font label_font = new Font("Tahoma", 9, System.Drawing.FontStyle.Reguar, System.Drawing.GraphicsUnit.Point);
Graphics graphics = Graphics.FromImage(dyn_image);
graphics = Graphics.FromImage(dyn_image);
graphics.Clear(Color.White);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, dyn_image.Width, dyn_image.Height);
graphics.DrawString(dyn_image_font, label_font, new SolidBrush(Color.Black), point);
RectangleF rectF = new RectangleF(5 , 100, 250, 170);
graphics.DrawString(label, label_font, new SolidBrush(Color.Black), rectF);
graphics.Flush();
graphics.Dispose();
System.Web.UI.Controls.Image gen_image = new System.Web.UI.WebControls.Image();
using (MemoryStream ms = new MemoryStream())
{
dyn_image.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
gen_image.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(byteImage);
}
return dyn_image;
}
//button click method handles user inputs
protected void Generate(object sender, EventArgs e)
{
CultureInfo provider = CultureInfo.InvariantCulture;
System.Globalization.DateTimeStyle style = DateTimeStyle.None;
DateTime dt;
DateTime.TryParseExact(datepicker.Text, "mmddyyyy", provider, style out dt);
int i = Int32.Parse(amount.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
foreach(List item in CheckBoxList1.Items)
{
//this forloops is for the DrawImage() method to generate more than
//one image from user input amount
for(int n = 1; n <= i; n++)
{
if (item.Selected)
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string barcode_label = item.Text + "QTY:___________"
//When image generates, it will show 1 to user input amount
string barode_data = item.Value + datepicker.Text + n.ToSTring("D2");
Bitmap dynImage = DrawBarcode(barcode_data, barcode_label)
MemoryStream ms = new MemoryStream();
dynImage.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
img.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(byteImage);
panel1.Controls.Add(img);
double spacing;
double mg = 5;
spacing = img.Width.Value + mg;
}
}
}
conn.Open();
foreach(ListItem item in CheckBoxList1.Items)
{
if(item.Selected)
{
//handling parameters in loop.
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Update_Account_Table";
cmd.Parameters["#SeqNum"].Value = amount.Text;
cmd.Parameters["#SeqDate"].Value = DateTime.ParseExact(datepicker.Text, "mmddyyyy", CultureInfo.InvariantCulture);
cmd.Parameters["#Account_ID"].CheckBoxList1.SelectedValue;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
SQL Code
CREATE TABLE AccountTable
(
RowID int IDENTITY(1, 1),
AccountID varchar(2),
AccountName varchar(50),
SeqNum int,
SeqDate datetime
)
CREATE PROCEDURE [ACCOUNTTABLE_UPDATE]
(
#SeqNum int,
#SeqDate datetime,
#Account_ID varchar(2)
)
AS
SET NOCOUNT ON
BEGIN
UPDATE AccountTable
SET SeqNum = #SeqNum, SeqDate = #SeqDate
WHERE AccountID = #AccountID
END
If a user selects a box, runs the application, the user's input is sent to the database
[X] AB
[] BC
[] CD
[] DE
Please Enter Amount [ 4]
Please Enter Date [08/24/2016]
The user submits the data on the webform and the database updates
RowID|AccountID|AccountName|SeqNum|SeqDate |
1|AB |Account A | 4|2016-24-08 00:00:0000|
2|BC |Account B |NULL |NULL |
3|CD |Account C |NULL |NULL |
4|DE |Account D |NULL |NULL |
The end goal is to when the user selects more than one checkbox and enters the values, more than one row in the table updates.
[X] AB
[X] BC
[X] CD
[X] DE
Please Enter Amount [ 4]
Please Enter Date [08/24/2016]
RowID|AccountID|AccountName|SeqNum|SeqDate |
1|AB |Account A | 4|2016-24-08 00:00:0000|
2|BC |Account B | 4|2016-24-08 00:00:0000|
3|CD |Account C | 4|2016-24-08 00:00:0000|
4|DE |Account D | 4|2016-24-08 00:00:0000|
I figured it out.
In my ListItem I had a value for Accound_ID. Since I was using that in one of the foreach loops that caused an issue when submitting through my database.
Creating another List and applying the new list on another foreach loop did the trick.
//In CheckBoxList1Bind() Method
ListItem item2 = new ListItem();
item.Value = sdr["AccountID"].ToString();
//In Generate() Method
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Update_Account_Table";
foreach(ListItem item2 in CheckBoxList1.Items)
{
if(item2.Selected)
{
//handling parameters in loop.
cmd.Parameters["#SeqNum"].Value = amount.Text;
cmd.Parameters["#SeqDate"].Value = DateTime.ParseExact(datepicker.Text, "mmddyyyy", CultureInfo.InvariantCulture);
cmd.Parameters["#Account_ID"].item2.Value;
cmd.ExecuteNonQuery();
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}

Creating a Sequence of numbers in dynamically generated images using database values

I have a web app that generates barcodes. It creates the barcodes by the amount entered by the user, then generates the code using the amount, a date value, and values in a checkboxlist. The data entered by the user is then sent to a database using a stored procedure. The date values and amount values in the corresponding table are reset every 24 hours, but if the user enters the values it increases, in a sequence throughout the day. What I'm trying to figure out is, if I can implement that sequence in my images that I am generating. I've attempted to use an SQL Reader but I don't know how to implement it correctly since it's in the foreach and for loop. The foreach takes the selected values in the checkbox list which then in the for loop creates the amount desired starting from the amount entered.
For example
1st. Attempt
[X] AB
[] BC
[] CD
[] DE
Please Enter Amount [ 4]
Please Enter Date [08/24/2016]
Barcodes:
AB08241601 AB08241602 AB08241603 AB08241604
2nd. Attempt
[X] AB
[] BC
[] CD
[] DE
Please Enter Amount [ 3]
Please Enter Date [08/24/2016]
Barcodes:
AB08241605 AB08241606 AB08241607
Here is the code that works
protected void Generate(object sender, EventArgs e)
{
CultureInfo provider = CultureInfo.InvariantCulture;
System.Globalization.DateTimeStyle style = DateTimeStyle.None;
DateTime dt;
DateTime.TryParseExact(datepicker.Text, "mmddyyyy", provider, style out dt);
int i = Int32.Parse(amount.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
foreach(List item in CheckBoxList1.Items)
{
for(int n = 1; n <= i; n++)
{
if (item.Selected)
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string barcode_label = item.Text + "QTY:___________"
//When image generates, it will show 1 to user input amount
string barode_data = item.Value + datepicker.Text + n.ToSTring("D2");
Bitmap dynImage = DrawBarcode(barcode_data, barcode_label)
MemoryStream ms = new MemoryStream();
dynImage.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
img.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(byteImage);
panel1.Controls.Add(img);
double spacing;
double mg = 5;
spacing = img.Width.Value + mg;
}
}
}
foreach(ListItem item2 in CheckBoxList1.Items)
{
if(item2.Selected)
{
//handling parameters in loop.
cmd.Parameters["#SeqNum"].Value = amount.Text;
cmd.Parameters["#SeqDate"].Value = DateTime.ParseExact(datepicker.Text, "mmddyyyy", CultureInfo.InvariantCulture);
cmd.Parameters["#Account_ID"].item2.Value;
cmd.ExecuteNonQuery();
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
SQL Code
CREATE TABLE AccountTable
(
RowID int IDENTITY(1, 1),
AccountID varchar(2),
AccountName varchar(50),
SeqNum int,
SeqDate datetime
)
CREATE PROCEDURE [ACCOUNTTABLE_UPDATE]
(
#SeqNum int,
#SeqDate datetime,
#Account_ID varchar(2)
)
AS
SET NOCOUNT ON
BEGIN
UPDATE AccountTable
SET SeqNum = SeqNum + #SeqNum, SeqDate = #SeqDate
WHERE AccountID = #AccountID
END
SqlDataReader() Attempt
cmd.CommandText = "SELECT SeqNum FROM AccountTable;";
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
foreach(List item in CheckBoxList1.Items)
{
for(int n = 1; n <= i; n++)
{
if (item.Selected)
{
if(sdr.Read())
{
n = (int)sdr["SeqNum"];
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string barcode_label = item.Text + "QTY:___________"
//When image generates, it will show 1 to user input amount
string barode_data = item.Value + datepicker.Text + n.ToSTring("D2");
Bitmap dynImage = DrawBarcode(barcode_data, barcode_label)
MemoryStream ms = new MemoryStream();
dynImage.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
img.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(byteImage);
panel1.Controls.Add(img);
double spacing;
double mg = 5;
spacing = img.Width.Value + mg;
}
}
}
}
while the database updates correctly it just displays the value found in the database and generates the first barcode with the database value and all other barcodes with with the value of 0. The amount of barcodes displayed corresponds to the Length of total items in my checkbox list. For an example below, if the Data for the checkbox selected = 4, if I run my code, the value in my database correctly changes to 6, but I get the results below
[X] AB
[] BC
[] CD
[] DE
Please Enter Amount [ 2]
Please Enter Date [08/24/2016]
Barcodes:
AB08241604 AB08241600 AB08241600 AB08241600
I don't know how to execute the reader with the items selected in the foreach loop since they are already being used to generate the barcodes themselves.

Displaying multiple image retrieving from database

My project allow admin to add medal for officer profile, currently I only able to insert the maximum of 5 medals. But my teacher ask me to let the admin insert as many medal as they want for the officer profile. I not sure how do I retrieve all the image that the admin inserted, I know how to insert image into database using varbinary. Do give me way for doing this. THANKS!
Code Below is how I do for inserting at maximum of 5 medals:
Code for uploading:
System.Drawing.Image uploaded = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
System.Drawing.Image newImage = new Bitmap(1024, 768);
using (Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(uploaded, 0, 0, 1024, 768);
}
byte[] results;
using (MemoryStream ms = new MemoryStream())
{
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
EncoderParameters jpegParms = new EncoderParameters(1);
jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
newImage.Save(ms, codec, jpegParms);
results = ms.ToArray();
}
string sqlImage = "Insert into OfficerMedal(policeid, image) values ('" + Session["policeid"] + "', #Data)";
SqlCommand cmdImage = new SqlCommand(sqlImage);
cmdImage.Parameters.AddWithValue("#Data", results);
InsertUpdateData(cmdImage);
I retrieve image using aspx page
protected void Page_Load(object sender, EventArgs e)
{
string strQuery = "select image from OfficerMedal where policeid='" + Session["policeid"] + "'";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download(DataTable dt)
{
// check if you have any rows at all
// no rows -> no data to convert!
if (dt.Rows.Count <= 0)
return;
// check if your row #0 even contains data -> if not, you can't do anything!
if (dt.Rows[0].IsNull("image"))
return;
Byte[] bytes = (Byte[])dt.Rows[0]["image"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpg";
Response.BinaryWrite(bytes);
Response.End();
}
To add on for this current method I retrieving image 1 by 1 from database. Instead of retrieving all image that belong to the officer.
The usual way to do this is with a HttpHandler rather than in your ASPX page itself. The handler is responsible for retrieving the image data from your database and outputting it as a graphic; it can then be used as the src for a regular <img> tag or the ImageUrl property for an <asp:image> control.
The easiest way to add a handler is to select Generic Handler in the Add New Item dialog:
In the code for the handler, ProcessRequest is the method that does the work e.g.
public void ProcessRequest(HttpContext context)
{
byte[] imageBytes;
// Get the id of the image we want to show
string imageId = context.Request.QueryString["ImageId"];
// Get the image bytes out of the database
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
// Pass in the image id we got from the querystring
SqlCommand cmd = new SqlCommand("SELECT image FROM PoliceMedal WHERE ImageId=" + imageId, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
reader.GetBytes(0, 0, imageBytes, 0, int.MaxValue);
}
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "image/jpg";
context.Response.BinaryWrite(imageBytes);
context.Response.End();
}
So we have our handler that will return the image data from the database, and we call this with a url like \ImageHandler.ashx?ImageId=1. This does require a change to your database in that you'll need to add a key to the PoliceMedal table - I suggest a SQL Server IDENTITY column.
It's not clear from your question how you're displaying the images on the ASPX page, so here I'll just show you how to add them into a PlaceHolder. So, we'll retrieve the set of image ids for an officer, construct an <asp:image> control for each of them and add the images to the PlaceHolder.
protected void Page_Load(object sender, EventArgs e)
{
using (
SqlConnection conn =
new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
// Query the table to get the list of image IDs for the current user
SqlCommand cmd = new SqlCommand("SELECT ImageId FROM PoliceMedal WHERE policeid = " + Session["policeid"], conn);
conn.Open();
SqlDataReader imageReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// For each image in the database
while (imageReader.Read())
{
// Create the new Image control
Image medalImage = new Image();
// Call the handler, passing the id of the image in the querystring
medalImage.ImageUrl = string.Format("ImageHandler.ashx?ImageId={0}",
imageReader.GetInt32(0));
// Add the image to the placeholder
MedalPlaceHolder.Controls.Add(medalImage);
}
}
}

Categories

Resources