Parameter is not valid Exception in windowsForm - c#

i am using multi panels for making multi section project and using access database and inserting some thing in it like below:
private void addmoneyPanel_firstLoad()
{
try
{
employee_list.Items.Clear();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select Ename,Elastname from employee";
OleDbDataReader reader = command.ExecuteReader();
while(reader.Read())
{
employee_list.Items.Add(reader[0].ToString() + " \n" +reader[1].ToString());
}
connection.Close();
/*addMoneyPanelMes.Text = "با موفقیت ذخیره شد.";
addMoneyPanelMes.ForeColor = Color.Green;*/
}
catch (Exception err)
{
addMoneyPanelMes.Text = "خظا در ارتباط با پایگاه داده.";
addMoneyPanelMes.ForeColor = Color.Red;
addMoneyPanelMes.Visible = true;
}
}
private void pictureBox1_Click_1(object sender, EventArgs e)
{
try
{
string TempPrice, TempCheckNum, TempCriditNum;
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
if(radioButton1.Checked == true)
{
TempPrice = money_price.Text;
TempCheckNum = "0";
TempCriditNum = "0";
}else if(radioButton2.Checked == true)
{
TempPrice = money_price.Text;
TempCheckNum = "0";
TempCriditNum = criditNumber.Text;
}
else
{
TempPrice = money_price.Text;
TempCheckNum = checkNumber.Text;
TempCriditNum = "0";
}
///////////////////////////////split the combo box names
string mainToSplit,id = "";
string[] splited;
mainToSplit = employee_list.SelectedItem.ToString();
splited = mainToSplit.Split('\n');
splited[0] = "" + splited[0].Remove((splited[0].Length-1),1);
command.CommandText = "select id from employee where Ename='" +splited[0]+ "' AND Elastname='" +splited[1]+"'";
OleDbDataReader reader = command.ExecuteReader();
if (reader.Read())
id = reader[0].ToString();
connection.Close();
connection.Open();
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "INSERT INTO realMoney (price,cardnum,checknum,theDate,employeeid,descrip) values(" + Int32.Parse(TempPrice) + "," + Int32.Parse(TempCriditNum) + "," + Int32.Parse(TempCheckNum) + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + Int32.Parse(id) + ",'" + money_descrip.Text + "')";
command2.ExecuteNonQuery();
connection.Close();
addMoneyPanelMes.Text = "با موفقیت ذخیره شد.";
addMoneyPanelMes.ForeColor = Color.Green;
addMoneyPanelMes.Visible = true;
}
catch(OleDbException h)
{
addMoneyPanelMes.Text = "خظا در ارتباط با پایگاه داده.";
addMoneyPanelMes.ForeColor = Color.Red;
addMoneyPanelMes.Visible = true;
}
}
this 2 function will be run successfully but after that i will get the "Parameter is not valid" Exception in this part:
private void timer1_Tick(object sender, EventArgs e)
{
if(pass == 0 || pass == 1)
{
prossespass();
}
DateTime datetime = DateTime.Now;
try
{
time.Text = string.Format("{0:hh:mm:ss}", DateTime.Now); // error here
timesun.Text = datetime.ToString("tt");
}
catch(Exception d)
{ }
}
this is a timer for a clock in my project. so after returning to the main panel that clock is existing in it (make the main panel visible and hide current panel) clock text box cant set and my project crashed.
i dont know what the problem is.
but if i erase this part from the second function that i mentioned:
addMoneyPanelMes.Text = "با موفقیت ذخیره شد.";
addMoneyPanelMes.ForeColor = Color.Green;
addMoneyPanelMes.Visible = true;
or removing insert section in second function above:
connection.Open();
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "INSERT INTO realMoney (price,cardnum,checknum,theDate,employeeid,descrip) values(" + Int32.Parse(TempPrice) + "," + Int32.Parse(TempCriditNum) + "," + Int32.Parse(TempCheckNum) + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + Int32.Parse(id) + ",'" + money_descrip.Text + "')";
command2.ExecuteNonQuery();
connection.Close();
i have other function in other panels that work with database but work great together this is it. thanks for your help.

