what could be the cause of my session keeps changing by itself? - asp.net

I have a news website , each news had an ID in my database table , I choose 4 IDs randomly to put their titles in the "see more" section .. I select the ID by generating a random row number , the problem is when I click on one of the suggested news it takes me to another news randomly ! which makes no sense to me . the weird thing is the other random ID that I'm taken to does exist but not the one that I clicked.
Latelty I noticed this : for example in the "see more" section we have title1 - title2 - title3 - title4 , so I clicked on title1 it takes me to another random news which i didn't click .. now the 4 titles in the "see more" section are different which is normal .. now when I click in title2 it will take me to the current news in title1 ! and so on next time when i click in title1 it will take me to the curent news in title2 . I can't understand the relation
I tried to store the random numbers in another variables (key1,key2..) before putting one of them in the session but It's still the same problem.
I tried also not refreshing the page (I mean depending just the post back).
I tried clearing the season also tried reomving them all before storing the news Id. There is no error messages.
int myrandom1;
int myrandom2;
int myrandom3;
int myrandom4;
string key1;
string key2;
string key3;
string key4;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
string key=" ";
key = Session["key"].ToString();
SqlConnection con = new SqlConnection("Data Source=.; initial catalog=celeblogy; integrated security=true");
SqlCommand cmd = new SqlCommand("select * from news where id like '" + key + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "new");
string Titre = ds.Tables["new"].Rows[0][1].ToString();
Titre = Titre.Replace("*", "'");
titre.InnerText = Titre;
string blog = Decode(ds.Tables["new"].Rows[0][2].ToString());
string[] Blogs;
blog = blog.Replace("*", "'");
Blogs = blog.Split('#');
Literal1.Text = Blogs[0];
Image1.Attributes["src"] = "pictures/" + key + "1.jpg";
if (Blogs.Length >= 2)
{
Literal2.Text = Blogs[1];
Image2.Attributes["src"] = "pictures/" + key + "2.jpg";
}
cmd = new SqlCommand("select * from news", con);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "news");
Random rnd = new Random();
myrandom1 =rnd.Next(ds.Tables["news"].Rows.Count-1);
Image3.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom1][0].ToString()+"1.jpg";
Label1.Text =ds.Tables["news"].Rows[myrandom1][1].ToString().Replace("*","'");
key1 = ds.Tables["news"].Rows[myrandom1][0].ToString();
myrandom2 = rnd.Next(ds.Tables["news"].Rows.Count - 1);
Image4.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom2][0].ToString() + "1.jpg";
Label2.Text = ds.Tables["news"].Rows[myrandom2][1].ToString().Replace("*", "'");
key2 = ds.Tables["news"].Rows[myrandom2][0].ToString();
myrandom3 = rnd.Next(ds.Tables["news"].Rows.Count - 1);
Image5.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom3][0].ToString() + "1.jpg";
Label3.Text = ds.Tables["news"].Rows[myrandom3][1].ToString().Replace("*", "'");
key3 = ds.Tables["news"].Rows[myrandom3][0].ToString();
myrandom4 = rnd.Next(ds.Tables["news"].Rows.Count - 1);
Image6.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom4][0].ToString() + "1.jpg";
Label4.Text = ds.Tables["news"].Rows[myrandom4][1].ToString().Replace("*", "'");
key4 = ds.Tables["news"].Rows[myrandom4][0].ToString();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session["key"] =key1;
Response.Redirect(Request.RawUrl);
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Session["key"] = key2;
Response.Redirect(Request.RawUrl);
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
Session["key"] = key3;
Response.Redirect(Request.RawUrl);
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
Session["key"] = key4;
Response.Redirect(Request.RawUrl);
}
picture of the see more section

Related

C# Gridview Search

Expert my search function is not working. Not sure where i went wrong.
My code is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=foc; Trusted_Connection=yes;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
Button1_Click(Button1, null);
TextBox1_TextChanged(TextBox1, null);
}
}
protected void BindGrid()
{
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "SELECT MIN([sddoc]) AS[sddoc],[Soldtopt], [tradingname], [REP],MIN([DELTXT]) AS[Preseller Text], SUM(try_cast([Orderqty] as float)) AS[Orderqty],count(distinct Orderqty) as Qtycount , [DlvDate], SUM(try_cast(Netvalue as float)) as Netvalue, count(distinct SDDoc) as Salesdoc , count(distinct case when Netvalue = '0' then 1 else null end) as ZeroValue , count(distinct SDDoc) - count(distinct case when Netvalue = '0' then 1 else null end) As Result FROM [FOC].[dbo].[foc] where dlvdate = #dlvdate GROUP by Soldtopt,tradingname,REP,DlvDate HAVING SUM(try_cast(Netvalue as float)) = 0 and count(distinct SDDoc) = 1 and count(distinct case when Netvalue = '0' then 1 else null end) = 1";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#dlvdate", TextBox1.Text);
cmd.ExecuteNonQuery();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
conn.Close();
gvEmployeeDetails.DataSource = ds;
gvEmployeeDetails.DataBind();
}
protected void gvEmployeeDetails_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblEmpID = (Label)e.Row.FindControl("lblEmpID");
GridView gv_Child = (GridView)e.Row.FindControl("gv_Child");
string txtempid = lblEmpID.Text;
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from [FOC].[dbo].[foc] where sddoc=#sddoc";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#sddoc", txtempid);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conn.Close();
gv_Child.DataSource = ds;
gv_Child.DataBind();
}
}
Hi problem is solved by binding the grid with button click.

