how do i retain values from pages in asp.net - asp.net

I need help with "retaining" values from one page to another example i answered the first page and proceed to the 2nd if i click "previous page" how can i keep my answers there.
Below are my codes:
protected void Button1_Click(object sender, EventArgs e)
{
//string sesrbl1;
string selectedvalue = RadioButtonList2.SelectedValue.ToString();
string selectedvalue2 = RadioButtonList4.SelectedValue.ToString();
string selectedvalue3 = RadioButtonList6.SelectedValue.ToString();
string selectedvalue4 = RadioButtonList8.SelectedValue.ToString();
string selectedvalue5 = RadioButtonList14.SelectedValue.ToString();
string selectedvalue6 = RadioButtonList11.SelectedValue.ToString();
bool risk;
SqlCommand cmd = new SqlCommand();
SqlConnection sqlcon = new SqlConnection("Data Source=DBASE;Initial Catalog=TumorRegistry;User ID=sa");
try
{
//Session["rb1"] = RadioButtonList12.SelectedValue;
//Session["rb2"] = RadioButtonList3.SelectedValue;
//Session["rb3"] = RadioButtonList5.SelectedValue;
//Session["rb4"] = RadioButtonList7.SelectedValue;
//Session["rb5"] = RadioButtonList13.SelectedValue;
if (RadioButtonList12.SelectedItem.Text== "FALSE")
{
if (bool.TryParse("False", out risk))
{
risk = false;
Session["rb1"] = risk;
}
}
if (RadioButtonList12.SelectedItem.Text == "TRUE")
{
if (bool.TryParse(RadioButtonList12.SelectedItem.Text, out risk))
{
risk = true;
Session["rb1"] = risk;
}
}
if (RadioButtonList3.SelectedItem.Text == "FALSE")
{
if (bool.TryParse(RadioButtonList3.SelectedItem.Text, out risk))
{
risk = false;
Session["rb2"] = risk;
}
}
if (RadioButtonList3.SelectedItem.Text== "TRUE")
{
if (bool.TryParse(RadioButtonList3.SelectedItem.Text, out risk))
{
risk = true;
Session["rb2"] = risk;
}
}
if (RadioButtonList5.SelectedItem.Text == "FALSE")
{
if (bool.TryParse(RadioButtonList5.SelectedItem.Text, out risk))
{
risk = false;
Session["rb3"] = risk;
}
}
if (RadioButtonList5.SelectedItem.Text == "TRUE")
{
if (bool.TryParse(RadioButtonList5.SelectedItem.Text, out risk))
{
risk = true;
Session["rb3"] = risk;
}
}
if (RadioButtonList7.SelectedItem.Text == "FALSE")
{
if (bool.TryParse(RadioButtonList7.SelectedItem.Text, out risk))
{
risk = false;
Session["rb4"] = risk;
}
}
if (RadioButtonList7.SelectedItem.Text == "TRUE")
{
if (bool.TryParse(RadioButtonList7.SelectedItem.Text, out risk))
{
risk = true;
Session["rb4"] = risk;
}
}
if (RadioButtonList13.SelectedItem.Text == "FALSE")
{
if (bool.TryParse(RadioButtonList13.SelectedItem.Text, out risk))
{
risk = false;
Session["rb5"] = risk;
}
}
if (RadioButtonList13.SelectedItem.Text == "TRUE")
{
if (bool.TryParse(RadioButtonList13.SelectedItem.Text, out risk))
{
risk = true;
Session["rb5"] = risk;
}
}
if (selectedvalue.ToString() == "0")
{
selectedvalue = null;
}
else if (selectedvalue2.ToString() == "0")
{
selectedvalue2 = null;
}
else if (selectedvalue3.ToString() == "0")
{
selectedvalue3 = null;
}
else if (selectedvalue4.ToString() == "0")
{
selectedvalue4 = null;
}
else if (selectedvalue5.ToString() == "0")
{
selectedvalue6 = null;
}
//Session["rb1"] = RadioButtonList12.SelectedValue;
//Session["rb2"] = RadioButtonList3.SelectedValue;
//Session["rb3"] = RadioButtonList5.SelectedValue;
//Session["rb4"] = RadioButtonList7.SelectedValue;
//Session["rb5"] = RadioButtonList13.SelectedValue;
//sending values to the submit button next page
Session["Holdtextbox1"] = RadioButtonList2.SelectedValue.ToString();
Session["Holdtextbox2"] = RadioButtonList4.SelectedValue.ToString();
Session["Holdtextbox3"] = RadioButtonList6.SelectedValue.ToString();
Session["Holdtextbox4"] = RadioButtonList8.SelectedValue.ToString();
Session["Holdtextbox5"] = RadioButtonList14.SelectedValue.ToString();
Session["Holdtextbox6"] = RadioButtonList11.SelectedValue.ToString();
selectedvalue = Session["Holdtextbox1"].ToString();
selectedvalue2 = Session["Holdtextbox2"].ToString();
selectedvalue3 = Session["Holdtextbox3"].ToString();
selectedvalue4 = Session["Holdtextbox4"].ToString();
selectedvalue5 = Session["Holdtextbox5"].ToString();
selectedvalue6 = Session["Holdtextbox6"].ToString();
Response.Redirect("WebForm1.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
that's for the first page
here's for the 2nd page i have 2 buttons button 1 and 2
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
////Button1.Attributes.Add("onClick", "javascript:history.back(); return false;");
// Response.Redirect("Default.aspx");
}
public void SaveRecord()
{
try
{
Holdtextbox1.Text = Session["Holdtextbox1"].ToString();
Holdtextbox2.Text = Session["Holdtextbox2"].ToString();
Holdtextbox3.Text = Session["Holdtextbox3"].ToString();
Holdtextbox4.Text = Session["Holdtextbox4"].ToString();
Holdtextbox5.Text = Session["Holdtextbox5"].ToString();
Holdtextbox6.Text = Session["Holdtextbox6"].ToString();
sqlcon.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlcon;
SqlDataAdapter DA = new SqlDataAdapter();
// string SqlInsert = "Insert into tbTRcBase (HPN,ISH, Asthma, DM, OtherCo,HPNTreatment, ISHTreatment,AsthmaTreatment, DMTreatment, OtherCoTreatment,SecondHandSmoke,Smoker, StopSmoking , Occupation , CancerFamilyHistory, FamilyWithCancer,ParentWithCancer) values ('" + bitsess.Text + "','" + bitsess2.Text + "','" + bitsess3.Text + "','" + bitsess4.Text + "','" + bitsess5.Text + "','" + Holdtextbox1.Text + "','" + Holdtextbox2.Text + "','" + Holdtextbox3.Text + "','" + Holdtextbox4.Text + "','" + Holdtextbox5.Text + "','" + Holdtextbox6.Text + "','" + rb1.SelectedValue.ToString() + "','" + rb2.SelectedValue.ToString() + "','" + cb1.Text + "','" + rb3.Text + "','" + cb2.Text + "','" + rb4.Text + "')";
string SqlInsert = "Insert into tbTRcBase (HPN,ISH, Asthma, DM, OtherCo,HPNTreatment, ISHTreatment,AsthmaTreatment, DMTreatment, OtherCoTreatment,SecondHandSmoke,Smoker, StopSmoking , Occupation , CancerFamilyHistory, FamilyWithCancer,ParentWithCancer) values ('" + Session["rb1"] + "','" + Session["rb2"] + "','" + Session["rb3"] + "','" + Session["rb4"] + "','" + Session["rb5"] + "','" + Holdtextbox1.Text + "','" + Holdtextbox2.Text + "','" + Holdtextbox3.Text + "','" + Holdtextbox4.Text + "','" + Holdtextbox5.Text + "','" + Holdtextbox6.Text + "','" + rb1.SelectedValue.ToString() + "','" + rb2.SelectedValue.ToString() + "','" + cb1.Text + "','" + rb3.Text + "','" + cb2.Text + "','" + rb4.Text + "')";
// string SqlInsert = "Insert into tbTRcBase (HPN, HPNTreatment) values ('" + Session["rb1"] + "','" + Holdtextbox1.Text + "')";
DA = new SqlDataAdapter(SqlInsert, sqlcon);
DataTable dt = new DataTable();
DA.Fill(dt);
sqlcon.Close();
Response.Write("<script language='javascript'>alert('" + " Data has been saved " + "')</script>");
}
catch (Exception e)
{
Response.Write("<script language='javascript'>alert('" + e.Message + "')</script>");
}
}

For retaining the values on the previous page, you would have to make use of those Session variables that you have stored on the same page before you pass them onto the next page.
On the Page_Load event of the previous page, make a function that just binds the respective controls based on the values of those Session variables.
Something like this :
public void BindData()
{
Holdtextbox1.Text = Session["Holdtextbox1"].ToString();
.
.
.
//all your controls and the Session values.
}
Hope this helps.

Related

How to declare scalar variable?

I get this error:
System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#refSlips".'
Code:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand aaa = new SqlCommand("INSERT INTO ConsultationTB VALUES('" + consultationTb.Text + "','" + dateTb.Text + "','" + bodytempTb.Text + "','" + paccodeTb.Text + "', #refSlips ", con);
string RadButt = string.Empty;
if (ForAdmission.Checked)
{
RadButt = "For Admission";
}
else if (ForLabTest.Checked)
{
RadButt = "For Laboratory Test";
}
else if (BothRb.Checked)
{
RadButt = "Both";
}
else if (NotAppRb.Checked)
{
RadButt = "Not Applicable";
}
con.Open();
aaa.ExecuteNonQuery();
con.Close();
getCONNO();
ForAdmission.Checked = false;
ForLabTest.Checked = false;
BothRb.Checked = false;
NotAppRb.Checked = false;
[ + "', #refSlips)" , con);] the problem was the parenthesis after refslips.

i hava 1 error when i do web login by asp.net

my ideas: i select id(max) in table users to write table Userlogin. I get error:
'Conversion failed when converting the varchar value to data type int.'
SELECT idUser
FROM Users
WHERE idUser = (SELECT MAX(idUser) FROM Users)
how to fix error? thank you.
img error: Mycode, Myerror
mycode:
`` `using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace Web_tintuc2
{
public partial class DangKi : System.Web.UI.Page
{
private string connectString = #"Data Source=DESKTOP-
RT3QMVS; Initial Catalog =web_tintuc; Integrated Security=True;";
SqlConnection sql_connect;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_thoat_Click(object sender, EventArgs
e)
{
Response.Redirect("Trangchu.aspx");
//Response.Write("<script>alert('Hello');</script>");
}
protected void btn_dangki_Click(object sender, EventArgs
e)
{
sql_connect = new SqlConnection(connectString);
sql_connect.Open();
string username = txt_username.Text;
string phone = txt_Phone.Text;
string password = txt_password.Text;
string name = txt_name.Text;
string ngaysinh = txt_brithday.Text;
string diachi = txt_diachi.Text;
string email = txt_Email.Text;
DateTime aDateTime = DateTime.Now;
string ngaydangki = aDateTime.ToString("yyyy-MM-dd HH:mm:ss"); // fomat kiểu ngày thánh trong sql server
string active = "Actived";
string IdGruop = "2";
string gioitinh1 = "Nam";
String gioitinh2 = "Nữ";
string sql_check = "select Username from Userlogin
where Username='" + username + "' ";
SqlCommand sql1 = new SqlCommand(sql_check,
sql_connect);
SqlDataReader read = sql1.ExecuteReader();
if (read.Read() == true)
Lb_thongbao.Text = "Username đã tồn tại";
read.Close();
if (Radio_nam.Checked == true)
{
string sql_insert_toUser = " insert into Users(HoTen,Diachi,Email,Dienthoai,gioitinh,ngaysinh,idGroup,ngaydangki,active ) values('" + name + "','" + diachi + "','" + diachi + "','" + email + "','" + phone + "','" + gioitinh1 + "','" + ngaysinh + "','" + IdGruop + "','" + ngaydangki + "','" + active + "')";
SqlCommand sqlcommand1 = new
SqlCommand(sql_insert_toUser, sql_connect);
sqlcommand1.ExecuteNonQuery();
string sql_id_users = "Select top 1 idUser from
Users order by idUser desc";
string sql_insert_to_UserLogin = "insert into
Userlogin(Username,Password,idUser) values('" + username + "','" +
password + "','" + sql_id_users + "') ";
SqlCommand sqlCommand2 = new
SqlCommand(sql_insert_to_UserLogin, sql_connect);
sqlCommand2.ExecuteNonQuery();
}
else if (Radio_nu.Checked == true)
{
string sql_insert_toUser = " insert into Users(HoTen,Diachi,Email,Dienthoai,gioitinh,ngaysinh,idGroup,ngaydangki,active )values('" + name + "','" + diachi + "','" + email + "','" + phone + "','" + gioitinh2 + "','" + ngaysinh + "','" + IdGruop + "','" + ngaydangki + "','" + active + "')";
SqlCommand sqlcommand1 = new SqlCommand(sql_insert_toUser, sql_connect);
sqlcommand1.ExecuteNonQuery();
string sql_id_users = " SELECT idUser FROM Users
WHERE idUser = (SELECT MAX(idUser) FROM Users) ";
string sql_insert_to_UserLogin = "insert into
Userlogin(Username,Password,idUser) values('" + username + "','" +
password + "','"+sql_id_users+"') ";
SqlCommand sqlCommand_2 = new
SqlCommand(sql_insert_to_UserLogin, sql_connect);
sqlCommand_2.ExecuteNonQuery();
}
}
}
}'' '
Your error is coming from your insert statement (line 62). You have single quotes around the variable sql_id_users. Remove the single quotes. It's treating the value as varchar since you have it enclosed in single quotes but it expects an integer.
Suggestion: When you post, please post your code as text and not an image.

Issue while working in server asp.net web application

I have an web application name travel. Every thing is working fine while working in test database even if i connect it to live database it works fine in local server but not working in live server.for ex.. I have a grid view to show the details where i can insert,delete,update and view but its working fine in my local server but in live server, my file are updating for the first time but if i try to update for the second time its not working. I have no idea whats happening can any one help me in this.
travel.cs
protected void gv_food_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gv_food.ShowFooter = true;
gv_food.EditIndex = -1;
Loadgv_food();
}
protected void gv_food_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
AddConfirmDelete((GridView)sender, e);
hdnAmtvalue.Value = Convert.ToString((e.Row.RowIndex + 1) + (gv_food.PageSize * gv_food.PageIndex));
hdnAmtvalue.Value = Convert.ToString(Convert.ToInt16(hdnAmtvalue.Value) + 3);
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList drp = (DropDownList)e.Row.FindControl("drpfood");
sqlq = "SELECT ':Select:' AS DESCRIPTION,0 AS regionid FROM dual";
sqlq += "\n UNION";
sqlq += "\n select DESCRIPTION,regionid from regionmaster";
ds = db.fillDataset(sqlq);
drp.DataSource = ds.Tables[0];
drp.DataTextField = "description";
drp.DataValueField = "regionid";
drp.DataBind();
DropDownList drpC = (DropDownList)e.Row.FindControl("drp_currency");
sqlq = "SELECT 0 AS CURRENCYID,':Select:' AS DESCRIPTION FROM dual";
sqlq += "\n UNION";
sqlq += "\n select CURRENCYID,DESCRIPTION from currencymaster";
ds1 = db.fillDataset(sqlq);
drpC.DataSource = ds1.Tables[0];
drpC.DataTextField = "description";
drpC.DataValueField = "currencyid";
drpC.DataBind();
drpC.SelectedIndex = 2;
Load_CurrencyRate();
DropDownList ddlcurrency = (DropDownList)e.Row.FindControl("drp_currency");
int foodamt = Convert.ToInt32(hdnAmtvalue.Value);
TextBox ticketamount = (TextBox)e.Row.FindControl("txtamount");
TextBox inrate = (TextBox)e.Row.FindControl("txt_inrrate");
TextBox dollarrate = (TextBox)e.Row.FindControl("txt_dollarrate");
TextBox inramount = (TextBox)e.Row.FindControl("txt_inramount");
TextBox dollaramount = (TextBox)e.Row.FindControl("txt_dollaramount");
TextBox txtdate = (TextBox)e.Row.FindControl("txtfromdate");
ticketamount.Attributes.Add("onkeypress", "return chkNumber()");
dollarrate.Attributes.Add("onkeypress", "return chkNumber()");
inrate.Attributes.Add("onkeypress", "return chkNumber()");
ticketamount.Attributes.Add("ontextchange", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
ddlcurrency.Attributes.Add("onchange", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
ticketamount.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
inrate.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
dollarrate.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
inramount.Attributes.Add("readonly", "readonly");
dollaramount.Attributes.Add("readonly", "readonly");
txtdate.Attributes.Add("readonly", "readonly");
//inrate.Text = hdnAdvInrRate.Value.ToString();
inrate.Text = hdnAdvUsdRate.Value.ToString();
dollarrate.Text = hdnAdvUsdRate.Value.ToString();
//ddlcurrency.SelectedIndex = ddlcurrency.Items.IndexOf(ddlcurrency.Items.FindByText(hdnAdvCurrency.Value));
drp.SelectedIndex = drp.Items.IndexOf(drp.Items.FindByText(hdnRegion.Value));
}
}
protected void gv_food_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
sql = "delete from tmpintfoodexpenses where detailid=" + gv_food.DataKeys[e.RowIndex].Values[0].ToString() + "";
db.Executecommand(sql);
gv_food.EditIndex = -1;
gv_food.ShowFooter = true;
Loadgv_food();
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Successfully deleted');</script>");
lblFoodException.ForeColor = System.Drawing.Color.Green;
lblFoodException.Text = "* Successfully deleted";
}
protected void gv_food_RowEditing(object sender, GridViewEditEventArgs e)
{
lblFoodException.Text = string.Empty;
try
{
gv_food.ShowFooter = false;
gv_food.EditIndex = e.NewEditIndex;
Loadgv_food();
//changes made on 25/jan/2012
DropDownList drp1 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEhr1");
DropDownList drp2 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEmin1");
DropDownList drp3 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEahr1");
DropDownList drp4 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEamin1");
sql = "select ARRIVALTIME,DEPATURETIME from tmpintfoodexpenses where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
//ds1 = db.fillDataset(sql);
DataTable dt = new DataTable();
dt = db.fillTable(sql);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["DEPATURETIME"].ToString().Contains(":"))
{
string[] _dhhmm = dt.Rows[0]["DEPATURETIME"].ToString().Trim().Split(new char[] { ':' });
if (_dhhmm[0].Trim() != null)
{
drp1.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_dhhmm[0].ToString()));
drp2.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_dhhmm[1].ToString()));
}
if (dt.Rows[0]["ARRIVALTIME"].ToString().Contains(":"))
{
string[] _ahhmm = dt.Rows[0]["ARRIVALTIME"].ToString().Trim().Split(new char[] { ':' });
if (_ahhmm[0].Trim() != null)
{
drp3.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_ahhmm[0].ToString()));
drp4.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_ahhmm[1].ToString()));
}
}
}
}
//End
sql = "select currencydescription,foodorperdiems from tmpintfoodexpenses where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds1 = db.fillDataset(sql);
currflag = ds1.Tables[0].Rows[0].ItemArray[0].ToString();
DropDownList drp = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpefood");
sql = "SELECT ':Select:' AS DESCRIPTION,0 AS regionid FROM dual";
sql += "\n UNION";
sql += "\n select description,regionid from regionmaster";
setDataSource(drp, sql);
DropDownList ddlFood = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("ddlFoodOrPerdiems");
ddlFood.SelectedValue = ds1.Tables[0].Rows[0].ItemArray[1].ToString();
Label lblregion = (Label)gv_food.Rows[e.NewEditIndex].FindControl("lblf");
lblregion.Visible = false;
drp.SelectedIndex = (drp.Items.IndexOf(drp.Items.FindByText(lblregion.Text.ToString())));
DropDownList drpC = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drp_ecurrency");
sqlq = "SELECT 0 AS CURRENCYID,':Select:' AS DESCRIPTION FROM dual";
sqlq += "\n UNION";
sqlq += "\n select CURRENCYID,DESCRIPTION from currencymaster";
ds1 = db.fillDataset(sqlq);
drpC.DataSource = ds1.Tables[0];
drpC.DataTextField = "description";
drpC.DataValueField = "currencyid";
drpC.DataBind();
drpC.SelectedIndex = drpC.Items.IndexOf(drpC.Items.FindByText(currflag));
indexrow = gv_food.Rows[e.NewEditIndex].RowIndex.ToString();
rowindex = int.Parse(indexrow);
rowindex = rowindex + 2;
DropDownList ddlcurrency = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drp_ecurrency");
TextBox ticketamount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txtUamount");
TextBox inrate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_einrrate");
TextBox dollarrate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_edollarrate");
TextBox inramount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_einramount");
TextBox dollaramount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_edollaramount");
TextBox txtdate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txtUfromdate");
ticketamount.Attributes.Add("onkeypress", "return chkNumber()");
dollarrate.Attributes.Add("onkeypress", "return chkNumber()");
inrate.Attributes.Add("onkeypress", "return chkNumber()");
ddlcurrency.Attributes.Add("onchange", "Calculatefoodedit(" + rowindex + ")");
ticketamount.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
inrate.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
dollarrate.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
inramount.Attributes.Add("readonly", "readonly");
dollaramount.Attributes.Add("readonly", "readonly");
txtdate.Attributes.Add("readonly", "readonly");
}
catch (Exception ex)
{
}
}
protected void gv_food_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
indexrow = "";
rowindex = 0;
GridViewRow row1 = gv_food.Rows[e.RowIndex];
TextBox tfromdate = row1.FindControl("txtUfromdate") as TextBox;
TextBox ttodate = row1.FindControl("txtUtodate") as TextBox;
DropDownList ddlfood = (DropDownList)row1.FindControl("ddlFoodOrPerdiems");
DropDownList ddl = (DropDownList)row1.FindControl("drpefood");
TextBox txtdescription = row1.FindControl("txtUdescription") as TextBox;
TextBox txtreference = row1.FindControl("txtUreference") as TextBox;
TextBox tAmt = row1.FindControl("txtUAmount") as TextBox;
//DropDownList drpccy = (DropDownList)row1.FindControl("drpEccy") as DropDownList;
Label tid = row1.FindControl("lblEid") as Label;
DropDownList drpccy = (DropDownList)row1.FindControl("drpEccy") as DropDownList;
DropDownList eddl_curr = (DropDownList)row1.FindControl("drp_ecurrency");
TextBox edcurrentrate = (TextBox)row1.FindControl("txt_edollarrate");
TextBox edamount = (TextBox)row1.FindControl("txt_edollaramount");
TextBox eicurrentrate = (TextBox)row1.FindControl("txt_einrrate");
TextBox eiamount = (TextBox)row1.FindControl("txt_einramount");
//changes made on 25/jan/2012
TextBox txtENoOfDays = row1.FindControl("txtENoOfDays") as TextBox;
DropDownList drpEhr1 = row1.FindControl("drpEhr1") as DropDownList;
DropDownList drpEmin1 = row1.FindControl("drpEmin1") as DropDownList;
DropDownList drpEahr1 = row1.FindControl("drpEahr1") as DropDownList;
DropDownList drpEamin1 = row1.FindControl("drpEamin1") as DropDownList;
//End
if (tfromdate.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the From Date');</script>");
lblFoodException.Text = "* Enter the From Date";
tfromdate.Focus();
return;
}
//changes made on 25/jan/2012
if (drpEhr1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Depature Hours.";
drpEhr1.Focus();
return;
}
if (drpEmin1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Depature Minute.";
drpEmin1.Focus();
return;
}
//End
if (ttodate.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the To Date');</script>");
lblFoodException.Text = "* Enter the To Date";
ttodate.Focus();
return;
}
if (drpEahr1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Arrival Hours.";
drpEahr1.Focus();
return;
}
if (drpEamin1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Arrival Minue.";
drpEahr1.Focus();
return;
}
//End
if (ddlfood.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Select the Food or Perdiems');</script>");
lblFoodException.Text = "* Select the Food or Perdiems";
ddl.Focus();
return;
}
if (ddl.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Select the region');</script>");
lblFoodException.Text = "* Select the region";
ddl.Focus();
return;
}
if (txtdescription.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Description');</script>");
lblFoodException.Text = "* Enter the Description";
txtdescription.Focus();
return;
}
if (txtreference.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Reference');</script>");
lblFoodException.Text = "* Enter the Reference";
txtreference.Focus();
return;
}
if (eddl_curr.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Currencyid');</script>");
lblFoodException.Text = "* Successfully Updated";
eddl_curr.Focus();
return;
}
if (edcurrentrate.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
edcurrentrate.Focus();
return;
}
if (edamount.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
edamount.Focus();
return;
}
if (eicurrentrate.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
eicurrentrate.Focus();
return;
}
if (eiamount.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
eiamount.Focus();
return;
}
//changes made on 25/jan/2012
if (Convert.ToInt32(drpEhr1.SelectedItem.Text) >= 12)
{
Ehh = "PM";
}
else
{
Ehh = "AM";
}
if (Convert.ToInt32(drpEahr1.SelectedItem.Text) >= 12)
{
Emm = "PM";
}
else
{
Emm = "AM";
}
DateTime t1 = Convert.ToDateTime(tfromdate.Text.ToString() + " " + drpEhr1.SelectedItem.Text.ToLower() + ":" + drpEmin1.SelectedItem.Text.ToString() + " " + Ehh);
DateTime t2 = Convert.ToDateTime(ttodate.Text.ToString() + " " + drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString() + " " + Emm);
tp1 = t2.Subtract(t1);
string[] EgetInfo = Convert.ToString(tp1).Split(new char[] { '.' });
if (EgetInfo.Length > 1) // Day calculating
{
Enodays = EgetInfo[0];
string[] EgetHours = EgetInfo[1].ToString().Split(new char[] { ':' });
if (Convert.ToInt32(EgetHours[0].ToString()) >= 6 && Convert.ToInt32(EgetHours[0].ToString()) < 12)
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString()) + 0.50;
}
else if (Convert.ToInt32(EgetHours[0].ToString()) >= 12)
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString()) + 1;
}
else
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString());
}
EtotTime = Ehh.ToString() + ":" + Emm.ToString() + " PM";
EtotTime = Ehh.ToString() + ":" + Emm.ToString() + " AM";
}
else//Hours Calculating
{
string[] EgetHours = EgetInfo[0].ToString().Split(new char[] { ':' });
Enodays = "0";
hh = EgetHours[0];
mm = EgetHours[1];
if (Convert.ToInt32(hh.ToString()) >= 6 && Convert.ToInt32(hh.ToString()) < 12)
{
EtotalDays = 0.50;
}
else if (Convert.ToInt32(hh.ToString()) >= 12)
{
EtotalDays = 1;
}
if (Convert.ToInt32(hh.ToString().Length) > 12)
{
EtotTime = hh.ToString() + ":" + mm.ToString() + " PM";
}
else
{
EtotTime = hh.ToString() + ":" + mm.ToString() + " AM";
}
}
txtENoOfDays.Text = Convert.ToString(EtotalDays);
//End
sqlq = "select min(traveldate),max(dateofreturn) from tmpinttravelclaimsdetail where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds3 = db.fillDataset(sqlq);
if (ds3.Tables[0].Rows.Count > 0)
{
fromdate = ds3.Tables[0].Rows[0].ItemArray[0].ToString();
todate = ds3.Tables[0].Rows[0].ItemArray[1].ToString();
}
string from = Convert.ToDateTime(tfromdate.Text).ToString("dd/MMM/yyyy");
string to = Convert.ToDateTime(ttodate.Text).ToString("dd/MMM/yyyy");
//string date = Convert.ToDateTime(tfromdate.Text).ToString("dd/MMM/yyyy");
bool x = ((Convert.ToDateTime(from) >= Convert.ToDateTime(fromdate)) && (Convert.ToDateTime(to) <= Convert.ToDateTime(todate)));
if (x == false)
{
//ClientScript.RegisterStartupScript(this.GetType(), "ma", "<script> alert('Date should be between departure date and arrival date '); </script>");
lblFoodException.Text = "* Date should be between departure date and arrival date";
tfromdate.Text = "";
return;
}
bool y = (Convert.ToDateTime(from) <= Convert.ToDateTime(todate));
if (y == false)
{
// ClientScript.RegisterStartupScript(this.GetType(), "ma", "<script> alert('invalid date '); </script>");
tfromdate.Text = "";
lblFoodException.Text = "Invalid Date";
return;
}
int curr8 = 1;
//Poovaragavan P changes made on 25/jan/2012
sqlq = "select min(DEPATURETIME),max(ARRIVALTIME),min(traveldate),max(dateofreturn) from tmpinttravelclaimsdetail where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds5 = db.fillDataset(sqlq);
if (ds5.Tables[0].Rows.Count > 0)
{
EDepTime = ds5.Tables[0].Rows[0].ItemArray[0].ToString();
EArrTime = ds5.Tables[0].Rows[0].ItemArray[1].ToString();
EDepDate = Convert.ToDateTime(ds5.Tables[0].Rows[0].ItemArray[2].ToString()).ToString("dd/MM/yyy");
EArrDate = Convert.ToDateTime(ds5.Tables[0].Rows[0].ItemArray[3].ToString()).ToString("dd/MM/yyyy");
}
if (EDepDate == Convert.ToDateTime(from.ToString()).ToString("dd/MM/yyyy") && EArrDate.ToString() == Convert.ToDateTime(to.ToString()).ToString("dd/MM/yyy"))
{
if ((EDepTime != drpEhr1.SelectedItem.Text.ToString() + ":" + drpEmin1.SelectedItem.Text.ToString()) || (EArrTime != drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString()))
{
lblFoodException.Text = "Time should be Equal to departure Time and arrival Time";
lblFoodException.ForeColor = System.Drawing.Color.Red;
drpEhr1.SelectedIndex = 0;
drpEmin1.SelectedIndex = 0;
drpEahr1.SelectedIndex = 0;
drpEamin1.SelectedIndex = 0;
drpEhr1.Focus();
return;
}
}
//End
sql = " Update tmpintfoodexpenses set Expensedate=to_Date('" + tfromdate.Text + "','dd/mon/yyyy'),";
sql += " Expensetodate=to_Date('" + ttodate.Text + "','dd/mon/yyyy'),";
sql += " FOODORPERDIEMS='" + ddlfood.SelectedItem.Value.ToString() + "',";
sql += " region=" + ddl.SelectedItem.Value.ToString() + ",";
sql += " DESCRIPTION='" + mod.checkforapostrophe(txtdescription.Text) + "',";
sql += " REFERENCE='" + mod.checkforapostrophe(txtreference.Text) + "',";
sql += " amount=" + mod.checkforapostrophe(tAmt.Text) + ",";
sql += " Currencyid=" + eddl_curr.SelectedItem.Value + ",";
sql += " currencydescription='" + mod.checkforapostrophe(eddl_curr.SelectedItem.Text) + "',";
sql += " dollarcurrentrate=" + mod.checkforapostrophe(edcurrentrate.Text) + ",";
sql += " dollaramount=" + mod.checkforapostrophe(edamount.Text) + ",";
sql += " inrcurrentrate=" + mod.checkforapostrophe(eicurrentrate.Text) + ",";
sql += " inramount=" + mod.checkforapostrophe(eiamount.Text) + ",";
//Poovaragavan P changes made on 25/jan/2012
sql += " NOOFDAYS='" + mod.checkforapostrophe(txtENoOfDays.Text) + "',";
sql += " ARRIVALTIME='" + drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString() + "',";
sql += " DEPATURETIME='" + drpEhr1.SelectedItem.Text.ToString() + ":" + drpEmin1.SelectedItem.Text.ToString() + "',";
sql += " TOTALTIME='" + EtotTime.ToString() + "'";
//End
sql += " where detailid =" + mod.checkforapostrophe(tid.Text) + "";
db.Executecommand(sql);
gv_food.EditIndex = -1;
gv_food.ShowFooter = true;
Loadgv_halting();
Loadgv_ticket();
Loadgv_local();
Loadgv_other();
Loadgv_food();
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Successfully Updated');</script>");
lblFoodException.ForeColor = System.Drawing.Color.Green;
lblFoodException.Text = "* Successfully Updated";
}

Syntax error (missing operator) in query expression for date in asp.net

the date in excel is of the date time format and the selected date is also date time format but wots the problem
OleDbDataAdapter da1 = new OleDbDataAdapter("SELECT [ProjectId],[ProjectName],[ManagerID],[ManagerName],[AllocationStartDate],[AllocationEndDate],[horizontalshortname] FROM [" + getExcelSheetName + #"] where [horizontalshortname]="+ "'" + TextBox_Horizontal.Text + "'"
+ " AND [Isonsite]=" + "'" + DropDownList_Location.SelectedItem.Text + "'"
+ " AND [AllocationStartDate]>="+Calendar1.SelectedDate
+ " AND [AllocationEndDate]<="+Calendar2.SelectedDate
, conn);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
//if (ds.Tables[0] != null )
if (ds1.Tables[0].Rows.Count > 0)
{
GridView_Utilization_Search.Visible = true;
GridView_Utilization_Search.DataSource = ds1.Tables[0];
GridView_Utilization_Search.DataBind();
}
else
{
GridView_Utilization_Search.Visible = false;
}

How to assign id zero while selecting the default in dropdownlist

I have a drop Down list and I want that if the user selected nothing the id should be stored in database as 0, other wise if the user selected something then the id of that item is stored.
Code is here:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Query = #"SELECT [category_id] FROM [Category_Master]";
ds1 = dl.fetchrecord(Query);
ddl_parent.Items.Insert(0, new ListItem("---none---"));
int i = 0;
while (i < ds1.Tables[0].Rows.Count)
{
flag = 1;
catname = "";
index = 1;
ListItem li = new ListItem();
li.Text = catmapping(ds1.Tables[0].Rows[i]["category_id"].ToString());
li.Value = ds1.Tables[0].Rows[i]["category_id"].ToString();
ddl_parent.Items.Add(li);
i = i + 1;
}
}
lbl_mess.Text = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
Query = #"INSERT INTO [RbmDatabase].[dbo].[Category_Master]
([Category_ParentId]
,[Category_Name]
,[Category_MetaTag]
,[Category_MetaTagKeywords]
,[Category_Description]
,[Category_SortOrder]
,[Category_Status]
,[Category_UpdateDate])
VALUES ('" + dl.QoutesHandel(ddl_parent.SelectedValue.ToString()) + "','" + dl.QoutesHandel(txt_category.Text.Trim()) + "','" + dl.QoutesHandel(txt_MTdesc.Text.Trim()) + "','" + dl.QoutesHandel(txt_MTkey.Text.Trim()) + "','" + dl.QoutesHandel(txt_Desc.Text.Trim()) + "','" + dl.QoutesHandel(txt_order.Text.Trim()) + "','" + dl.QoutesHandel(ddl_status.SelectedIndex.ToString()) + "','" + String.Format("{0:yyyy-MM-dd}", DateTime.Now) + "')";
dl.insertrecord(Query, lbl_mess);
lbl_mess.Text = "Record Inserted Successfull.....!";
}
}
You should insert the "none" value when creating the list item
new ListItem("---none---", "0"));

Resources