Deleting 11th row in RadGrid makes it become blank - c#

I have one Telerik RadGrid. Using a method I am filling the grid. I have enabled the paging property. I have used ItemTemplate-->ImageButton for delete and edit options. I have set page size as 10. Page load time is working properly and populating the grid. After inserting the 11th row the pagination starts and it will show in the next page with one record. But when I am deleting the 11th row the grid becomes blank. I have used dataset to bind the records.
radgrid.DataBind();
dsDataset.Dispose();
But its item.count is 0. What is the reason?
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
PopulatePackage();
}
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
protected void gvPackage_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
SqlHelper objSQL = new SqlHelper();
DataSet dsPackage = new DataSet();
dsPackage = objSQL.ExecuteDataset("AL_PackageType_List_Retrieve", objUtl.NumericEntry(Session["LocationId"].ToString()));
gvPackage.DataSource = dsPackage.Tables[0];
dsPackage.Dispose();
//PopulatePackage();
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
}
}
private void PopulatePackage()
{
try
{
lblMessage.Text = string.Empty;
SqlHelper objSQL = new SqlHelper();
DataSet dsPackage = new DataSet();
dsPackage = objSQL.ExecuteDataset("AL_PackageType_List_Retrieve", objUtl.NumericEntry(Session["LocationId"].ToString()));
gvPackage.DataSource = null;
gvPackage.DataSource = dsPackage.Tables[0];
gvPackage.DataBind();
//dsPackage.Dispose();
if (gvPackage.Items.Count <= 0)
{
lblMessage.Text = "No Package Details Found...";
gvPackage.Visible = false;
}
else
{
gvPackage.Visible = true;
}
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
}
}

Okay as far as I am understanding it, You have a radgrid in which you have allowed paging and set the page size to 10. Upon inserting the 11th record a new page is shown with that 11th record. And when that 11th record is deleted you are viewing a blank page, instead of showing the page having record from 1 to 10. I hope I am right here.
Anyway. I guess the problem is that the Radgrid is not having the data for the page you are viewing now.
There is an event in RadGrid named NeedDataSource. This Event is fired up whenever the RadGrid needs to display the data. You can call the Binding logic in this event and see if it works for you.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
RadGrid1.DataSource = "BindingSource";
RadGrid1.DataBind();
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
BindGrid();
}
See if this works for you..

Related

asp.net linq query datatable

I have been following this tutorial to implement edit/update functionality via a modal popup form in asp.net:
http://msdnaspdotnettuto.blogspot.com/2015/01/aspnet-gridview-crud-using-twitter.html
This is my code:
public partial class GroupSummary1 : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGroupSummary();
}
}
private void LoadGroupSummary()
{
try
{
UserBLL userBLL = new UserBLL();
dt = userBLL.GetGroupSummary(2, 2017);
gvGroupSummary.DataSource = dt;
gvGroupSummary.DataBind();
}
catch (SqlException ex)
{
System.Console.Error.Write(ex.Message);
}
}
protected void gvGroupSummary_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("detail"))
{
string code = gvGroupSummary.DataKeys[index].Value.ToString();
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<int>("GroupID").Equals(code)
select i;
DataTable detailTable = query.CopyToDataTable<DataRow>();
DetailsView1.DataSource = detailTable;
DetailsView1.DataBind();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type='text/javascript'>");
sb.Append("$('#detailModal').modal('show');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
}
}
}
When I select the "detail" button on the grid view, the following error occurs:
System.ArgumentNullException HResult=0x80004003 Message=Value
cannot be null. Parameter name: source Source= StackTrace:
At this line:
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<int>("GroupID").Equals(code)
select i;
The dt object is NULL and I suspect this is the source of the problem. However, I have declared it above just as in the tutorial.
Any ideas?
Thanks
LoadGroupSummary is only firing on initial page load, not on postback. Clicking your detail button to call gvGroupSummary_RowCommand() will cause a postback.
Simply remove the if (!IsPostBack) from your page load.
protected void Page_Load(object sender, EventArgs e)
{
LoadGroupSummary();
}
EDIT:
Might be worth mentioning that if whatever data userBLL.GetGroupSummary() returns is static, you should probably only load it once. For Example:
private void LoadGroupSummary()
{
try
{
if (Session["GroupSummary"] != null)
{
dt = (DataTable)Session["GroupSummary"];
}
else
{
UserBLL userBLL = new UserBLL();
dt = userBLL.GetGroupSummary(2, 2017);
Session["GroupSummary"] = dt;
}
gvGroupSummary.DataSource = dt;
gvGroupSummary.DataBind();
}
catch (SqlException ex)
{
System.Console.Error.Write(ex.Message);
}
}