Filtering on multiple parameters

I want to filter on multiple parameters in crystal reports through combo box but the problem is one filter is active at a time.
Here is the code of index change of both combo boxes:
protected void drpUserName_SelectedIndexChanged(object sender, EventArgs e)
{
username = drpUserName.SelectedValue;
ReportDocument rd = new ReportDocument();
rd.Load(Server.MapPath("LeaveReport.rpt"));
rd.SetParameterValue("username", username);
rd.SetParameterValue("status", status);
rd.SetDatabaseLogon("cde_portal", "credyna", "SERVER\\SQLEXPRESS", "lbs");
CrystalReportViewer1.ReportSource = rd;
}
protected void drpStatus_SelectedIndexChanged(object sender, EventArgs e)
{
status = drpStatus.SelectedValue;
ReportDocument rd = new ReportDocument();
rd.Load(Server.MapPath("LeaveReport.rpt"));
rd.SetParameterValue("status", status);
rd.SetParameterValue("username", username);
rd.SetDatabaseLogon("cde_portal", "credyna", "SERVER\\SQLEXPRESS", "lbs");
CrystalReportViewer1.ReportSource = rd;
}
And here is record selection formula:
If {?username} = "-1" Then // -1 for all values
{tblEmployee.Employeer_UserName} <> {?username} // return all records
Else
{tblEmployee.Employeer_UserName} = {?username} // return selected records
and IF {?status} = "-1" Then
{tblLeave.leave_status} <> {?status}
Else
{tblLeave.leave_status} = {?status}
One more thing in above formula: if I check {?username} first and then check {?status} in this case {?username} filtering is working, but if I check {?status} first then {?status}, filtering works fine.
you can do this by this way...
protected void drpUserName_SelectedIndexChanged(object sender, EventArgs e)
{
string strSelection = "1=1";
rd.SetParameterValue("username", drpUserName.SelectedValue);
rd.SetParameterValue("status", drpStatus.SelectedValue);
if (drpUserName.SelectedValue != "-1")
{
strSelection = strSelection + "And {tblEmployee.Employeer_UserName}=" + "\""+ drpUserName.SelectedValue+"\"";
}
if ( drpStatus.SelectedValue != "-1")
{
strSelection = strSelection + "And {tblLeave.leave_status}=" +"\""+ drpStatus.SelectedValue+"\"" ;
}
rd.RecordSelectionFormula = strSelection;
rd.SetDatabaseLogon("cde_portal", "credyna", "SERVER\\SQLEXPRESS", "lbs");
CrystalReportViewer1.ReportSource = rd;
}
protected void drpStatus_SelectedIndexChanged(object sender, EventArgs e)
{
string strSelection = "1=1";
rd.SetParameterValue("username", drpUserName.SelectedValue);
rd.SetParameterValue("status", drpStatus.SelectedValue);
if (drpUserName.SelectedValue != "-1")
{
strSelection = strSelection + "And {tblEmployee.Employeer_UserName}=" + "\"" + drpUserName.SelectedValue + "\"";
}
if (drpStatus.SelectedValue != "-1")
{
strSelection = strSelection + "And {tblLeave.leave_status}=" + "\"" + drpStatus.SelectedValue + "\"";
}
rd.RecordSelectionFormula = strSelection;
rd.SetDatabaseLogon("cde_portal", "credyna", "SERVER\\SQLEXPRESS", "lbs");
CrystalReportViewer1.ReportSource = rd;
}

