Pagination in gridview - c#

I would like to assign number of rows to my GridView.
Example:
GridView1.Rows.Count = 500;
More My code
using (CEntities context = new CEntities())
{
Users = context.Procedure(0,10).ToList<Procedure_Result>();
}
GridView1.UseAccessibleHeader = true;
GridView1.DataSource = Users;
GridView1.DataBind();
I will explain this problem much more clearly:
I wrote this context.Procedure(0,10) I get only 10 elements and one page. Normally I have 500 elements (rows). I search place where can I write value of all my rows. Otherwise I will not see other my pages.
Example of my problem in JTable Grid -> StudentsCount (I want make similar version in GridView to make this GridView very fast. Simple way I know. )
http://jtable.org/Tutorials/UsingWithAspNetWebFormsPageMethods
[WebMethod(EnableSession = true)]
public static object StudentList(int jtStartIndex, int jtPageSize, string jtSorting)
{
try
{
//Get data from database
int studentCount = Repository.StudentRepository.GetStudentCount();
List<Student> students = Repository.StudentRepository.GetStudents(jtStartIndex, jtPageSize, jtSorting);
//Return result to jTable
return new { Result = "OK", Records = students, TotalRecordCount = studentCount };
}
catch (Exception ex)
{
return new { Result = "ERROR", Message = ex.Message };
}
}

If you want to apply paging in your GridView.
You can try this.
Markup
<asp:GridView ID="gridview" AllowPaging="true" PageSize="10" OnPageIndexChanging="gridview_PageIndexChanging" runat="server" />
Code behind
protected void gridview_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//Fill grid here
gridview.PageIndex = e.NewPageIndex;
gridview.DataBind();
}

Related

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

Use textbox in gridview bound field in asp.net

I have a gridview which I used to display tabular data.
I want the users to edit the field values and save it.
Is there any way to add a textbox in place of bound field.
This is my gridview.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="186px" Width="325px">
<Columns>
</Columns>
</asp:GridView>
This is the code behind which populate the GridView
public List<DataControlField> columns = new List<DataControlField>();
public object DataSource { get; set; }
protected void Page_Init(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
BoundField bf = new BoundField() ;
bf.HeaderText = "LastName" ;
bf.DataField = "LastName";
columns.Add(bf);
}
foreach (DataControlField col in columns)
{
GridView1.Columns.Add(col);
}
}
protected void Page_Load(object sender, EventArgs e)
{
List<Data> lastN = new List<Data>() ;
for(int i = 0 ; i < 50; i++ )
{
lastN.Add(new Data(i.ToString()));
}
GridView1.DataSource = lastN;
GridView1.DataBind();
}
}
I would like to suggest you to try listview, it allows you to edit the dynamic data, such as the content in textbox
You can use a GridView with EditTemplates. You can refer to this example for that.
It is possible to edit all rows of a GridView at the same time. Refer to this example.
You can optionally use Telerik's ASP.NET Data Grid that you can configure to work like excel using this example.

Get new dropdownlist boxes On button click in asp.net c# with different Ids and assign datasource, along with selection changed functionality

I need to generate 3 DropDownList Boxes in a row Dynamically on ADD Button click event. Once the DDL is generated i should be able to assign Data source to it and also do DDL-selectedEventChanged functionality on them in c# asp.net.
Below link was exactly am looking for but i couldn't assign data source or i couldn't do any functionality
"Adding multiple DropDownLists with a button click"
any better Ideas please help
if i press Button i need to get 3 DDLs at a time, if i press again it should generate again, so number of clicks= no. of rows with three DDL's in each row
Here is the sample code. The only trick is that you need to load those dynamic controls again after post back. Otherwise, you won't be able to access those.
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:Button runat="server" ID="AddButton" OnClick="AddButton_Click" Text="Add" />
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
private List<string> DataSource
{
get { return new List<string> { "One", "Two", "Three" }; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var dataSource = DataSource;
foreach (int id in ControlIds)
{
var ddl = new DropDownList();
ddl.ID = id.ToString();
foreach (var data in dataSource)
ddl.Items.Add(new ListItem(data));
PlaceHolder1.Controls.Add(ddl);
}
}
}
protected void AddButton_Click(object sender, EventArgs e)
{
var dataSource = DataSource;
for (int i = 0; i < 3; i++)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var ddl = new DropDownList();
ddl.ID = id.ToString();
foreach (var data in dataSource)
ddl.Items.Add(new ListItem(data));
PlaceHolder1.Controls.Add(ddl);
}
}

