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.
Related
I want make a auto number based date and number at "Transaction" Form. But i have problem with make a "condition" to compare date "today" and date "yesterday". If date is different, then will make a new "autonumber" from number 1. For example, that date is 2019-08-08 so the ID from "permintaanId" is P2019080803 (two last number is how many transaction make that day). And tomorrow is 2019-08-09 will make ID P2019080901 (two last number will reset because no one transaction make)
private void auto()
{
long hitung;
string urut;
SqlConnection conn = konn.GetConn();
conn.Open();
cmd = new SqlCommand("select permintaanId from permintaan_data where permintaanId in(select max(permintaanId) from permintaan_data) order by permintaanId DESC", conn);
rd = cmd.ExecuteReader();
rd.Read();
if (rd.HasRows) //<- this condition
{
hitung = Convert.ToInt64(rd[0].ToString().Substring(rd["permintaanId"].ToString().Length - 2, 2)) + 1;
string joinstr = "00" + hitung;
urut = "P" + DateTime.Now.ToString("yyyyMMdd") + joinstr.Substring(joinstr.Length - 2, 2);
}
else
{
urut = "P" + DateTime.Now.ToString("yyyyMMdd") + "01";
}
rd.Close();
txt_noPermintaan.Text = urut;
conn.Close();
}
get last item created
cmd = new SqlCommand("select top1 permintaanId from permintaan_data order by DESC", conn);
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
var id = rd["the one with p and 2 numbers at the end"].ToString();
var dateLastCreated = id.ToString().Remove(0,1).Remove(id.Length-2,2);
if (dateLastCreated == DateTime.Now.ToString("yyyyMMdd"))
{
//increment
}
else
{
//create new
}
}
DECLARE #permintaanId INT=0
DECLARE #NewNo VARCHAR(40)=''
select #permintaanId=CAST(ISNULL(MAX(RIGHT(permintaanId,1)),0)+1 AS INT)
FROM permintaan_data
WHERE CAST([tranData] AS DATE) =CAST(GETDATE() AS DATE)
SET #NewNo='P'+CONVERT(VARCHAR(10),GETDATE(),112)+CAST(#permintaanId AS VARCHAR(10))
SELECT #NewNo
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();
}
}
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();
}
}
}
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.
This is s for loop and it will go to the times and will put the time column as true. This works for the first time, but when the time increases by 0.5, it stays false. The for loop is working as i tried a MessageBox.Show("" + Time1 + ""); inside the for loop.
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
try
{
SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");
cn.Open();
SqlCommand Command = new SqlCommand("INSERT INTO Slots ([Date],[RoomID],[" + Time1 + "]) Values (#date,#room,1)", cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
try
{
cn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here is what the database looks like, the first true field works, but when it loops to another time, it remains false, I think it may be due to the fact that if I have an existing row with that date (date is primary key), i cannot update that row, so i might need to have an IF the row exists, update, else create a new row.
Try this, you don't have to open connection in each loop, create your sql statement first looping through each value and then do insert using one statement
private string CreateInsertStatement(double time_began_5, double time_finished_5)
{
string sql = "INSERT INTO Slots ([Date],[RoomID],";
string valuesql = " Values (#date,#room,";
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
sql+ = "[" + Time1 + "],";
valuesql+ = "1,";
}
sql = sql.TrimEnd(',') + ") ";
valuesql = valuesql.TrimEnd(',') + ") ";
return sql + valuesql;
}
private string CreateUpdateStatement(double time_began_5, double time_finished_5)
{
string sql = "UPDATE Slots SET ";
string wheresql = " WHERE [Date] = #date AND [RoomID] = #room";
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
sql+ = "[" + Time1 + "] = 1,";
}
sql = sql.TrimEnd(',');
return sql + wheresql;
}
Then in you actual insert code:
try
{
SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");
cn.Open();
SqlCommand Command;
//check if row exists
Command = new SqlCommand("select count(*) from Slots WHERE [Date] = #date AND [RoomID] = #room", cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
var cnt = Command.ExecuteScalar();
if(cnt!=null)
{
string sqlstr = ""
if(Int32.Parse(cnt.ToString()) > 0)
{
sqlstr = CreateUpdateStatement(time_began_5,time_finished_5);
}
else if(Int32.Parse(cnt.ToString()) == 0)
{
sqlstr = CreateInsertStatement(time_began_5,time_finished_5);
}
Command = new SqlCommand(sqlstr, cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
}
try
{
cn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
You are doing an insert.
In every loop you insert a new row and set the value true only for the column which name is equal to the current value of the variable Time1.
Not having a value for the other columns they probably default to false. (bit columns I suppose)
If you want a default to true for every column perhaps it is better to change the database schema adding the default for every time column, otherwise you need a long list of parameters
EDIT: If your logic dictates that you need only one row per date and set every time column to true if you enter the situation above then you can move this logic in the database using a stored procedure:
CREATE PROCEDURE InsertOrUpdateSlotFromCode(#dt smalldatetime, #roomID int)
AS
BEGIN
DECLARE #cnt INT
SELECT #cnt = COUNT(*) from Slots WHERE [Date] = #dt
if #cnt = 0
INSERT INTO Slots ([Date],[RoomID], <here all the time fields> VALUES (#dt, #roomID, 1, ....)
else
UPDATE Slots SET [09.00] = 1, ..... WHERE [Date] = #dt
End
END
then your code call the sp
using(SqlConnection cn = new SqlConnection(.........))
{
cn.Open();
SqlCommand Command = new SqlCommand("InsertOrUpdateSlotFromCode", cn);
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
}
Of course now you can completely get rid of the loop