How to page gridview that already has data bound to it?

I have a View button on my webpage. As soon as a user clicks on this button, through a web service data is fetched and then data is bound to grid view. But when the grid view loads it only shows the number of rows mentioned in PageSize property of the grid and does not show page numbers.
private void FetchData(ref DataTable dt)
{
string s_strResult = "";
string s_strQuery = "";
string s_strQueryType = "";
try
{
grdSearchResult.DataSource = dt.DataSet.Tables["Result"];
grdSearchResult.DataBind();
tblSearchResult.Visible = true;
lblSearchResult.Text = "Total Items:" + dt.DataSet.Tables["Result"].Rows.Count;
}
}
The Result DataSet contains 5000 rows with 30 columns each. When the gridView loads all I can see is just 100 records (as PageSize=100). How can I page the results? The data needs to be fetched at button click only. The code for gridView page index change is as follows:
protected void grdSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
grdSearchResult.PageIndex = e.NewPageIndex;
grdSearchResult.DataBind();
}
catch (Exception ex)
{
DisplayMessage(GlobalClass.enumMsgType.Error, ex.Message);
}
}
Hello Rishik please check below link for gridview paging:
http://www.codeproject.com/Articles/816953/How-To-Implement-Paging-in-GridView-Control-in-ASP
http://www.c-sharpcorner.com/UploadFile/rohatash/gridview-paging-sample-in-Asp-Net/
You can store your data in a Viewstate or Session variable, I recommend to use a property as wrapper like this:
private DataTable dtStored
{
get { return (ViewState["dt"] == null) ? null : (DataTable)ViewState["dt"]; }
set { ViewState["dt"] = value; }
}
now you can bind your DataTable and save it in the property:
private void FetchData(ref DataTable dt)
{
string s_strResult = "";
string s_strQuery = "";
string s_strQueryType = "";
try
{
dtStored = dt.DataSet.Tables["Result"];
grdSearchResult.DataSource = dtStored;
grdSearchResult.DataBind();
tblSearchResult.Visible = true;
lblSearchResult.Text = "Total Items:" + dt.DataSet.Tables["Result"].Rows.Count;
}
}
and in the IndexPageChanging method just add a line:
protected void grdSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
grdSearchResult.DataSource = dtStored;
grdSearchResult.PageIndex = e.NewPageIndex;
grdSearchResult.DataBind();
}
catch (Exception ex)
{
DisplayMessage(GlobalClass.enumMsgType.Error, ex.Message);
}
}
If your data is too large maybe it could be better to store it in a Session variable than in a Viewstate, because the second one is going to travel from the Client to the Server and from the Server to the Client in every Postback while you stay in the same page or until you set the variable to null

Gridview always show previous selected row

I am updating gridview after selecting row and then clicking edit which works perfectly but one thing is annoying me that whenever i visit that gridview that it shows that ROW SELECTED and Colored. Why ? i want fresh gridview with no record of previous selected data.
CODE:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int ComplainantTypeID = Convert.ToInt32(txtSelectedID.Text.Trim());
ComplainantTypeBizz comBizz = new ComplainantTypeBizz(txtName.Text);
ManageComplainantType mngComplainantType = new ManageComplainantType();
bool Result = mngComplainantType.Update(comBizz, ComplainantTypeID);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtName);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
You have to bind the data to the gridview (GridView.DataBind();) after you edit it in the RowUpdated event and set the GridView.SelectedIndex = -1; after each data bind to unselect any row in your grid.
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
GridView1.DataBind();
GridView1.SelectedIndex = -1;
}
Hope this helps.