just turn the timer off:
timer1.Enabled = false;
when enter to each panel and turn it on when come back to main panel:
timer1.Enabled = true;

Related

how to validate log out only once in visual studio c# via access database

Form
Database
I want to make an employee Check in and Out form the check in part is done perfectly.
But for check out the update query allows to edit pre-entered values to change, I don't want already entered values to be able to change afterwards, and only enter Out_time to free cells.
Below is my code:
private void out_btn_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Daily_emp_track set Out_Time='" + time1.Text + "' where Emp_ID=" + id_txt.Text + " ";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("You are out");
}
catch (Exception ex)
{
MessageBox.Show("Entered ID not valid ");
con.Close();
}
}
To prevent the entered value from being changed again and get Out_Time by system instead of inputting manually, you could refer to the following code:
private void out_btn_Click(object sender, EventArgs e)
{
var time = DateTime.Now;
string time1;
if (time.Hour > 12)
{
time1 = time.Hour - 12 + ":" + time.Minute + " PM";
}
else
{
time1 = time.Hour + ":" + time.Minute + " AM";
}
try
{
string OutTime;
con.Open();
OleDbCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT Out_Time FROM Daily_emp_track WHERE Emp_ID='" + id_txt.Text + "'";
OleDbDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
OutTime = reader["Out_Time"].ToString();
if (OutTime != "")
{
MessageBox.Show("Out Time has submitted");
}
else
{
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Daily_emp_track SET Out_Time='" + time1 + "' WHERE Emp_ID='" + id_txt.Text + "'";
cmd.ExecuteNonQuery();
MessageBox.Show("You are out");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Entered ID not valid ");
}
finally
{
con.Close();
}
}

Trouble in C# inventory system update button

I have a problem in the form of my inventory system. Well it worked perfectly when one textbox was involved. But when there are 2 or more textbox involve it shows errors specifically: Truncated incorrect DOUBLE value: 'Knooks and Cranies'.
(Knooks and Cranies is an example of a supplier i inputted.)
I don't really know what's wrong because this is the 1st time I've encountered this error.
here's my code:
namespace SupplyRequestAndInventoryManagementSystem
{
public partial class DI_Assets : Form
{
connection con = new connection();
MySqlCommand cmd;
MySqlDataReader reader;
public DI_Assets()
{
InitializeComponent();
}
//load data from database
private void DI_Assets_Load(object sender, EventArgs e)
{
loadDepartment();
}
//checker
private void ListDelivery_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListDelivery.SelectedItems.Count > 0)
{
ListViewItem itm = ListDelivery.SelectedItems[0];
lblAssetIDChecker.Text = itm.SubItems[4].Text;
}
}
//load data from supplier
private void btnSearch_Click(object sender, EventArgs e)
{
loadtbl();
}
//add button
private void btnAdd_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to add new Delivery Information?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" || txtProdName.Text == "" || txtProdBrand.Text == "" || txtQty.Text == "" || DTPReceived.Text == "")
{
MessageBox.Show("Don't leave blanks!");
}
else
{
con.Close();
cmd = new MySqlCommand("Select * from deliver_mat where Del_MSupplier ='" + SuppNameCombo.Text + "' and Del_MName='" + txtProdName.Text + "' and Del_MBrand ='" + txtProdBrand.Text + "' and Del_MQty= '" + txtQty.Text + "' and Del_MReceived='" + DTPReceived.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
MessageBox.Show("Delivery Information already exist, sepcify a new one!");
}
else
{
addSection();
MessageBox.Show("Delivery Information successfully added!");
loadtbl();
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
}
else
{
MessageBox.Show("Adding new Delivery Information has been cancelled!");
}
}
//update button
private void btnUpdate_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to update the section?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" && txtProdName.Text == "" && txtProdBrand.Text == "" && txtQty.Text == "" && DTPReceived.Text == "")
{
MessageBox.Show("Please choose section to be updated!");
}
else
{
updateSection();
MessageBox.Show("Section has been successfully updated!");
loadtbl();
SuppNameCombo.Text = "";
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
else
{
MessageBox.Show("Updating section has been cancelled!");
}
}
//----------------------------------------------------------------------------------------------
//Retrieving Data from DB to listview
void loadtbl()
{
con.Close();
DataTable table = new DataTable();
cmd = new MySqlCommand("Select * from deliver_assets where Del_ASupplier = '" + SuppNameCombo.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
ListDelivery.Items.Clear();
while (reader.Read())
{
ListViewItem item = new ListViewItem(reader["Del_AName"].ToString());
item.SubItems.Add(reader["Del_ABrand"].ToString());
item.SubItems.Add(reader["Del_AReceived"].ToString());
item.SubItems.Add(reader["Del_AQty"].ToString());
item.SubItems.Add(reader["Del_aID"].ToString());
item.SubItems.Add(reader["Del_ASupplier"].ToString());
ListDelivery.Items.Add(item);
}
}
//Load Data to combo box
void loadDepartment()
{
con.Close();
DataTable table5 = new DataTable();
cmd = new MySqlCommand("Select Supp_Name from supply", con.con);
con.Open();
reader = cmd.ExecuteReader();
table5.Load(reader);
foreach (DataRow row in table5.Rows)
{
SuppNameCombo.Items.Add(row["Supp_Name"]);
}
}
//add function
void addSection()
{
con.Close();
cmd = new MySqlCommand("insert into deliver_assets(Del_AName, Del_ABrand, Del_AReceived, Del_AQty, Del_Asupplier) values('" + txtProdName.Text + "', '" + txtProdBrand.Text + "', '" + DTPReceived.Text + "', '" + txtQty.Text + "', '" + SuppNameCombo.Text + "')", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
//update function
void updateSection()
{
con.Close();
cmd = new MySqlCommand("update deliver_assets set Del_ASupplier ='" + SuppNameCombo.Text + "' and Del_AName ='" + txtProdName.Text + "' and Del_ABrand ='" + txtProdBrand.Text + "' and Del_AQty ='" + txtQty.Text + "' and Del_AReceived ='" + DTPReceived.Text + "' where Del_aID ='" + lblAssetIDChecker.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
}
}
Your code contains many errors that should be avoided in handling a database task:
Use of global variables for disposable object (in particular a
MySqlConnection)
No use of parameters
Incorrect syntax for the Update statement
Use of incorrect methods to Execute insert/update queries
Trying to use a do-it-all method to establish a connection (related
to first)
Thinking that a column with a specific datatype will happily accept a string as its value
To just give an example I will try to rewrite the Update code
//update function
void updateSection()
{
string cmdText = #"update deliver_assets
set Del_ASupplier =#sup.
Del_AName = #name,
Del_ABrand = #brand
Del_AQty = #qty
Del_AReceived = #recv
where Del_aID = #id";
using(MySqlConnection con = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, con))
{
cmd.Parameters.Add("#sup", MySqlDbType.VarChar).Value = SuppNameCombo.Text;
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = txtProdName.Text;
cmd.Parameters.Add("#brand", MySqlDbType.VarChar).Value = txtProdBrand.Text;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = Convert.ToDouble(txtQty.Text);
cmd.Parameters.Add("#recv", MySqlDbType.VarChar).Value = DTPReceived.Text;
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = Convert.ToInt32(lblAssetIDChecker.Text);
con.Open();
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowUpdated > 0)
MessageBox.Show("Record updated");
}
}
Note that I can't be sure about the correct datatype of your columns. You should create the parameter with the DataType compatible for your column changing the MySqlDbType values shown in the example above.

Local database not refreshing after updating data from C#

I'm working with a local database, and it works well, the whole app. The problem is that I'm facing with some annoying things. If I update, or add new data to my local database, I have to close the whole app and start it again so I can see the new data I have entered. Why is it not refreshing and how can I solve it?
Here is how I add data:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label5.Text = "1";
}
else
{
label5.Text = "0";
}
if (radioButton2.Checked)
{
label5.Text = "2";
}
if (textBox1.Text.Length == 0)
{
textBox1.Text = "Fara";
}
if (textBox2.Text.Length == 0)
{
textBox2.Text = "0";
}
if (textBox3.Text.Length == 0)
{
textBox3.Text = "0";
}
if (numeTextBox.TextLength != 0 && prenumeTextBox.TextLength != 0)
{
var connString = (#"Data Source=" + Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\Angajati.sdf");
//var connString = #"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
using (var conn = new SqlCeConnection(connString))
{
try
{
//deschide conectiunea in db
conn.Open();
//creaza comanda in SQL Server CE
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
cmd.CommandText = "INSERT INTO info(Nume, Prenume, Data, Proiect, Schimburi, Poza, Acord, Baza) VALUES('" + numeTextBox.Text.Trim() + "', '" + prenumeTextBox.Text.Trim() + "', '" + dateTimePicker1.Value.ToShortDateString() + "', '" + textBox1.Text.Trim() + "', " + label5.Text + " , #Poza, " + textBox2.Text + ", " + textBox3.Text + ");";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Salvat cu succes!");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
numeTextBox.Clear();
prenumeTextBox.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Trebuie sa completezi campurile inainte de a salva!");
}
}
Here is how I update it:
private void button1_Click_1(object sender, EventArgs e)
{
//var connString = (#"Data Source= |DataDirectory|\Angajati.sdf");
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
var query = "UPDATE info SET Nume='" + textBox5.Text + "' , Prenume='" + textBox4.Text + "' , Data='" + dateTimePicker1.Value.ToShortDateString() + "', Proiect='" + textBox1.Text + "', Schimburi='" + label10.Text + "', Poza=#Poza, Acord='" + textBox2.Text + "', Baza='" + textBox3.Text + "' WHERE Nume='" + textBox5.Text + "' AND Prenume='" + textBox4.Text + "'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Here is how I search data:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length != 0)
{
var numePrenume = textBox1.Text.Trim().Split(' ');
if (numePrenume.Count() > 1)
{
var nume = numePrenume[0];
var prenume = numePrenume[1];
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT COUNT(*) FROM info WHERE Nume='" + nume + "' AND Prenume='" + prenume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
//checks if there's the searched record is in the db.
int infoCount = (int)command.ExecuteScalar();
if (infoCount > 0)
{
Info form = new Info(nume, prenume);
form.Show();
}
else
{
MessageBox.Show("Nu exista un angajat cu acest nume");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Nu ai introdus prenumele");
}
}
else
{
MessageBox.Show("Nu ai introdus nici un nume!");
}
}
I have solved this problem by changing the path to the db, it was something wrong at it, and by creating a refresh function for my gridView called after the insert. Bellow is the code for the solution:
Getting the path like this now:
string startPath = Application.StartupPath;
var filepath = startPath + "\\" + "Grupe.sdf";
var connString = (#"Data Source=" + filepath +"");
The refresh function:
public void refresh()
{
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM copii";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}

Ozeki is not returning other records

I'm doing an Ozeki Messenger Project using C#. I want to retrieve more than one record from the table. Its returning me the first record only...
Here's my code. Any Idea what am doing wrong guys?
protected void Page_Load(object sender, EventArgs e)
{
try
{
String x;
String y;
String z;
String SenderNumber, receiverNumber, message;
SenderNumber = Request.QueryString.Get("sender");
receiverNumber = Request.QueryString.Get("receiver");
message = Request.QueryString.Get("msg");
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
SqlDataReader reader;
connection.ConnectionString = Constring;
command.Connection = connection;
command.CommandText = "SELECT P_Name, P_Parking FROM tblPharmacy Where Code = '" + message + "'" ;
connection.Open();
reader = command.ExecuteReader();
String data = "";
while (reader.Read())
{
x = reader["P_Name"].ToString();
y = reader["P_Parking"].ToString();
data += x + " " + y + " - ";
Response.Redirect("http://localhost:9333/ozeki?login=admin&password=xxxxxx&action=sendMessage&messagetype=SMS:TEXT&recepient=" + SenderNumber + " &messageData= " + data);
}
reader.Close();
connection.Close();
}
catch (Exception)
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
String x;
String y;
String z;
String SenderNumber, receiverNumber, message;
SenderNumber = Request.QueryString.Get("sender");
receiverNumber = Request.QueryString.Get("receiver");
message = Request.QueryString.Get("msg");
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
SqlDataReader reader;
connection.ConnectionString = Constring;
command.Connection = connection;
command.CommandText = "SELECT P_Name, P_Parking FROM tblPharmacy Where Code = '" + message + "'" ;
connection.Open();
reader = command.ExecuteReader();
String data = "";
while (reader.Read())
{
x = reader["P_Name"].ToString();
y = reader["P_Parking"].ToString();
data += x + " " + y + " - ";
}
Response.Redirect("http://localhost:9333/ozeki?login=admin&password=xxxxxx&action=sendMessage&messagetype=SMS:TEXT&recepient=" + SenderNumber + " &messageData= " + data);
reader.Close();
connection.Close();
}
catch (Exception)
{
}
}
I got The Answer Myself.. LOL. The Response.Redirect should be outside the While Loop. It Works Just fine :D

why does checkchanged event does not fire on uncheck of checkbox in asp.net

Part of attendance tracker application which displays subjects of user and lets him mark his own attendance.
With enableviewstate="true", the checkbox does not get unchecked and the checkchanged event does not execute.
namespace portal
{
public partial class tracker : System.Web.UI.Page
{
String[] split; string day;
protected void Page_Load(object sender, EventArgs e)
{
/* if (Session["uname"] == null)
{
Response.Redirect("Firstpage.aspx");
}*/
String[] split = new String[16];
DateTime d1 = DateTime.Today;
string month = d1.ToString("MMMM");
Lblmonth.Text = month;
String userid = Session["uname"].ToString();
SqlConnection con2 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd2 = new SqlCommand("select sbranch ,syear from studdetails where userid=#userid ", con2);
cmd2.Parameters.AddWithValue("userid", userid);
String branch = "", year = "";
SqlDataReader rdr2 = null;
con2.Open();
rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
branch = rdr2["sbranch"].ToString();
year = rdr2["syear"].ToString();
}
con2.Close();
int sem = 0;
switch (year)
{
case "B.E": sem = 8;
break;
case "T.E": sem = 6;
break;
case "S.E": sem = 4;
break;
case "F.E": sem = 2;
break;
default: sem = 2;
break;
}
int tempmonth = (int)(d1.Month);
if (tempmonth > 6)
sem = sem - 1;
SqlConnection con3 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd3 = new SqlCommand("select subject from subjecttable where department=#dept and semester=#sem ", con3);
cmd3.Parameters.AddWithValue("dept", branch);
cmd3.Parameters.AddWithValue("sem", sem);
con3.Open();
SqlDataReader rdr3 = null;
rdr3 = cmd3.ExecuteReader();
string subject = "";
while (rdr3.Read())
{
subject = rdr3["subject"].ToString();
}
con3.Close();
Char[] separator = new Char[] { ',' };
String[] subsplit = subject.Split(separator);
int size = subsplit.Length;
switch (size)
{
case 6: subj6.Text = subsplit[5];
goto case 5;
case 5: subj5.Text = subsplit[4];
goto case 4;
case 4: subj4.Text = subsplit[3];
goto case 3;
case 3: subj3.Text = subsplit[2];
goto case 2;
case 2: subj2.Text = subsplit[1];
goto case 1;
case 1: subj1.Text = subsplit[0];
break; ;
}
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsWeekend)
{
e.Cell.BackColor = System.Drawing.Color.DarkBlue;
}
else
{
e.Cell.BackColor = System.Drawing.Color.LightBlue;
}
SelectedDatesCollection dates = Calendar1.SelectedDates;
DateTime toDay = DateTime.Today;
string days = toDay.ToLongDateString();
Labelday.Text = days;
Char[] separator = new Char[] { ',' };
String[] split1 = days.Split(separator);
day = split1[0];
Session["day"] = Calendar1.SelectedDate.ToShortDateString();
if (dates.Count > 0)
{
Labelday.Text = dates[0].ToLongDateString() + "<br />";
String temp = Labelday.Text;
split1 = temp.Split(separator);
day = split1[0];
}
if (!(day.Equals("Saturday") || day.Equals("Sunday")))
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
string cla = Convert.ToString(Session["uclass"]);
SqlCommand cmd = new SqlCommand("select " + day + " from studtimetable where class = #class ", con);
con.Open();
cmd.Parameters.AddWithValue("class", cla);
SqlDataReader rdr = null;
String tt = "";
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
tt = rdr[day].ToString();
}
con.Close();
split = tt.Split(separator);
int size = split.Length;
lbltime.Visible = true;
Lblsubj.Visible = true;
Lblatt.Visible = true;
switch (size)
{
case 16: Label15.Text = split[15];
Session["l15"] = Label15.Text;
Label14.Text = split[14];
CheckBox8.Visible = true;
goto case 14;
case 14: Label13.Text = split[13];
Session["l13"] = Label13.Text;
Label12.Text = split[12];
CheckBox7.Visible = true;
goto case 12;
case 12: Label11.Text = split[11];
Session["l11"] = Label11.Text;
Label10.Text = split[10];
CheckBox6.Visible = true;
goto case 10;
case 10: Label9.Text = split[9];
Session["l9"] = Label9.Text;
Label8.Text = split[8];
CheckBox5.Visible = true;
goto case 8;
case 8: Label7.Text = split[7];
Session["l7"] = Label7.Text;
Label6.Text = split[6];
CheckBox4.Visible = true;
goto case 6;
case 6: Label5.Text = split[5];
Session["l5"] = Label5.Text;
Label4.Text = split[4];
CheckBox3.Visible = true;
goto case 4;
case 4: Label3.Text = split[3];
Session["l3"] = Label3.Text;
Label2.Text = split[2];
CheckBox2.Visible = true;
goto case 2;
case 2: Label1.Text = split[1];
Session["l1"] = Label1.Text;
Label0.Text = split[0];
CheckBox1.Visible = true;
break;
}
}
else
{
lbltime.Text = "Enjoy weekend";
lbltime.Visible = true;
}
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
CheckBox1.Checked = false;
CheckBox2.Checked = false;
CheckBox3.Checked = false;
CheckBox4.Checked = false;
CheckBox5.Checked = false;
CheckBox6.Checked = false;
CheckBox7.Checked = false;
CheckBox8.Checked = false;
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
string sub = Session["l1"].ToString();
string userid = Session["uname"].ToString();
string date = Session["day"].ToString();
string tempclass = Session["uclass"].ToString();
SqlConnection con4 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd4 = new SqlCommand("insert into " + tempclass + "track values ('" + userid + "','" + sub + "','" + date + "')", con4);
con4.Open();
cmd4.ExecuteNonQuery();
con4.Close();
}
else
{
Label18.Text = "uncheck";//temporary to check if this block executes
}
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox2.Checked == true)
{
string sub = Session["l3"].ToString();
string userid = Session["uname"].ToString();
string date = Session["day"].ToString();
string tempclass = Session["uclass"].ToString();
SqlConnection con4 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd4 = new SqlCommand("insert into " + tempclass + "track values ('" + userid + "','" + sub + "','" + date + "')", con4);
con4.Open();
cmd4.ExecuteNonQuery();
con4.Close();
//Response.Redirect("tracker.aspx");
}
else
{
}
}
protected void CheckBox3_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox3.Checked == true)
{
string sub = Session["l5"].ToString();
string userid = Session["uname"].ToString();
string date = Session["day"].ToString();
string tempclass = Session["uclass"].ToString();
SqlConnection con4 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd4 = new SqlCommand("insert into " + tempclass + "track values ('" + userid + "','" + sub + "','" + date + "')", con4);
con4.Open();
cmd4.ExecuteNonQuery();
con4.Close();
//Response.Redirect("tracker.aspx");
}
else
{
}
}
protected void CheckBox4_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox4.Checked == true)
{
string sub = Session["l7"].ToString();
string userid = Session["uname"].ToString();
string date = Session["day"].ToString();
string tempclass = Session["uclass"].ToString();
SqlConnection con4 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd4 = new SqlCommand("insert into " + tempclass + "track values ('" + userid + "','" + sub + "','" + date + "')", con4);
con4.Open();
cmd4.ExecuteNonQuery();
con4.Close();
//Response.Redirect("tracker.aspx");
}
else
{
}
}
protected void CheckBox5_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox5.Checked == true)
{
string sub = Session["l9"].ToString();
string userid = Session["uname"].ToString();
string date = Session["day"].ToString();
string tempclass = Session["uclass"].ToString();
SqlConnection con4 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd4 = new SqlCommand("insert into " + tempclass + "track values ('" + userid + "','" + sub + "','" + date + "')", con4);
con4.Open();
cmd4.ExecuteNonQuery();
con4.Close();
//Response.Redirect("tracker.aspx");
}
else
{
}
}
protected void CheckBox6_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox6.Checked == true)
{
string sub = Session["l11"].ToString();
string userid = Session["uname"].ToString();
string date = Session["day"].ToString();
string tempclass = Session["uclass"].ToString();
SqlConnection con4 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd4 = new SqlCommand("insert into " + tempclass + "track values ('" + userid + "','" + sub + "','" + date + "')", con4);
con4.Open();
cmd4.ExecuteNonQuery();
con4.Close();
//Response.Redirect("tracker.aspx");
}
else
{
}
}
protected void CheckBox7_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox7.Checked == true)
{
string sub = Session["l13"].ToString();
string userid = Session["uname"].ToString();
string date = Session["day"].ToString();
string tempclass = Session["uclass"].ToString();
SqlConnection con4 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd4 = new SqlCommand("insert into " + tempclass + "track values ('" + userid + "','" + sub + "','" + date + "')", con4);
con4.Open();
cmd4.ExecuteNonQuery();
con4.Close();
//Response.Redirect("tracker.aspx");
}
else
{
}
}
protected void CheckBox8_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox8.Checked == true)
{
string sub = Session["l15"].ToString();
string userid = Session["uname"].ToString();
string date = Session["day"].ToString();
string tempclass = Session["uclass"].ToString();
SqlConnection con4 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\mmm\portal\App_Data\student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd4 = new SqlCommand("insert into " + tempclass + "track values ('" + userid + "','" + sub + "','" + date + "')", con4);
con4.Open();
cmd4.ExecuteNonQuery();
con4.Close();
//Response.Redirect("tracker.aspx");
}
else
{
}
}
}
}
From MSDN (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.oncheckedchanged.aspx):
A CheckBox control must persist some values between posts to the
server for this event to work correctly. Be sure that view state is
enabled for this control.
When (html) checkbox is not checked and form is submitted, no value would be passed back to server, that's why you need to enable ViewState for this control, so ASP.NET would keep track of the state (checked/unchecked).
Remove EnableViewState="false" and it should work fine
Thank you everyone for your consideration.
Problem finally solved. On uncheck event by user the checkchanged method was not executing because 1)with autopostback on, uncheck caused execution of page_load method, which in turn caused the checkbox.visible= false, so checkchanged didnot executed, and then calendar render method caused checkbox.visible =true with the previous state(viewstate=true) ie checked state.
special thnx to floremin and loren.
Solution: you should set-> EnableViewstate = True, ViewStateMode = Enabled, Autopostback = true. that's all. this works me.

Categories