loading data in gridview is slow - asp.net

For having the result like below and showing column 2 (user control) & column 3 (user control) grouped by column 1. I have made the code like below but it is slow , actually when I use just column 1 , loading is quick (5 seconds) , when I use column 1 & column2 (user control "document list") loading is 10 seconds, and when I use column 1 & column 2 (document list") & column3 ("DocTransList") loading is 45 seconds. I think my code in LINQ is not efficient , but I do not know how to solve it.
TRANSMITTAL No Documents REV
TT-001 DOC-001 01
DOC-002 01
public partial class Transmittals : System.Web.UI.Page
{
class TransmittalPresentationModel
{
public int TransID { get; set; }
public String TransmittalNo { get; set; }
public IEnumerable<tblDocument> Documents { get; set; }
public IEnumerable<tblTransmittall> DocTrans { get; set; }
}
private EDMSDataContext _DataContext;
protected void Page_Load(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
if (!IsPostBack)
{
DisplayAuthors();
}
}
private void DisplayAuthors()
{
var query =
from transmittal in _DataContext.tbltransmittalNos
orderby transmittal.TRANSMITTAL
select new TransmittalPresentationModel
{
TransID = transmittal.TransID,
TransmittalNo = transmittal.TRANSMITTAL,
Documents = transmittal.tblTransmittalls.Select(Transmittals => Transmittals.tblDocument),
DocTrans = transmittal.tblTransmittalls
};
GridViewTransmittals.DataSource = query.ToList();
GridViewTransmittals.DataBind();
}
protected void GridViewTransmittals_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem == null) return;
TransmittalPresentationModel transmittal = (TransmittalPresentationModel)e.Row.DataItem;
DocumentList documentList = (DocumentList)e.Row.FindControl("DocumentList1");
DocTransList doctranslist = (DocTransList)e.Row.FindControl("DocTransList2");
documentList.Documents = transmittal.Documents;
documentList.DataBind();
doctranslist.DocTrans = transmittal.DocTrans;
doctranslist.DataBind();
}
}

Your having issues because your records all need to load into the GridView on each page load / refresh. This pulls from the database and draws each row each time which is time consuming.
Better options are to use Ajax to load your GridView.
Or use Paging on the server side and only give the data to your page it needs.

Related

display next page asynchronously and then run its page load event

I have an airline site in which i am trying to display the fare from different API/Web service. But Firstly i want to display the search page--> Display processing --> binding data in the page from theses API/web service as they received.
but i am not able to display search page before the result processing.
What i have tried (code)-
public partial class asyncgridview : System.Web.UI.Page,ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsCallback)
{
ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);
}
}
private string _Callback;
public string GetCallbackResult()
{
return _Callback;
}
public void RaiseCallbackEvent(string eventArgument)
{
DataTable table = fetchData();
gvAsync.DataSource = table;
gvAsync.DataBind();
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
gvAsync.RenderControl(new HtmlTextWriter(sw));
_Callback = sw.ToString();
}
}
}
regards
Avishek

passing gridview particular row datas to another page in asp.net?

i want to set session in login page and want to pass one page girdview data to another page.
slno title author publication takenby
1 book1 author1 pub1 sendrequest (button)
Above image showing gridview. when i click the Request Book button(1st one). it will redirect to sendrequest.aspx page. and have to bring that row data (i.e)
slno=1
title=book1
Author=author1
publication=publ
i tried below code
user.aspx.cs
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string user = (string)(Session["User"]);
if (e.CommandName.Equals("SendRequestCmd"))
{
if (user == null)
{
Session["slno"] = null;
Session["bookname"] = null;
var clickedRow = ((Button)e.CommandSource).NamingContainer as GridViewRow;
// now access the cells like this
SlNo = clickedRow.Cells[0].Text;
Session["slno"] = SlNo.ToString();
BookName = clickedRow.Cells[1].Text;
Session["bookname"] = BookName.ToString();
}
}
}
sendquest.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string slno = "", bookname = "";
slno = (string)(Session["slno"]);
bookname = (string)(Session["bookname"]);
if (slno == null || bookname == null)
{
Response.Write("serial no: " + slno + "\nbookname: " + bookname);
}
}
protected void Logout()
{
Session.Clear();
}
but i got error in
slno=(string)(Session["slno"]);
bookname=(string)(Session["bookname"]);
why? anybody correct it?
else say better way?
Without posting your error it's difficult to see what the problem is. You could check that Sessions are enabled in your application.
Another way to do this (which may be better) is passing just the id/slno (via QueryString) to your other page, then perform a lookup to get your data at that stage.
I will surely create a type(Class) for booking
with slno title author publication properties and
public class Booking
{
public Booking()
{
//
// TODO: Add constructor logic here
//
}
public int slno { get; set; }
public string Title { get; set; }
public string author { get; set; }
public string publication { get; set; }
}
set all properties of object of booking type and pass that object in session
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string user = (string)(Session["User"]);
if (e.CommandName.Equals("SendRequestCmd"))
{
if (user == null)
{
Booking b = new Booking();
b.slno = clickedRow.Cells[0].Text;
b.Title = BookName.ToString();
Session["Booing"] = b;
}
}
}
and on receiving end just case that session value into that object again
and access each property just by using dot with object name .
Booking b=(Booking)Session["Booking"]
int slno=b.slno;
string Title=b.Title;
Without posting error not possible to give suggestion or correction , my answer is just how can you pass multiple values using session from one page to another .
Thanks