ASP.NET C# trying to hide a link button

I am somewhat new to ASP.NET and I am confused by the syntax so I am a little lost. I am trying to hide/disable a button based on an if statement but I dont know how to disable or hide it. I have done C# before but this code looks unfamiliar to me.
Below is some of the code:
C# component:
protected override void Render(HtmlTextWriter writer)
{
string PostCtrl = Request.Params["__EVENTTARGET"];
if (PostCtrl == "AccColLocation_content$collisionLocation$EditColLocation")
{
valDropDownlist(((CustomControl.DropDownValidator)collisionLocation.FindControl("valLoc_municipality")), "CollisionLocation.municipality");
..............
}
}
HTML:
<ItemTemplate>
<asp:LinkButton ID="EditColLocation" runat="server" Text="Edit Collision Location" OnClick="CollisionLocation_Edit" />
</ItemTemplate>
valDropDownList Method:
protected void valDropDownlist(CustomControl.DropDownValidator valDropdown, string DataElement)
{
try
{
bool mvarRequired, srRequired;
DataTable dtDataElement = DBFunctions.DBFunctions.getDataElement(RepDateTime, DataElement);
string s = dtDataElement.Rows[0]["mvarRequired"].ToString();
mvarRequired = (dtDataElement.Rows[0]["mvarRequired"].ToString() == "True") ? true : false;
srRequired = (dtDataElement.Rows[0]["srRequired"].ToString() == "True") ? true : false;
valDropdown.HaveToSelect = (SelfReported) ? srRequired : mvarRequired;
}
catch (Exception err)
{
MessageBox("An error occurred while setting drop down validation rules. " + err.ToString());
}
}
All these buttons are in grid view.
I have something of this nature:
protected void deletedr(object sender, EventArgs e)
{
try
{
GridView gv = (GridView)FindControl("DriverInfo");
gv.DataSource = DBFunctions.DBFunctions.getInfo(ReportID.Value, "", 2); ;
gv.DataBind();
bool isSelectedLast = false;
DataTable dt = DBFunctions.DBFunctions.getInfo(ReportID.Value, "", 2);
if (dlDriverNo.SelectedValue == dt.Rows[dt.Rows.Count - 1]["DriverNo"].ToString())
{
isSelectedLast = true;
}
if (!(DBFunctions.DBFunctions.deleteDriver(ReportID.Value, dlDriverNo.SelectedValue, isSelectedLast)))
{
MessageBox(null);
}
else
{
dlDriverNo.Visible = false;
lblDelDriver.Visible = false;
delDriverconfim.Visible = false;
cancelDel.Visible = false;
dlDriverNo.Items.Clear();
gv.DataSource = DBFunctions.DBFunctions.getInfo(ReportID.Value, "", 2);
gv.DataBind();
}
}
catch (Exception err)
{
MessageBox("An error occurred while deleting the driver. " + err.ToString());
}
}
If your LinkButton is in a GridView, the most interesting problem is getting a handle on it. After you have a handle you can just set it to invisible or disabled:
linkButton.Visible = false;
or
linkButton.Enabled = false;
But to get a handle to the LinkButton control you will need to use .FindControl in a suitable event on the GridView control:
<asp:GridView ID="myGridView" runat="server" OnRowDataBound="myGridView_RowDataBound">
...
</aspGridView>
Then in the code behind you would have:
protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
var linkButton = (LinkButton)e.Row.FindControl("EditColLocation");
if (linkButton != null)
{
if (*your condition to check*)
linkButton.Visible = false;
}
}
Hope this will get you moving in the right direction.
you can try
valDropdown.Visible = false; //Mask the control
After the if condition write the below code.
Buttonname.visible=false;

Deleting 11th row in RadGrid makes it become blank

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..

Categories

Resources