What is the concept (# ) Coming before the select this code?

What is the concept (# ) Coming before the select this code?
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = **#**"SELECT tblstore.storname,tblproduct.pid, tblproduct.pname, tblproduct.pprice, tblproduct.publisher, tblproduct.writer FROM tblproduct INNER JOIN tblstore ON tblproduct.storeid = tblstore.storeid WHERE tblproduct.pname LIKE # likeText;";
SqlDataSource2.SelectParameters.Add("likeText", txtName.Text);
GridView1.EmptyDataText = "not result";
}
Remove space between # and likeText from command text
SqlDataSource2.SelectCommand = #"SELECT tblstore.storname,tblproduct.pid, tblproduct.pname, tblproduct.pprice, tblproduct.publisher, tblproduct.writer FROM tblproduct INNER JOIN tblstore ON tblproduct.storeid = tblstore.storeid WHERE tblproduct.pname LIKE #likeText";
and add parameter value like this
SqlDataSource2.SelectParameters.Add("#likeText","%" + txtName.Text + "%");

changing label text on selectedindexchanged of dropdown

I need the address (below the dropdown) to change as per the name that is selected in the dropdown... (they are all for one user only)...! (i donno why this keeps saying your post seems only code!!!!!!)
public DataSet BindDropDownListToAUserAddress2()
{
UserFunctions objGetSession = new UserFunctions();
string strSession = objGetSession.GetEmailFromSession();
DataSet dsUserAddress = new DataSet();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string strQuery = "(SELECT FirstName +' '+ LastName as FullName, * FROM AUserAddress inner join AState on AUserAddress.State_ID = AState.ID inner join ACountry on AUserAddress.Country_ID = ACountry.ID inner join AUser on AUserAddress.AUser_ID=AUser.ID where AUser.Email='" + strSession + "')";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(dsUserAddress, "AUserAddress");
con.Close();
return dsUserAddress;
}
protected void ddlName_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dsUserAddress = objBindDDL.BindDropDownListToAUserAddress2();
string strSession = objGetSession.GetEmailFromSession();
ddlName.SelectedValue = "FullName";
if (objBindDDL.BindDropDownListToAUserAddress2() != null && objBindDDL.BindDropDownListToAUserAddress2().Tables.Count > 0)
{
lblDisplayFirstName.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["FirstName"].ToString();
lblDisplayLastName.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["LastName"].ToString();
lblDisplayAddressLine1.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine1"].ToString();
lblDisplayAddressLine2.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine2"].ToString();
lblDisplayAddressLine3.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine3"].ToString();
lblDisplayCity.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["City"].ToString();
lblDisplayState.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["StateName"].ToString();
lblDisplayCountry.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["CountryName"].ToString();
lblDisplayPostalCode.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["PostalCode"].ToString();
}
}
when you are binding data to dropdown list
ddlStatus.DataTextField = "FullName";
ddlStatus.DataValueField = "Id";
onselected index change event
int ID =Convert.Toint32(ddlName.SelectedValue)
by using this ID select only this ID Record from the dataTable and display

Listview custom paging with datapager

Can anyone please tell me how to implement custom paging with datapager. Now I have managed to do this with 2 buttons (for next and previous pages) and LoadListview() method, but I would like to use this method in datapager. Any suggestions?
Code behind file:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BusinessConnectionString"].ToString());
SqlDataAdapter adap;
int startIndex;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadListview();
}
}
private void LoadListview()
{
string FindWhat = Request.QueryString["Find"];
string FindWhere = Request.QueryString["Where"];
string TownName = FindWhere;
string CountyName = FindWhere;
string PostcodeName = FindWhere;
//startIndex = int.Parse(ViewState["index"].ToString());
startIndex = MyDataPager.StartRowIndex * MyDataPager.PageSize;
int endIndex = startIndex + MyDataPager.PageSize;
adap = new SqlDataAdapter("SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY id_Business) AS MyRow, id_Business, Name, TownName FROM UbeloView WHERE (Name Like '%" + FindWhat + "%' AND TownName Like '%" + TownName + "%') UNION ALL SELECT ROW_NUMBER() OVER (ORDER BY id_Business) AS MyRow, id_Business, Name, TownName FROM UbeloView WHERE (Name Like '%" + FindWhat + "%' AND CountyName Like '%" + CountyName + "%') UNION ALL SELECT ROW_NUMBER() OVER (ORDER BY id_Business) AS MyRow, id_Business, Name, TownName FROM UbeloView WHERE (Name Like '%" + FindWhat + "%' AND PostcodeName Like '%" + PostcodeName + "%')) AS log WHERE MyRow >=" + startIndex + " AND MyRow <=" + endIndex + " ", conn);
DataSet ds = new DataSet();
adap.Fill(ds);
lstBusiness.DataSource = ds;
lstBusiness.DataBind();
}
protected void MyDataPager_PreRender(object sender, EventArgs e)
{
LoadListview();
}
This article could help you: http://www.codeproject.com/Articles/24065/Paging-ListView-With-DataPager
In this article, the author has used a DataPager_PreRender to bind his data to a ListView:
protected void DataPagerProducts_PreRender(object sender, EventArgs e)
{
ProductList db = new ProductList();
this.ListViewProducts.DataSource = db.GellAll();
this.ListViewProducts.DataBind();
}
You could try something similar:
protected void MyDataPager_PreRender(object sender, EventArgs e)
{
LoadListview();
}
Then all you will need to do is modify your LoadListview() method to get the start index from the DataPager control itself.
private void LoadListview()
{
string FindWhat = Request.QueryString["Find"];
string FindWhere = Request.QueryString["Where"];
string TownName = FindWhere;
string CountyName = FindWhere;
string PostcodeName = FindWhere;
startIndex = MyDataPager.StartRowIndex * MyDataPager.PageSize;
adap = new SqlDataAdapter("<Query removed to save space>", conn);
DataSet ds = new DataSet();
adap.Fill(ds);
lstBusiness.DataSource = ds;
lstBusiness.DataBind();
}
As you can see, I am getting the startIndex by getting the row index and multiplying it by the page size of your DataPager. Now you can just change this part of your SQL Query from startIndex * 80 to startIndex.
If all goes to plan, you won't need your btnPrevious and btnNext click events.
I hope this gives you some insight in what you are trying to achieve.

Resources