Display Multiple Notes on Same Date of Calender

I want to display calendar with some notes/events which i stored in database.
In some date more than one notes are added.
Now when page is load i want that all in my calendar control.
I done that BUT It displays only one(1st entered) note in the calendar although i saved more than one notes on that same DATE.
It looks like below image..
In this Image On Date 7 i added 2 Notes but it displays only one...
My code is as below...
public partial class _Default : System.Web.UI.Page
{
public static ArrayList MyColllection;
//Structure
public struct My_Date
{
public DateTime Cal_Date;
public string Cal_Type;
public string Cal_Title;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyColllection = Get_Event();
}
}
public ArrayList Get_Event()
{
SqlConnection myCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
SqlCommand myComd = new SqlCommand("SELECT * FROM Cal_Event",myCon);
SqlDataReader myDataReader;
try
{
myCon.Open();
myDataReader = myComd.ExecuteReader();
MyColllection = new ArrayList();
My_Date temp;
//Iterate through the data reader
while(myDataReader.Read())
{
temp.Cal_Title = myDataReader.GetValue(1).ToString();
temp.Cal_Date = Convert.ToDateTime(myDataReader.GetValue(2));
temp.Cal_Type = myDataReader.GetValue(3).ToString();
MyColllection.Add(temp);
}
}
catch
{}
finally
{
myCon.Close();
}
return MyColllection;
}
public void Calendar1_DayRender(object o, DayRenderEventArgs e)
{
string FontColor;
string compDate = "01/01/1900"; // Date to compare initially
DateTime DayVal = Convert.ToDateTime(compDate);
bool mItemDay = false;
bool dayTextChanged = false;
StringBuilder strTemp = new StringBuilder();
foreach (My_Date temp_dt in MyColllection)
{
if ("01/01/1900" != temp_dt.Cal_Date.ToShortDateString())
{
if (dayTextChanged == true)
{
break;
}
mItemDay = false;
DayVal = temp_dt.Cal_Date;
}
else
{
mItemDay = true;
}
if (e.Day.Date == Convert.ToDateTime(temp_dt.Cal_Date.ToString("d")))
{
switch (temp_dt.Cal_Type)
{
case "1" :
FontColor = "Blue";
break;
case "2":
FontColor = "Red";
break;
default:
FontColor = "Black";
break;
}
if (mItemDay == false)
{
strTemp = new StringBuilder();
}
else
{
strTemp.Append("<br>");
}
strTemp.Append("<span style='font-family:verdana;font-size:10px;font-weight:bold;color'");
strTemp.Append(FontColor);
strTemp.Append("'><br>");
strTemp.Append(temp_dt.Cal_Title.ToString());
strTemp.Append("</span>");
e.Cell.BackColor = System.Drawing.Color.Yellow;
dayTextChanged = true;
}
}
if (dayTextChanged == true)
{
e.Cell.Controls.Add(new LiteralControl(strTemp.ToString()));
}
}
}
So I need to display multiple Notes on same day...
So How can I do this??
Thanks in Advance....
Calendars are basically date pickers and using them to display data is one of the most common mistakes people make. Use a ListView to display your data/events; calendars were never meant for that.
At some stage the calendar cells are going to stretch as events are added for the same day, breaking the entire display. And if you try to set a limit, then people are going to complain and start asking why other events are listed and theirs aren't, etc.
In your code, you're basically swallowing the exception instead of handling it. Comment out the try-catch-finally (leave the Close()) and check what error you get then :)

How to calculate the page index in grid view