Asp.net listview does not display data correctly

My problem is that when i display data in listview for first time then it show correctly but when i display data second time then listview does not update the data correctly. I have made a function for databinding with listview which i have called in pageLoad and some other method.
Can anyone please give me a solution about this ?
I have also uploaded my source code for more detail.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
protected void LoadDataIntoListView()
{
Users objQuery = new Users();
string adminID = "Here is my query to get the data from MS-SQL";
objQuery.ExecuteSql(str);
if (objQuery.RowCount > 0)
{
Title = "Row affected";
lstAppointments.Items.Clear();
lstAppointments.DataSource = objQuery.DefaultView;
lstAppointments.DataBind();
}
else
{
Title = "None Row affected";
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string caseID = (string)Session["caseID"];
//string updateQuery = "update Cases set sCaseStatus='cancel' where iCaseID= '" + caseID + "'";
Cases objCases = new Cases();
objCases.LoadByPrimaryKey(Convert.ToInt32(caseID));
if (String.Equals(objCases.SCaseStatus, "cancel"))
{
Page.Title = "No Update";
ModalPopupExtender1.Hide();
}
else
{
objCases.SCaseStatus = "cancel";
objCases.Save();
Page.Title = "No Update";
ModalPopupExtender1.Hide();
lstAppointments.Items.Clear();
LoadDataIntoListView();
}
}
Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
You are binding data in not Postback. That means it does not binds data when you postback to same page. If you want to bind that on every page load, call the function LoadDataIntoListView() in Page_Load

Two dropdown in a page ( conflict )

Two dropdownlists drop1, drop2 have separate selected index changed. Any dropdown, on selectedindexchanged, goes to another page. If we use back button in browser it goes back to our home page and one of dropdown will be selected position. If we change the other dropdown, it works only the first selected index changed in the coding section
How can we solve this problem?
code
protected void Page_Load(System.Object sender, System.EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
string zCenterId="0";
if(Request.QueryString["LCID"]!=null)
{
zCenterId = Request.QueryString["LCID"].ToString();
}
ManageActivityAdminUIController ObjCtrl = new ManageActivityAdminUIController();
List<ManageActivityAdminUIInfo> ObjInfo = ObjCtrl.GetActivityList(zCenterId );
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataBind();
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataTextField = "ActivityName";
drplistactivity.DataValueField = "ID";
drplistactivity.DataBind();
drplistactivity.Items.Insert(0, new ListItem("<--Select Activity-->", "0"));
ManageCoursesController ObjCtrl = new ManageCoursesController();
List<ManageCoursesInfo> ObjInfo = ObjCtrl.GetCourses(zCenterId );
drplistcourse.DataSource = ObjInfo;
drplistcourse.DataTextField = "CourseName";
drplistcourse.DataValueField = "ID";
drplistcourse.DataBind();
drplistcourse.Items.Insert(0, new ListItem("<--Select Course-->", "0"));
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void drplistactivity_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Activity.aspx?ActivityId="+drplistactivity.SelectedItem.Value);
Response.Redirect(url);
}
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}
If ViewState is off (on the dropdown or any of its parents - all the way up to the page) then the event won't fire. (It should post back though...)
The problem seems to be caused by the caching of your page.
I'd say that your two events are triggered, but you can not see it because of redirect
You may disable caching of your form :
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
Response.Expires = -1;
or you may test the eventtarget inside your eventhandlers
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
if(drplistcourse.UniqueID!=Request.Form["__EVENTTARGET"])
return;
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}

Categories

Resources