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();
}
}
}
Related
I need to create a table which will always display the last ten records of CTLog on a TableLayoutPanel. So whenever the user adds a new CTLog in Access database by clicking on a button, the table will dynamically update and display the last ten CTLogs. When adding the first ten records, I managed to get them on table but those records added after the 10th row cannot be displayed. I used the method of replacing the old labels on TableLayoutPanel by erasing the old one and then add the new ones.
private void RecentCT()
{
int j = 0;
for (j = 0; j < 10; j++)
{
tableLayoutPanel1.Controls.Remove(tableLayoutPanel1.GetControlFromPosition(j + 1, 0));
tableLayoutPanel1.Controls.Remove(tableLayoutPanel1.GetControlFromPosition(j + 1, 1));
}
string sql = "select Top 10 * from timer where ModelLog = #m and ShiftLog = #sl and ShiftStart = #ss and ShiftEnd = #se";
using (OleDbCommand cmd = new OleDbCommand(sql, connection))
{
//all cmd.Parameters.Add actions at here
try
{
connection.Open();
//List<string> results = new List<string>(); I used list and foreach previously
Label[] labels = new Label[10];
Label[] labels2 = new Label[10];
int i = 0;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
labels[i] = new Label
{
Text = reader["CTLog"].ToString(),
Anchor = AnchorStyles.None,
Font = new Font("Microsoft Sans Serif", 10, FontStyle.Regular),
TextAlign = ContentAlignment.MiddleCenter
};
labels2[i] = new Label
{
Text = "Unit " + reader["UnitID"].ToString(),
Anchor = AnchorStyles.None,
Font = new Font("Microsoft Sans Serif", 10, FontStyle.Regular),
TextAlign = ContentAlignment.MiddleCenter
};
tableLayoutPanel1.Controls.Add(labels2[i], i + 1, 0);
tableLayoutPanel1.Controls.Add(labels[i], i + 1, 1);
i++;
}
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Recent cycle time records cannot be retrieved. Error: " + ex.Message);
connection.Close();
}
}
}
Did I miss out something or something is wrong in my method?
Problem is with the sql query I used.
This is the correct sql query:
string sql = "select top 10 * from timer where ModelLog = #m and ShiftLog = #sl and ShiftStart = #ss and ShiftEnd = #se ORDER BY ID DESC";
To get the latest 10 rows of records, I must combine top and order by in desc form in a query. Because using only top keyword will only get the first 10 row, not the last ten rows.
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();
}
}
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.
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.
I have a stored procedure that return 3 tables . All I care about populating the List with is the result set from the last table the stored procedure returns; which has 3 columns. I have the following code so far:
string connStr = null;
SqlConnection scnn;
SqlCommand sCmd;
string sql = null;
connStr = "Data Source=server;Initial Catalog=dbName;Integrated Security=SSPI";
sql = #"DECLARE #udt1 userDefTblType1;" +
"INSERT INTO #one (uid) VALUES (0), (1), (2), (3);" +
"DECLARE #udt2 userDefTblType2;" +
"INSERT INTO #two (uid) VALUES (0);" +
"DECLARE #udt3 userDefTblType3;" +
"INSERT INTO #three (uid) VALUES (0),(1);" +
"EXEC [dbo].[storedProcedure] #one, #two, #three;";
sqlCnn = new SqlConnection(connStr);
try
{
sCnn.Open();
sCmd = new SqlCommand(sql, sCnn);
SqlDataReader sReader = sCmd.ExecuteReader();
sReader.Read();
sReader.NextResult(); //move to next table
sReader.Read();
sReader.NextResult(); //move to next table
sReader.Read(); //table of interest
List<decimal> results = new List<decimal>();
while (sReader.Read())
{
results.Items.Add(sqlReader["column1"].ToString()); //my problem is here
results.Items.Add(sqlReader["column2"].ToString()); //my problem is here
results.Items.Add(sqlReader["column2"].ToString()); //my problem is here
};
sqlReader.Close();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I need to fill the list like column1, column2, column3 respectively for as many rows there are so that I can populate an HTML table.
May you advise on what I am doing wrong; am I taking the right approach?
Thanks (I am starting to get a little more advance in C#, I do more db dev)
EDIT:
The following is an example of the 3rd table the stored proc returns:
Column1 | Column2 | Column3
---------------------------
5.6 | 5.1 | 7.4 |
5.7 | 5.4 | 7.7 |
5.8 | 5.6 | 7.9 |
5.9 | 5.8 | 7.0 |
5.1 | 5.6 | 7.7 |
I have code already dynamically written for a html table. I just need to store these results some where to enumerate through them so can add the values to the relative html tabs in my code.
EDIT:
In the end I want my code to look something like this:
html.WriteLine("<tr>");
while (colCount <= numCol)
{
html.WriteLine("<td>" POSITION IN <LIST> + "</td>");
cFinalColCount++;
}
html.WriteLine("</tr>");
rowCount++;
Use a gridview for tabling data in your html. It's much easier than building your own tables.
C# code:
DataTable dt = new DataTable();
try
{
sCnn.Open();
sCmd = new SqlCommand(sql, sCnn);
SqlDataReader sReader = sCmd.ExecuteReader();
sReader.Read();
sReader.NextResult(); //move to next table
sReader.Read();
sReader.NextResult(); //move to next table
dt.Load(sReader); // Convert your data reader to a DataTable
sqlReader.Close();
sqlCmd.Dispose();
sqlCnn.Close();
// UNTESTED CODE - but it should be close.
GridView gv = new GridView(); // create gridview
gv.DataSource = dt; // Set the DataTable as the DataSource for the GridView
gv.DataBind(); // Bind the Data to the GridView
StringWriter sWriter = new StringWriter(); //stringwriter needed for html writer
HtmlTextWriter htWriter = new HtmlTextWriter(sWriter); // create HthmWriter
gv.RenderControl(htWriter); //render the gridview in the htmlwriter
htWriter.Write(true); // write the html writer to the output stream
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
As JonSkeet suggested, what makes the most sense is to declare a class with three decimals as properties (preferably with sensible names, such as below):
public class Volume
{
public decimal Length { get; set; }
public decimal Width { get; set; }
public decimal Height { get; set; }
}
Then you'll create a List of Volume objects:
List<Volume> results = new List<Volume>();
while (sReader.Read())
{
// Error checking elided
var length = decimal.Parse(sqlReader["column1"]);
var width = decimal.Parse(sqlReader["column2"]);
var height = decimal.Parse(sqlReader["column3"]);
results.Add(new Volume { Length = length, Width = width, Height = height });
};