I am using a set of codes for all web pages
grvcity.PageIndex + = 1;
to get the next page in grid view
I want to caluclate the page index where the currently is on . How to do it
GridView.PageIndex property both gets and sets the index of currently displayed page:
[BrowsableAttribute(true)]
public virtual int PageIndex { get; set; }
Therefore, the answer in your case should simply be:
int currentPage = grvcity.PageIndex;
Update
If you are talking about the PageIndexChanging event, here is a sample:
protected void grvcity_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grvcity.PageIndex = e.NewPageIndex;
grvcity.DataBind();
}

asp.net data entry form

I want to build a form where users can enter some data in a few text boxes and click the "Add" button and have the the data appear in a grid or something like it. They need to be able to enter multiple rows.
Then when they are done they can click the "Save" button to save the data to the database.
How do I get the data from from the text boxes into the "grid"?
EDIT
Here's what I have so far
protected void Page_Load(object sender, EventArgs e)
{
DataTable myDataTable = new DataTable();
DataColumn dc1 = new DataColumn("Employee");
myDataTable.Columns.Add(dc1);
DataColumn dc2 = new DataColumn("Category");
myDataTable.Columns.Add(dc2);
DataColumn dc3 = new DataColumn("Description");
myDataTable.Columns.Add(dc3);
DataColumn dc4 = new DataColumn("P/S/N");
myDataTable.Columns.Add(dc4);
DataColumn dc5 = new DataColumn("Hours");
myDataTable.Columns.Add(dc5);
DataColumn dc6 = new DataColumn("WeekEnding");
myDataTable.Columns.Add(dc6);
}
protected void btnAddToGrid_Click(object sender, EventArgs e)
{
DataRow row = myDataTable.NewRow();// i'm getting error here sayind myDataTable does not exist
row["Employee"] = LoginName1.ToString();
row["Category"] = ddlCategory.SelectedValue;
row["Description"] = txtDescription.Text;
row["P/S/N"] = ddlPSN.SelectedValue;
row["Hours"] = ddlHours.SelectedValue;
row["WeekEnding"] = txtWeekEnding.Text;
myDataTable.Rows.Add(row);
Ok your first problem from your comment:
i'm getting error here sayind myDataTable does not exist
Is because you defined your table in the Page_Load and then it goes out of scope at the end of the function. It sounds like you don't understand the basic concepts of ASP.NET and what you are trying to do.
Here is a quick and dirty untested solution to your problem but I must stress that you should try and understand why this solution works before trying to extend it or do more in ASP.NET. I hope my 10 minutes of my time helps you get a good start into understanding C# and ASP.NET.
[Serializable]
public class YourData
{
public string Employee { get; set; }
public string Category { get; set; }
public string Description { get; set; }
public string P_S_N { get; set; }
public string Hours { get; set; }
public string WeekEnding { get; set; }
}
// Used to add your list of data to the viewstate cache
// (There are other ways to store data between posts but I am trying to keep it simple)
public void SetYourCachedData(List<YourData> data)
{
ViewState["YourDataCache"] = data;
}
// Used to get your save data so far
public List<YourData> GetYourCachedData()
{
return ViewState["YourDataCache"] == null ?
new List<YourData>() : (List<YourData>)(ViewState["YourDataCache"]);
}
protected void Page_Load(object sender, EventArgs e)
{
// Do nothing
}
protected void btnAddToGrid_Click(object sender, EventArgs e)
{
// Get the data and store it in the ViewState to cache it between post backs
// Assuming one record added with each click.
List<YourData> data = GetYourCachedData();
data.Add(new YourData()
{
Employee = LoginName1.ToString(),
Category = ddlCategory.SelectedValue,
Description = txtDescription.Text,
P_S_N = ddlPSN.SelectedValue,
Hours = ddlHours.SelectedValue,
WeekEnding = txtWeekEnding.Text
});
// You can bind to any type of collection easily.
// You don't need to use a DataTable with a GridView
yourGrid.DataSource = data;
yourGrid.DataBind();
SetYourCachedData(data);
}
protected void btnSaveData_Click(object sender, EventArgs e)
{
// Pull data from the ViewState cache
List<YourData> data = GetYourCachedData();
// Now iterate through data to save it to your database...
// look this up if you don't know how as this is a lot more work.
}
looks like you just need to set the output object's datasource and bind it.
I.e.:
myGrid.datasource = myDataTable
myGrid.databind()
And as Kelsey says -- keep your datatable in scope.
a public dim right above your page_load would be easier, if you just want to try it out. Otherwise, the separate class approach is a good way to go.

Resources