Listview custom paging with datapager - asp.net

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.

Related

what could be the cause of my session keeps changing by itself?

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

Upload and update excel file

I have a task to upload the excel file and also check update if the same record found, I have uploaded the excel file in the database which is working fine.
Now, I have to check if the same records inserted then update otherwise insert the new records, I have two table first I am inserting the records in the temp table then after that I am checking the temp table with the original table , if records matches then update else insert, I am using nested for loop to check the records
my loop works fine and insert the top two records, but when it comes to the 3rd record then insert it multiple times and on 4th again multiple times,Kindly guide me what i am doing wrong
here is my code so far
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
int id;
string contactPerson;
string designation;
string company;
string contact;
string emailaddress;
string city;
string region;
string industry;
string division;
string mobile;
string address;
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/uploadExcel/") + FileUpload1.FileName);
String ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
DeleteRecords();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr[0].ToString() != "")
{
// Response.Write("<br/>"+dr[0].ToString());
id = Convert.ToInt32(dr[0].ToString());
contactPerson = dr[1].ToString();
designation = dr[2].ToString();
company = dr[3].ToString();
emailaddress = dr[4].ToString();
contact = dr[5].ToString();
mobile = dr[6].ToString();
address = dr[7].ToString();
city = dr[8].ToString();
region = dr[9].ToString();
industry = dr[10].ToString();
division = dr[11].ToString();
InsertTemp(id, contactPerson, designation, company, emailaddress, contact,
mobile, address, city, region, industry, division);
//InsertOrignal(id, contactPerson, designation, company, emailaddress, contact,
// mobile, address, city, region, industry, division);
}
else
{
break;
}
String myconn = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection conn = new SqlConnection(myconn);
conn.Open();
DataTable dt_temp = new DataTable();
DataTable dt_orignal = new DataTable();
SqlDataAdapter da_temp = new SqlDataAdapter("select * from Tbl_ExcelData order by id asc", conn);
SqlDataAdapter da_orignal = new SqlDataAdapter("select * from Tbl_ExcelUploadData order by id asc", conn);
da_temp.Fill(dt_temp);
da_orignal.Fill(dt_orignal);
if (dt_orignal.Rows.Count > 0)
{
for (int i = 0; i < dt_temp.Rows.Count; i++)
{
for (int j = 0; j < dt_orignal.Rows.Count; j++)
{
if (dt_temp.Rows[i]["email"].ToString() == dt_orignal.Rows[j]["email"].ToString())
{
//Update Record if required
}
else
{
//insert record into orignal table
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
}
}
else
{
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
lblmessage.Text = "Data Has Been Updated Successfully";
mycon.Close();
File.Delete(ExcelPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void InsertTemp(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address,String city,String region,String industry,
String division)
{
//String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "insert into Tbl_ExcelData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
private void InsertOrignal(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address, String city, String region, String industry,
String division)
{
//String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "insert into Tbl_ExcelUploadData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
private void DeleteRecords()
{
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "Delete from Tbl_ExcelData";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
If you have the Temporary table just to check if the row exists in an Original table, then it is not a good practice.
Directly check if the row exists in your original table with the Primary key id or any Unique Key and then decide whether to Insert or Update.
One way to do this,
while (dr.Read())
{
if (dr[0].ToString() != "")
{
id = Convert.ToInt32(dr[0].ToString()); //add other columns which needs to be fetched from Excel
string query = "select count(1) from Tbl_ExcelData where id=?"; //To check if the row already exsits
SqlCommand cmd = new SqlCommand(con);
cmd.CommandText = query;
cmd.Paramaters.Add(new SqlParameter(1, id));
int count = (Int32) cmd.ExecuteScalar();
if (count > 0) //which means row already exists
{
//Your update code goes here
}
else
{
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
After comments, here is a basic idea. One way you can load your excel data into DataTable and loop through it and decide for Upsert. Remember to learn about MultipleActiveResultSets
try
{
string ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
string _oleDBConnectionString = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}; Extended Properties=Excel 8.0; Persist Security Info = False", ExcelPath);
string _sqlConnectionString = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True; MultipleActiveResultSets=true;"; //enable MultipleActiveResultSets as you'll be opening a nested SqlConnection
string _excelQuery = "select * from [Sheet1$]";
DataTable tempDataTable = null;
using (var conn = new OleDbConnection(_oleDBConnectionString)) //This code loads your excel data into data table
{
conn.Open();
using (var cmd = new OleDbCommand(_excelQuery, conn))
{
using (var reader = cmd.ExecuteReader())
{
var dt = new DataTable();
dt.Load(reader); //this will load your excel data into DataTable
tempDataTable = dt;
}
}
}
using(var sqlConn = new SqlConnection(_sqlConnectionString)) //this code will connect to sql db and upsert based on the id from the excel
{
sqlConn.Open();
string countQuery = "select count(1) from Tbl_ExcelData where id=:id";
using(var cmd = new SqlCommand(countQuery, sqlConn))
{
var param = new SqlParameter("#id");
foreach (DataRow row in tempDataTable.Rows) //this will loop through the DataTable rows, the actual rows from Excel which are loaded into DataTable
{
var id = row["id"]; //get the id column from the excel
var contactPerson = row["contactPerson"]; //get the contactPerson column from the excel
cmd.Paramaters["#id"] = id;
int count = (int) cmd.ExecuteScalar();
if (count) //row already exist in original table
{
//update the row in original table
}
else
{
//insert the row in original table
InsertOriginal(sqlConn, id, contactPerson);
}
}
}
}
}
catch(Exception ex)
{
}
function InsertOriginal(SqlConnection conn, int id, string contactPerson)
{
string insertQuery = "insert into Tbl_ExcelUploadData (id,contactpersonn) values('#id','#contactPerson');
using(var cmd = new SqlCommand(insertQuery, conn))
{
cmd.Parameters.Add(new SqlParameter("#id",id));
cmd.Parameters.Add(new SqlParameter("#contactPerson", contactPerson));
cmd.ExecuteNonQuery();
}
}
Also, this is not a tested code. Feel free to comment back.

Error: An expression of non-boolean type specified in a context where a condition is expected

I want to pass three query string variables, which ars DateFrom, DateTo and UserName. When I call that the variable, it shows an error:
'An expression of non-boolean type specified in a context where a condition is expected, near 'admin'.'".
How can I resolve the issue? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
strDate = Convert.ToDateTime(Request.QueryString["DateFrom"]);
endDate = Convert.ToDateTime(Request.QueryString["DateTo"]);
UserName = Convert.ToSingle(Request.QueryString["UsName"]);
string UserName = Request.QueryString["UsrName"];
string sql;
sql = ("SELECT * FROM tblReport WHERE Date between'" + strDate + "'and'" + endDate + "'and'" + UserName + "'");
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
DataSet dst = new DataSet();
sda.Fill(dst, "tblReport");
crypt.Load(#"D:\My Project\Asp.Net\ITApplication\ITApplication\CrystalReport.rpt");
crypt.SetDataSource(dst);
CrystalReportViewer1.ReportSource = crypt;
}
you are missing something in your where clause... should be like this:
WHERE Date BETWEEN '<FromDate>' AND '<ToDate>'
AND UserName = '<UserName>'
Your SQL string is not formatted well.
Put spaces near yout and operators and use () in your between:
sql = ("SELECT * FROM tblReport WHERE [Date] between ('" + strDate + "' and '" + endDate + "') and UserName='" + UserName + "'");
Side note:
Using SQL strings with concatenating values like this is a very bad idea. It exposes you to SQL Injections, and overall a bad practice. Please consider using Command.Parameters:
SqlCommand Command = new SqlCommand("SELECT * FROM tblReport WHERE [Date] between (#strDate and #endDate) and UserName=#UserName");
Command.Parameters.Add(new SqlParameter("strDate", strDate));
Command.Parameters.Add(new SqlParameter("endDate", endDate));
Command.Parameters.Add(new SqlParameter("UserName", UserName));

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

Resources