I'm trying to implement custom paging on a GridView but getting odd behaviour when the last page is being displayed. I thought it might be becuase I had implemented it manually by extending the 4.0 GridView control, but I've now tried using the 4.5 features as per http://www.c-sharpcorner.com/UploadFile/99bb20/custom-paging-with-gridview-control-in-Asp-Net-4-5/ but it is displaying exactly the same behaviour.
Basically if the item count of the last page is less than the PageSize then whenever the grid posts back it fills up with empty rows, as seen below:
Page markup:
<asp:GridView ID="gvTest" runat="server" PageSize="10" AllowPaging="true" AllowCustomPaging="true" AutoGenerateColumns="false" OnRowCommand="gvTest_RowCommand" OnPageIndexChanging="gvTest_PageIndexChanging">
<Columns>
<asp:BoundField DataField="ItemText" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnTest" runat="server" Text="Test postback" CommandName="TEST" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
BindData();
}
}
private void BindData() {
List<TestItem> items = new List<TestItem>() {
new TestItem() { ItemText = "Item1" },
new TestItem() { ItemText = "Item2" },
new TestItem() { ItemText = "Item3" },
new TestItem() { ItemText = "Item4" },
new TestItem() { ItemText = "Item5" },
new TestItem() { ItemText = "Item6" },
new TestItem() { ItemText = "Item7" },
new TestItem() { ItemText = "Item8" },
new TestItem() { ItemText = "Item9" },
new TestItem() { ItemText = "Item10" },
new TestItem() { ItemText = "Item11" },
new TestItem() { ItemText = "Item12" }
};
gvTest.DataSource = items.Skip(gvTest.PageIndex * gvTest.PageSize).Take(gvTest.PageSize).ToList();
gvTest.VirtualItemCount = items.Count;
gvTest.DataBind();
}
protected void gvTest_PageIndexChanging(object sender, GridViewPageEventArgs e) {
gvTest.PageIndex = e.NewPageIndex;
BindData();
}
All works as expected, but clicking on a linkbutton on the 2nd (last) page results in the following:
Before postback:
After postback:
Is this a known GridView issue? Not sure what I'm doing wrong....
Hahaha, just noticed this is a relatively old question. Hopefully it helps someone though!
Is it something related to your OnRowCommand? I took out the OnRowCommand since I don't know what you are doing in that block. Otherwise the code works fine
I ran the following code:
aspx page:
<asp:GridView ID="gvTest" runat="server" PageSize="10" AllowPaging="true" AllowCustomPaging="true" AutoGenerateColumns="false" OnPageIndexChanging="gvTest_PageIndexChanging">
<Columns>
<asp:BoundField DataField="ItemText" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnTest" runat="server" Text="Test postback" CommandName="TEST" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind with mock class:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
List<TestItem> items = new List<TestItem>()
{
new TestItem() {ItemText = "Item1"},
new TestItem() {ItemText = "Item2"},
new TestItem() {ItemText = "Item3"},
new TestItem() {ItemText = "Item4"},
new TestItem() {ItemText = "Item5"},
new TestItem() {ItemText = "Item6"},
new TestItem() {ItemText = "Item7"},
new TestItem() {ItemText = "Item8"},
new TestItem() {ItemText = "Item9"},
new TestItem() {ItemText = "Item10"},
new TestItem() {ItemText = "Item11"},
new TestItem() {ItemText = "Item12"}
};
gvTest.DataSource = items.Skip(gvTest.PageIndex * gvTest.PageSize).Take(gvTest.PageSize).ToList();
gvTest.VirtualItemCount = items.Count;
gvTest.DataBind();
}
protected void gvTest_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvTest.PageIndex = e.NewPageIndex;
BindData();
}
}
public class TestItem
{
public string ItemText { get; set; }
}
Which resulted in:
Page 1:
Page 2:
I used this way to avoid this problem
but this is not a good way...
private int gvDataCount
{
get
{
object count = ViewState["gvDataCount"];
if (count == null)
count = gvTest.PageSize;
return Convert.ToInt32(count);
}
set
{
ViewState["gvDataCount"] = value;
}
}
private void BindData()
{
//....
var list = items.Skip(gvTest.PageIndex * gvTest.PageSize).Take(gvTest.PageSize).ToList();
this.gvDataCount = list.Count;
gvTest.DataSource = list;
gvTest.VirtualItemCount = items.Count;
gvTest.DataBind();
}
protected void gvTest_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
if (e.Row.RowIndex > this.gvDataCount)
e.Row.Visible = false;
}
Related
I need to create dynamic form, which i will have to create the textbox, textarea,dropdown etc, based on the field type.
Now, I have successfully created this dynamic textbox etc using my rowdatabound.
My problem is I could not retrieve the textbox value entered when the save button is clicked.
My aspx file
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="selectProspect" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FieldTitle" HeaderText="" />
<asp:BoundField DataField="FieldType" HeaderText="FieldType" />
<asp:TemplateField>
<ItemTemplate>
//DYNAMICALLY ADDING TEXTBOX
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RightText" HeaderText="" />
<asp:BoundField DataField="TemplatesInfoCode" HeaderText="TemplatesInfoCode" ItemStyle-CssClass="hiddencol" />
</Columns>
</asp:GridView>
My code behind file
protected void Page_Load(object sender, EventArgs e)
{
GetTemplateComponent();
}
public void GetTemplateComponent()
{
StringBuilder sb;
DataSet ds;
sb = new StringBuilder();
sb.AppendLine("select * from template where tc='0002' order by Sequence");
ds = Conn.DataAdapter(CommandType.Text, sb.ToString());
gv.DataSource = ds;
gv.DataBind();
}
protected void gv_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string value = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "FieldType"));
if (value == "Date" || value == "TextBox")
{
TextBox TextBox1 = new TextBox() { ID = "TextBox1", EnableViewState = false, CssClass = "form-control" };
e.Row.Cells[3].Controls.Add(TextBox1);
}
if (value == "TextArea")
{
TextBox DateTextBox = new TextBox() { EnableViewState = false, CssClass = "form-control", TextMode = TextBoxMode.MultiLine, Rows = 5, Columns = 50 };
e.Row.Cells[3].Controls.Add(DateTextBox);
}
if (value == "Content")
{
TextBox ContentAreaControl = new TextBox()
{
TextMode = TextBoxMode.MultiLine,
EnableViewState = false,
Columns = 10,
MaxLength = 150,
Height = 200,
CssClass = "Content-container",
};
e.Row.Cells[3].Controls.Add(ContentAreaControl);
}
}
}
protected void SaveTemplateDetails(object sender, EventArgs e)
{
foreach (GridViewRow row in gv.Rows)
{
FieldValue.Value = row.Cells[3].Text.ToString();
*//I DONT KNOW HOW TO READ THE VALUE*
}
}
I just want to know how is the proper way to read this dynamically created textbox
Thank you
ASPX Page Code.
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDataBound="gv_RowDataBound1">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="selectProspect" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FieldTitle" HeaderText="" />
<asp:BoundField DataField="FieldType" HeaderText="FieldType" />
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RightText" HeaderText="" />
<asp:BoundField DataField="TemplatesInfoCode" HeaderText="TemplatesInfoCode" />
</Columns>
</asp:GridView>
Code behind file
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string fieldType = e.Row.Cells[2].Text;
TextBox txtData = e.Row.Cells[3].FindControl("TextBox1") as TextBox;
switch (fieldType)
{
case "Date":
case "TextBox":
txtData.EnableViewState = false;
txtData.CssClass = "form-control";
break;
case "TextArea":
txtData.EnableViewState = false;
txtData.CssClass = "form-control";
txtData.TextMode = TextBoxMode.MultiLine;
txtData.Rows = 5;
txtData.Columns = 50;
break;
case "Content":
txtData.TextMode = TextBoxMode.MultiLine;
txtData.EnableViewState = false;
txtData.Columns = 10;
txtData.MaxLength = 150;
txtData.Height = 200;
txtData.CssClass = "Content-container";
break;
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveTemplateDetails();
}
private void SaveTemplateDetails()
{
foreach (GridViewRow row in gv.Rows)
{
foreach (Control c in row.Cells[3].Controls)
{
TextBox txtDate = c as TextBox;
if (txtDate != null)
{
string data = txtDate.Text;
}
}
}
}
I have this RadioButtonList
<asp:RadioButtonList runat="server" ID="loanTypeCheck" CssClass="pull-right" RepeatDirection="Horizontal">
<asp:ListItem Value="Cash" Text=" Cash "/>
<asp:ListItem Value="Non-Cash" Text=" Non-Cash " />
<asp:ListItem Value="Dharauti" Text=" Dharauti " />
</asp:RadioButtonList>
And in Code Behind in my save button event
protected void SaveButton_Click(object sender, EventArgs e)
{
if (IsFormValidForSave())
{
var loanReceipt = GetLoanReceiptFromForm();
var transactionsDetails = new List<TransactionDetail>();
var loantypeCheck = loanTypeCheck.SelectedValue;
//if (IsCashReceipt)
if (loantypeCheck == "Cash")
{
var transaction = new Transaction()
{
AuditUserId = UserId,
OfficeId = OfficeId,
VerificationStatusId = 0,
BookName = EverestEnums.TransactionBookName.LoanReceipt,
BookNameString = EverestEnums.TransactionBookName.LoanReceipt.ToString(),
TranDateString = DateConversion.GetCurrentServerDate().ToString(),
ValueDateString = ValueDateControl.ValueDateAd.ToString(),
TellerId = UserId,
TotalAmount = SubmittedAmountTextBox.Text.ToDecimal(),
ValueDate = ValueDateControl.ValueDateAd,
TranDate = DateConversion.GetCurrentServerDate(),
};
i am getting null value for the radio button.Am i missing something?
i have a telerik grid and use GridTemplateColumn as bellow
<telerik:GridTemplateColumn DataField="Status" ReadOnly="true" UniqueName="colStatus" HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpstatus" runat="server" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
then i fill dropdown and label in ItemDataBound event :
protected void grdList_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem editItem = (GridEditableItem)e.Item;
var info = (ProductViewInfo)e.Item.DataItem;
DropDownList drpstatus = (DropDownList)editItem["colStatus"].FindControl("drpstatus");
var cntType = new ProductTypeController();
var lst = cntType.GetStatusList(PortalId, enumTypes.MainGroup);
drpstatus.DataSource = lst;
drpstatus.DataTextField = "Caption";
drpstatus.DataValueField = "StatusID";
drpstatus.DataBind();
drpstatus.SelectedValue = info.Status.ToString();
}
else
{
var item = e.Item as GridDataItem;
var info = (ProductViewInfo)item.DataItem;
Label lblStatus = (Label)item["colStatus"].FindControl("lblStatus");
lblStatus.Text = info.StatusCaption;
}
}
}
but my drop down does not fill! "e.Item.IsInEditMode" always returns false. should i add anything else in order to fill dropdown?
I guess the problem related to ReadOnly="true"
try to remove it
This is homework, a Website to rate doctors, using Visual Studio in C#. I have a GridView that gets data from a repository. The DoctorPicture column should display a picture that is in my Images folder, not a string. When I run the page with the GridView, an error says, "A field or property with the name 'Images' was not found on the selected data source." This is my GridView:
<asp:ObjectDataSource ID="ObjectDataSourceDoctor" runat="server" DataObjectTypeName="MidtermApplication.Models.Doctor" DeleteMethod="Remove" InsertMethod="Add" SelectMethod="GetItems" TypeName="MidtermApplication.Models.TestDoctorRepository" UpdateMethod="Update"></asp:ObjectDataSource>
<asp:GridView ID="GridViewDoctor" runat="server" DataSourceID="ObjectDataSourceDoctor" DataKeyNames="DoctorPicture" AutoGenerateColumns="False">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="DoctorName" HeaderText="DoctorName" SortExpression="DoctorName" />
<asp:BoundField DataField="DoctorSpecialty" HeaderText="DoctorSpecialty" SortExpression="DoctorSpecialty" />
<asp:BoundField DataField="rating" HeaderText="rating" SortExpression="rating" />
<asp:BoundField DataField="times" HeaderText="times" SortExpression="times" />
<asp:CheckBoxField DataField="fave" HeaderText="fave" SortExpression="fave" />
<asp:CheckBoxField DataField="rated" HeaderText="rated" SortExpression="rated" />
<asp:ImageField DataImageUrlField="Images" HeaderText="DoctorPicture">
</asp:ImageField>
</Columns>
</asp:GridView>
Here is where the data is coming from (I think):
public class TestDoctorRepository : IDoctorRepository
{
List<Doctor> doctors;
public TestDoctorRepository()
{
doctors = new List<Doctor> {
new Doctor { DoctorPicture = "Images/0cropped.jpg", DoctorName = "Michael Shores", DoctorSpecialty = "Opthamology", times = 0, rating = 0, rated = true, fave = true },
new Doctor { DoctorPicture = "Images/1cropped.jpg", DoctorName = "Ming Wu", DoctorSpecialty = "Cardiology", times = 0, rating = 0, rated = true, fave = true },
new Doctor { DoctorPicture = "Images/1bcropped.jpg", DoctorName = "Susan McInerney", DoctorSpecialty = "Gynecology", times = 0, rating = 0, rated = true, fave = true },
new Doctor { DoctorPicture = "Images/2cropped.jpg", DoctorName = "Michelle Adkins", DoctorSpecialty = "Dermatology", times = 0, rating = 0, rated = true, fave = true },
new Doctor { DoctorPicture = "Images/5cropped.jpg", DoctorName = "Kathy Powers", DoctorSpecialty = "Chiropractor", times = 0, rating = 0, rated = true, fave = true }
};
}
"A field or property with the name 'Images' was not found on the
selected data source."
Error explains the reason, if there is no 'Images' property then which property can be set as DataImageUrlField?
try by changing DataImageUrlField="Images" to DataImageUrlField="DoctorPicture"
<asp:ImageField DataImageUrlField="DoctorPicture" HeaderText="DoctorPicture">
I'm using radlistview in my asp.net project . The problem that when I have to get all items of radlistview it return only items of the current page.
Example :
radlistview2.Items.ToList();
Output :
I got only 10 elements which are in the first page
My Question is :
How To get all items in radlistview ???
Please try with the below code snippet.
ASPX
<telerik:RadListView ID="RadListView1" runat="server" OnNeedDataSource="RadListView1_NeedDataSource" AllowPaging="true" PageSize="2">
<ItemTemplate>
<%# Eval("ID") %>
</ItemTemplate>
</telerik:RadListView>
<telerik:RadDataPager ID="RadDataPager1" runat="server" PagedControlID="RadListView1"
PageSize="2">
<Fields>
<telerik:RadDataPagerButtonField FieldType="FirstPrev"></telerik:RadDataPagerButtonField>
<telerik:RadDataPagerButtonField FieldType="Numeric"></telerik:RadDataPagerButtonField>
<telerik:RadDataPagerButtonField FieldType="NextLast"></telerik:RadDataPagerButtonField>
</Fields>
</telerik:RadDataPager>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
ASPX.CS
protected void RadListView1_NeedDataSource(object sender, RadListViewNeedDataSourceEventArgs e)
{
dynamic data1 = new[] {
new { ID = 1, Name ="Name_1",Customdate = DateTime.Now},
new { ID = 2, Name = "Name_2",Customdate = DateTime.Now},
new { ID = 3, Name = "Name_3",Customdate = DateTime.Now},
new { ID = 4, Name = "Name_4",Customdate = DateTime.Now},
new { ID = 5, Name = "Name_5",Customdate = DateTime.Now}
};
RadListView1.DataSource = data1;
}
protected void Button1_Click(object sender, EventArgs e)
{
int i = RadListView1.Items.Count();
RadListView1.AllowPaging = false;
RadListView1.Rebind();
int j = RadListView1.Items.Count();
//Access your count here
RadListView1.AllowPaging = true;
RadListView1.Rebind();
}